<?php
// api/hod_assignments.php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/performance_common.php';

try {
    rvu_perf_ensure_tables($pdo);
    $user = rvu_perf_require_user($pdo);
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
    $input = rvu_perf_input();

    if ($method === 'GET') {
        $isAdmin = rvu_perf_role_is_admin((string)($user['role'] ?? ''));
        $history = $isAdmin && in_array(strtolower((string)($_GET['history'] ?? '')), ['1','true','yes'], true);

        if ($isAdmin) {
            $sql = "SELECT a.*,
                           s.full_name AS staff_name,
                           s.email AS staff_email,
                           b.full_name AS assigned_by_name
                    FROM student_performance_hod_assignments a
                    LEFT JOIN users s ON s.id = a.staff_user_id
                    LEFT JOIN users b ON b.id = a.assigned_by";
            if (!$history) $sql .= ' WHERE a.is_active = TRUE';
            $sql .= ' ORDER BY a.campus, a.department_name, a.assigned_at DESC';
            $rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } else {
            $stmt = $pdo->prepare("SELECT a.*,
                                         s.full_name AS staff_name,
                                         s.email AS staff_email,
                                         b.full_name AS assigned_by_name
                                  FROM student_performance_hod_assignments a
                                  LEFT JOIN users s ON s.id = a.staff_user_id
                                  LEFT JOIN users b ON b.id = a.assigned_by
                                  WHERE a.staff_user_id = ?
                                    AND a.is_active = TRUE
                                    AND LOWER(a.campus) = LOWER(?)
                                    AND LOWER(a.department_name) = LOWER(?)
                                  ORDER BY a.campus, a.department_name");
            $stmt->execute([
                (int)$user['id'],
                trim((string)($user['campus'] ?? '')),
                trim((string)($user['program'] ?? '')),
            ]);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        }

        rvu_perf_json([
            'data' => array_map('rvu_perf_assignment_public', $rows),
            'is_admin' => $isAdmin,
        ]);
    }

    if ($method === 'POST') {
        rvu_perf_require_admin($user);

        $departmentId = (int)($input['department_id'] ?? 0);
        $staffId = (int)($input['staff_user_id'] ?? 0);
        $campus = rvu_perf_clean_text($input['campus'] ?? '', 255);

        if ($departmentId <= 0 || $staffId <= 0 || $campus === '') {
            rvu_perf_json(['detail' => 'Department, campus and staff member are required.'], 422);
        }

        $department = rvu_perf_department($pdo, $departmentId);
        if (!$department) rvu_perf_json(['detail' => 'The selected department does not exist in the departments database.'], 404);

        $staff = rvu_perf_staff($pdo, $staffId);
        if (!$staff) rvu_perf_json(['detail' => 'The selected staff member does not exist.'], 404);
        if (strtolower(trim((string)$staff['role'])) !== 'staff') {
            rvu_perf_json(['detail' => 'Only a staff account can be assigned as HOD.'], 422);
        }

        $staffCampus = trim((string)($staff['campus'] ?? ''));
        $staffDepartment = trim((string)($staff['program'] ?? ''));
        $departmentName = trim((string)$department['name']);

        if ($staffCampus === '' || strcasecmp($staffCampus, $campus) !== 0) {
            rvu_perf_json(['detail' => 'The selected staff member must belong to the selected campus.'], 422);
        }
        if ($staffDepartment === '' || strcasecmp($staffDepartment, $departmentName) !== 0) {
            rvu_perf_json(['detail' => 'The selected staff member must belong to the selected department.'], 422);
        }

        $pdo->beginTransaction();
        $close = $pdo->prepare("UPDATE student_performance_hod_assignments
                                SET is_active = FALSE, ended_at = CURRENT_TIMESTAMP
                                WHERE campus = ? AND department_id = ? AND is_active = TRUE");
        $close->execute([$campus, $departmentId]);

        $insert = $pdo->prepare("INSERT INTO student_performance_hod_assignments
            (department_id, department_name, campus, school, staff_user_id, assigned_by)
            VALUES (?, ?, ?, ?, ?, ?)
            RETURNING id, assigned_at");
        $insert->execute([
            $departmentId,
            $departmentName,
            $campus,
            trim((string)($staff['school'] ?? '')) ?: null,
            $staffId,
            (int)$user['id'],
        ]);
        $created = $insert->fetch(PDO::FETCH_ASSOC);
        $pdo->commit();

        rvu_perf_json([
            'message' => $staff['full_name'] . ' is now the HOD for ' . $departmentName . ' at ' . $campus . '.',
            'id' => (int)$created['id'],
            'assigned_at' => $created['assigned_at'],
        ], 201);
    }

    if ($method === 'DELETE') {
        rvu_perf_require_admin($user);
        $id = (int)($_GET['id'] ?? $input['id'] ?? 0);
        if ($id <= 0) rvu_perf_json(['detail' => 'A valid assignment id is required.'], 422);

        $stmt = $pdo->prepare("UPDATE student_performance_hod_assignments
                               SET is_active = FALSE, ended_at = CURRENT_TIMESTAMP
                               WHERE id = ? AND is_active = TRUE");
        $stmt->execute([$id]);
        if ($stmt->rowCount() === 0) rvu_perf_json(['detail' => 'Active HOD assignment not found.'], 404);
        rvu_perf_json(['message' => 'HOD assignment ended successfully.']);
    }

    rvu_perf_json(['detail' => 'Unsupported request.'], 405);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    rvu_perf_json(['detail' => 'HOD assignment server error: ' . $e->getMessage()], 500);
}
