<?php

/**
 * Admin Departments Management API
 * Handles CRUD operations for departments
 */
require_once 'config/database.php';
require_once 'utils/helpers.php';

try {
    // Get and verify token
    $token = Helpers::getBearerToken();
    $userData = Helpers::verifyJWT($token);

    if (!$userData) {
        Helpers::sendResponse(false, 'Unauthorized access', null, 401);
    }

    $database = new Database();
    $db = $database->getConnection();

    // Verify admin access
    $query = "SELECT ur.role_level FROM users u JOIN user_roles ur ON u.role_id = ur.id WHERE u.id = :user_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $userData['user_id']);
    $stmt->execute();
    $userRole = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$userRole || $userRole['role_level'] < 4) {
        Helpers::sendResponse(false, 'Unauthorized. Admin access required.', null, 403);
    }

    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

    // GET: Retrieve departments
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        handleGet($db);
    }

    // POST: Create or update department
    elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        handleCreate($db, $userData);
    }

    // PATCH: Archive/Restore department
    elseif ($_SERVER['REQUEST_METHOD'] === 'PATCH') {
        handleUpdate($db, $userData);
    }

    // DELETE: Delete department
    elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
        handleDelete($db, $userData);
    }

    // Not allowed method
    else {
        Helpers::sendResponse(false, 'Method not allowed', null, 405);
    }
} catch (PDOException $e) {
    ErrorLogger::logDatabaseError($e, $userData['user_id'] ?? 'unknown', [
        'endpoint' => 'admin/departments',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'Database error in departments management: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    ErrorLogger::logError($e, [
        'endpoint' => 'admin/departments',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'Error in departments management: ' . $e->getMessage(), null, 500);
}

function handleGet($db)
{
    // $includeInactive = isset($_GET['include_inactive']) ? filter_var($_GET['include_inactive'], FILTER_VALIDATE_BOOLEAN) : false;
    // $whereClause = $includeInactive ? '' : 'WHERE d.is_active = TRUE';

    $query = "SELECT d.`id`, d.`name`, d.`description`, d.`is_active`, d.created_at, d.updated_at,
                         COUNT(DISTINCT u.id) as member_count,
                         COUNT(DISTINCT CASE WHEN u.is_hod = TRUE THEN u.id END) as hod_count,
                         GROUP_CONCAT(DISTINCT CASE WHEN u.is_hod = TRUE 
                              THEN CONCAT(u.first_name, ' ', u.last_name) END 
                              SEPARATOR ', ') as hods
                  FROM departments d
                  LEFT JOIN users u ON d.id = u.department_id AND u.is_active = TRUE 
                  GROUP BY d.id
                  ORDER BY d.name ASC";

    $stmt = $db->prepare($query);
    $stmt->execute();
    $departments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    Helpers::sendResponse(true, 'Departments retrieved successfully', [
        'departments' => $departments,
        'count' => count($departments)
    ]);
}

function handleCreate($db, $userData)
{
    $data = json_decode(file_get_contents("php://input"));

    if (empty($data->name)) {
        Helpers::sendResponse(false, 'Department name is required', null, 400);
    }

    // Check if this is an update (id provided)
    if (!empty($data->id)) {
        // Check if department exists
        $query = "SELECT id, name FROM departments WHERE id = :id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $data->id);
        $stmt->execute();

        if ($stmt->rowCount() === 0) {
            Helpers::sendResponse(false, 'Department not found', null, 404);
        }

        // Check if name already exists (excluding current department)
        $query = "SELECT id FROM departments WHERE name = :name AND id != :id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':name', $data->name);
        $stmt->bindParam(':id', $data->id);
        $stmt->execute();

        if ($stmt->rowCount() > 0) {
            Helpers::sendResponse(false, 'Department name already exists', null, 409);
        }

        // Update existing department
        $query = "UPDATE departments 
                      SET name = :name, description = :description, updated_at = NOW() 
                      WHERE id = :id";

        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $data->id);
        $stmt->bindParam(':name', $data->name);
        $description = $data->description ?? '';
        $stmt->bindParam(':description', $description);

        if ($stmt->execute()) {
            // Log admin activity
            Helpers::logAdminAction(
                $db,
                $userData['user_id'],
                'update_department',
                'update',
                'department',
                $data->id,
                json_encode(['name' => $data->name])
            );
            Helpers::sendResponse(true, 'Department updated successfully');
        } else {
            Helpers::sendResponse(false, 'Failed to update department', null, 500);
        }
    } else {
        // Check if name already exists
        $query = "SELECT id FROM departments WHERE name = :name";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':name', $data->name);
        $stmt->execute();

        if ($stmt->rowCount() > 0) {
            Helpers::sendResponse(false, 'Department name already exists', null, 409);
        }

        // Create new department
        $query = "INSERT INTO departments (name, description, is_active, created_at) 
                      VALUES (:name, :description, TRUE, NOW())";

        $stmt = $db->prepare($query);
        $stmt->bindParam(':name', $data->name);
        $description = $data->description ?? '';
        $stmt->bindParam(':description', $description);

        if ($stmt->execute()) {
            $newDeptId = $db->lastInsertId();

            // Log admin activity
            Helpers::logAdminAction(
                $db,
                $userData['user_id'],
                'create_department',
                'create',
                'department',
                $newDeptId,
                json_encode(['name' => $data->name])
            );
            $logQuery = "INSERT INTO admin_logs 
                            (admin_id, action, action_type, target_type, target_id, details, ip_address, created_at) 
                            VALUES 
                            (:admin_id, 'create_department', 'create', 'department', :dept_id, :details, :ip, NOW())";

            Helpers::sendResponse(true, 'Department created successfully', [
                'department_id' => $newDeptId
            ], 201);
        } else {
            Helpers::sendResponse(false, 'Failed to create department', null, 500);
        }
    }
}

function handleUpdate($db, $userData)
{
    $data = json_decode(file_get_contents("php://input"));

    if (empty($data->id) || !isset($data->action)) {
        Helpers::sendResponse(false, 'Department ID or action is required', null, 400);
    }

    // Check if department exists
    $query = "SELECT `id`, `name`, `is_active` FROM `departments` WHERE `id` = :id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':id', $data->id);
    $stmt->execute();
    $dept = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$dept) {
        Helpers::sendResponse(false, 'Department not found', null, 404);
    }

    // Update department status
    $query = "UPDATE `departments` SET `is_active` = :is_active, `updated_at` = NOW() WHERE `id` = :id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':id', $data->id);
    $isActive = $data->action == "archive" ? false : true;
    $stmt->bindParam(':is_active', $isActive, PDO::PARAM_BOOL);

    if ($stmt->execute()) {
        // Log admin activity
        Helpers::logAdminAction(
            $db,
            $userData['user_id'],
            $isActive ? 'restore_department' : 'archive_department',
            'update',
            'department',
            $data->id,
            json_encode(['name' => $dept['name'], 'is_active' => $isActive])
        );
        $message = $isActive ? 'Department restored successfully' : 'Department archived successfully';
        Helpers::sendResponse(true, $message);
    } else {
        Helpers::sendResponse(false, 'Failed to update department status', null, 500);
    }
}

function handleDelete($db, $userData)
{
    $data = json_decode(file_get_contents("php://input"));
    $deptId = isset($data->id) ? intval($data->id) : null;

    if (!$deptId) {
        Helpers::sendResponse(false, 'Department ID is required', null, 400);
    }

    // Check if department has users
    $query = "SELECT COUNT(*) as user_count FROM users WHERE department_id = :dept_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':dept_id', $deptId);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result['user_count'] > 0) {
        Helpers::sendResponse(false, 'Cannot delete department with assigned users. Please reassign users first.', null, 400);
    }

    // Get department info before deletion
    $query = "SELECT name FROM departments WHERE id = :dept_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':dept_id', $deptId);
    $stmt->execute();
    $dept = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$dept) {
        Helpers::sendResponse(false, 'Department not found', null, 404);
    }

    // Delete department
    $query = "DELETE FROM departments WHERE id = :dept_id";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':dept_id', $deptId);

    if ($stmt->execute()) {
        // Log admin activity
        Helpers::logAdminAction(
            $db,
            $userData['user_id'],
            'delete_department',
            'delete',
            'department',
            $deptId,
            json_encode(['name' => $dept['name']])
        );
        Helpers::sendResponse(true, 'Department deleted successfully');
    } else {
        Helpers::sendResponse(false, 'Failed to delete department', null, 500);
    }
}
