<?php
// api/departments.php
// University-wide department directory with one HOD assignment per campus.

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/session_auth.php';
rvu_audit_context_from_request($pdo);
header('Content-Type: application/json; charset=UTF-8');

function departmentRespond(int $code, $body = null): void {
    http_response_code($code);
    if ($body !== null) {
        echo json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
    }
    exit;
}

function departmentClean($value, int $max = 0): string {
    $text = trim((string)($value ?? ''));
    $text = preg_replace('/\s+/', ' ', $text);
    if ($max > 0 && mb_strlen($text) > $max) {
        $text = mb_substr($text, 0, $max);
    }
    return $text;
}

function departmentNorm($value): string {
    return mb_strtoupper(departmentClean($value), 'UTF-8');
}

function departmentCampusKey($value): string {
    $n = departmentNorm($value);
    if ($n === '') return '';
    if (strpos($n, 'MANSA') !== false) return 'MANSA';
    if (strpos($n, 'NDOLA') !== false) return 'NDOLA';
    if (strpos($n, 'CHIPATA') !== false) return 'CHIPATA';
    if (strpos($n, 'LIVINGSTONE') !== false) return 'LIVINGSTONE';
    if (strpos($n, 'E-LEARNING') !== false || strpos($n, 'ELEARNING') !== false || strpos($n, 'ONLINE') !== false) return 'E-LEARNING';
    if (strpos($n, '10 MILES') !== false || strpos($n, 'TEN MILES') !== false) return '10 MILES';
    if ($n === 'HQ' || $n === 'HQ CAMPUS' || strpos($n, 'HEAD QUART') !== false || strpos($n, 'HEADQUART') !== false || strpos($n, 'HEAD OFFICE') !== false) return 'HQ';
    return $n;
}

function departmentTableExists(PDO $pdo, string $table): bool {
    $stmt = $pdo->prepare("SELECT 1 FROM information_schema.tables WHERE table_schema = current_schema() AND table_name = ? LIMIT 1");
    $stmt->execute([$table]);
    return (bool)$stmt->fetchColumn();
}

function departmentColumns(PDO $pdo, string $table): array {
    $stmt = $pdo->prepare("SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position");
    $stmt->execute([$table]);
    return $stmt->fetchAll(PDO::FETCH_COLUMN) ?: [];
}

function departmentEnsureHodTable(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS department_hods (
        id BIGSERIAL PRIMARY KEY,
        department_id BIGINT NOT NULL REFERENCES departments(id) ON DELETE CASCADE,
        campus VARCHAR(180) NOT NULL,
        user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    // A department may have exactly one HOD for each logical campus.
    $pdo->exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_department_hods_department_campus
        ON department_hods (department_id, UPPER(TRIM(campus)))");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_department_hods_user ON department_hods (user_id, department_id)");
}

function departmentCampusRows(PDO $pdo): array {
    $values = [];

    // The campuses table is the ONLY authoritative source of university campuses.
    // Never create department/HOD campus cards from free-text values stored on users.
    if (!departmentTableExists($pdo, 'campuses')) {
        return [];
    }

    $columns = departmentColumns($pdo, 'campuses');
    $nameField = in_array('name', $columns, true)
        ? 'name'
        : (in_array('campus_name', $columns, true) ? 'campus_name' : null);

    if ($nameField === null) {
        return [];
    }

    $quoted = '"' . str_replace('"', '""', $nameField) . '"';
    $stmt = $pdo->query("SELECT $quoted AS campus FROM campuses WHERE $quoted IS NOT NULL AND TRIM($quoted) <> '' ORDER BY $quoted ASC");
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $campus = departmentClean($row['campus'] ?? '', 180);
        $key = departmentCampusKey($campus);
        if ($key !== '') $values[$key] = $campus;
    }

    return array_values($values);
}

function departmentCandidateRows(PDO $pdo): array {
    if (!departmentTableExists($pdo, 'users')) return [];

    // HOD candidates must belong to a campus that actually exists in the
    // authoritative campuses table. Stale free-text campuses on users are ignored.
    $officialCampuses = [];
    foreach (departmentCampusRows($pdo) as $campus) {
        $officialCampuses[departmentCampusKey($campus)] = $campus;
    }
    if (!$officialCampuses) return [];

    $columns = departmentColumns($pdo, 'users');
    $select = ['id'];
    foreach (['full_name', 'email', 'role', 'campus', 'school', 'program', 'position'] as $field) {
        if (in_array($field, $columns, true)) $select[] = '"' . $field . '"';
    }

    $stmt = $pdo->query('SELECT ' . implode(', ', $select) . ' FROM users ORDER BY ' . (in_array('full_name', $columns, true) ? 'full_name' : 'id') . ' ASC');
    $rows = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $campus = departmentClean($row['campus'] ?? '', 180);
        if ($campus === '') continue;

        $campusKey = departmentCampusKey($campus);
        if ($campusKey === '' || !isset($officialCampuses[$campusKey])) continue;

        $row['id'] = (int)$row['id'];
        $row['full_name'] = departmentClean($row['full_name'] ?? '', 255);
        $row['email'] = departmentClean($row['email'] ?? '', 255);
        $row['role'] = departmentClean($row['role'] ?? '', 80);
        $roleKey = strtolower($row['role']);
        if (strpos($roleKey, 'staff') === false && strpos($roleKey, 'admin') === false) continue;

        // Return the canonical campus spelling from the campuses table.
        $row['campus'] = $officialCampuses[$campusKey];
        $row['school'] = departmentClean($row['school'] ?? '', 180);
        $row['program'] = departmentClean($row['program'] ?? '', 180);
        $row['position'] = departmentClean($row['position'] ?? '', 180);
        $rows[] = $row;
    }
    return $rows;
}

function departmentAssignments(PDO $pdo, int $departmentId): array {
    if ($departmentId <= 0) return [];
    $stmt = $pdo->prepare("SELECT h.id, h.department_id, h.campus, h.user_id, h.created_at, h.updated_at,
                                  u.full_name, u.email, u.role, u.campus AS user_campus
                           FROM department_hods h
                           INNER JOIN users u ON u.id = h.user_id
                           WHERE h.department_id = ?
                           ORDER BY h.campus ASC");
    $stmt->execute([$departmentId]);
    $rows = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $rows[] = [
            'id' => (int)$row['id'],
            'department_id' => (int)$row['department_id'],
            'campus' => departmentClean($row['campus'] ?? '', 180),
            'user_id' => (int)$row['user_id'],
            'hod_name' => departmentClean($row['full_name'] ?? '', 255),
            'hod_email' => departmentClean($row['email'] ?? '', 255),
            'hod_role' => departmentClean($row['role'] ?? '', 80),
            'user_campus' => departmentClean($row['user_campus'] ?? '', 180),
            'created_at' => $row['created_at'] ?? null,
            'updated_at' => $row['updated_at'] ?? null,
        ];
    }
    return $rows;
}

function departmentPublicRows(PDO $pdo): array {
    $campuses = departmentCampusRows($pdo);
    $campusCount = count($campuses);
    $stmt = $pdo->query('SELECT * FROM departments ORDER BY name ASC');
    $rows = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $id = (int)($row['id'] ?? 0);
        $assignments = departmentAssignments($pdo, $id);
        $row['id'] = $id;
        $row['hod_assignments'] = $assignments;
        $row['hod_assigned_count'] = count($assignments);
        $row['campus_count'] = $campusCount;
        $row['hod_complete'] = $campusCount > 0 && count($assignments) === $campusCount;
        $rows[] = $row;
    }
    return $rows;
}

function departmentUserForCampus(PDO $pdo, int $userId, string $campus): ?array {
    if ($userId <= 0) return null;
    $stmt = $pdo->prepare("SELECT id, full_name, email, role, campus FROM users WHERE id = ? LIMIT 1");
    $stmt->execute([$userId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) return null;
    if (departmentCampusKey($row['campus'] ?? '') !== departmentCampusKey($campus)) return null;
    return $row;
}

function departmentNormalizeHodAssignments(PDO $pdo, $raw): array {
    if (!is_array($raw)) {
        departmentRespond(422, ['detail' => 'Assign one HOD to this department for every campus.']);
    }

    $campuses = departmentCampusRows($pdo);
    if (!$campuses) {
        departmentRespond(422, ['detail' => 'No campuses are registered. Add campuses before creating departments.']);
    }

    $campusMap = [];
    foreach ($campuses as $campus) {
        $campusMap[departmentCampusKey($campus)] = $campus;
    }

    $assignments = [];
    foreach ($raw as $item) {
        if (!is_array($item)) {
            departmentRespond(422, ['detail' => 'One of the HOD assignments has an invalid structure.']);
        }
        $campus = departmentClean($item['campus'] ?? '', 180);
        $userId = (int)($item['user_id'] ?? 0);
        $key = departmentCampusKey($campus);
        if ($key === '' || !isset($campusMap[$key])) {
            departmentRespond(422, ['detail' => 'An HOD assignment references an unknown campus: ' . ($campus ?: 'Unnamed campus')]);
        }
        if (isset($assignments[$key])) {
            departmentRespond(422, ['detail' => 'Only one HOD may be assigned to a department at ' . $campusMap[$key] . '.']);
        }
        $user = departmentUserForCampus($pdo, $userId, $campusMap[$key]);
        if (!$user) {
            departmentRespond(422, ['detail' => 'The selected HOD for ' . $campusMap[$key] . ' does not exist or belongs to a different campus.']);
        }
        $assignments[$key] = [
            'campus' => $campusMap[$key],
            'user_id' => $userId,
        ];
    }

    $missing = [];
    foreach ($campusMap as $key => $campus) {
        if (!isset($assignments[$key])) $missing[] = $campus;
    }
    if ($missing) {
        departmentRespond(422, [
            'detail' => 'Every campus must have an HOD for this department. Missing: ' . implode(', ', $missing) . '.',
        ]);
    }

    return array_values($assignments);
}

function departmentSaveHodAssignments(PDO $pdo, int $departmentId, array $assignments): void {
    $delete = $pdo->prepare('DELETE FROM department_hods WHERE department_id = ?');
    $delete->execute([$departmentId]);

    $insert = $pdo->prepare("INSERT INTO department_hods (department_id, campus, user_id, updated_at)
                             VALUES (?, ?, ?, CURRENT_TIMESTAMP)");
    foreach ($assignments as $assignment) {
        $insert->execute([
            $departmentId,
            $assignment['campus'],
            (int)$assignment['user_id'],
        ]);
    }
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$parts = explode('/', trim($_SERVER['PATH_INFO'] ?? '', '/'));
$id = $parts[0] !== '' ? $parts[0] : null;
$action = strtolower(departmentClean($_GET['action'] ?? '', 40));

if (count($parts) > 1 || ($id !== null && (!ctype_digit($id) || (int)$id <= 0))) {
    departmentRespond(400, ['detail' => 'Invalid department ID or route.']);
}

try {
    departmentEnsureHodTable($pdo);

    if ($method === 'GET' && $id === null && $action === 'setup') {
        departmentRespond(200, [
            'campuses' => departmentCampusRows($pdo),
            'candidates' => departmentCandidateRows($pdo),
            'message' => 'Departments are university-wide. HOD assignments are campus-specific.',
        ]);
    }

    if ($method === 'GET' && $id === null) {
        departmentRespond(200, departmentPublicRows($pdo));
    }

    if ($method === 'GET' && $id !== null) {
        $stmt = $pdo->prepare('SELECT * FROM departments WHERE id = ? LIMIT 1');
        $stmt->execute([(int)$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) departmentRespond(404, ['detail' => 'Department not found.']);
        $row['id'] = (int)$row['id'];
        $row['hod_assignments'] = departmentAssignments($pdo, (int)$row['id']);
        $row['campus_count'] = count(departmentCampusRows($pdo));
        $row['hod_assigned_count'] = count($row['hod_assignments']);
        $row['hod_complete'] = $row['campus_count'] > 0 && $row['campus_count'] === $row['hod_assigned_count'];
        departmentRespond(200, $row);
    }

    $input = [];
    if ($method === 'POST' || $method === 'PUT') {
        $raw = file_get_contents('php://input');
        $decoded = json_decode($raw, true);
        if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) {
            departmentRespond(400, ['detail' => 'Supply a valid JSON object.']);
        }
        $input = $decoded;

        foreach (array_keys($input) as $key) {
            if (!in_array($key, ['name', 'description', 'hod_assignments'], true)) {
                departmentRespond(400, ['detail' => 'Unsupported department field: ' . $key]);
            }
        }

        if ($method === 'POST' || array_key_exists('name', $input)) {
            $name = departmentClean($input['name'] ?? '', 180);
            if ($name === '') departmentRespond(400, ['detail' => 'Department name is required.']);
            $input['name'] = $name;
        }

        if (array_key_exists('description', $input)) {
            if ($input['description'] !== null && !is_string($input['description'])) {
                departmentRespond(400, ['detail' => 'Description must be text.']);
            }
            $input['description'] = departmentClean($input['description'] ?? '', 2000);
        }
    }

    if ($method === 'POST' && $id === null) {
        $assignments = departmentNormalizeHodAssignments($pdo, $input['hod_assignments'] ?? null);

        $dup = $pdo->prepare('SELECT id FROM departments WHERE UPPER(TRIM(name)) = UPPER(TRIM(?)) LIMIT 1');
        $dup->execute([$input['name']]);
        if ($dup->fetchColumn() !== false) {
            departmentRespond(409, ['detail' => 'This department already exists. Departments are university-wide and must not be duplicated per campus.']);
        }

        $pdo->beginTransaction();
        $stmt = $pdo->prepare('INSERT INTO departments (name, description) VALUES (?, ?) RETURNING id');
        $stmt->execute([$input['name'], $input['description'] ?? '']);
        $departmentId = (int)$stmt->fetchColumn();
        departmentSaveHodAssignments($pdo, $departmentId, $assignments);
        $pdo->commit();

        departmentRespond(201, [
            'message' => 'Department created with campus HOD assignments.',
            'id' => $departmentId,
            'hod_assignments' => departmentAssignments($pdo, $departmentId),
        ]);
    }

    if ($method === 'PUT' && $id !== null) {
        if (empty($input)) departmentRespond(400, ['detail' => 'No department changes supplied.']);

        $pdo->beginTransaction();
        $check = $pdo->prepare('SELECT id, name FROM departments WHERE id = ? FOR UPDATE');
        $check->execute([(int)$id]);
        $current = $check->fetch(PDO::FETCH_ASSOC);
        if (!$current) {
            $pdo->rollBack();
            departmentRespond(404, ['detail' => 'Department not found. Reload the directory.']);
        }

        if (array_key_exists('name', $input)) {
            $dup = $pdo->prepare('SELECT id FROM departments WHERE UPPER(TRIM(name)) = UPPER(TRIM(?)) AND id <> ? LIMIT 1');
            $dup->execute([$input['name'], (int)$id]);
            if ($dup->fetchColumn() !== false) {
                $pdo->rollBack();
                departmentRespond(409, ['detail' => 'Another university-wide department already uses this name.']);
            }
        }

        $fields = [];
        $params = [];
        foreach (['name', 'description'] as $key) {
            if (array_key_exists($key, $input)) {
                $fields[] = "$key = ?";
                $params[] = $input[$key];
            }
        }
        if ($fields) {
            $params[] = (int)$id;
            $stmt = $pdo->prepare('UPDATE departments SET ' . implode(', ', $fields) . ' WHERE id = ?');
            $stmt->execute($params);
        }

        // Staff profiles currently store their department name in users.program.
        // Keep those profiles synchronized if the university-wide department is renamed.
        if (array_key_exists('name', $input)
            && departmentNorm($input['name']) !== departmentNorm($current['name'] ?? '')
            && departmentTableExists($pdo, 'users')
            && in_array('program', departmentColumns($pdo, 'users'), true)) {
            $sync = $pdo->prepare("UPDATE users SET program = ? WHERE UPPER(TRIM(COALESCE(program, ''))) = UPPER(TRIM(?))");
            $sync->execute([$input['name'], $current['name']]);
        }

        // The edit UI always sends the complete campus/HOD matrix. Existing
        // departments from older versions can therefore be upgraded safely.
        if (array_key_exists('hod_assignments', $input)) {
            $assignments = departmentNormalizeHodAssignments($pdo, $input['hod_assignments']);
            departmentSaveHodAssignments($pdo, (int)$id, $assignments);
        } else {
            $campusCount = count(departmentCampusRows($pdo));
            $currentCount = count(departmentAssignments($pdo, (int)$id));
            if ($campusCount <= 0 || $currentCount !== $campusCount) {
                $pdo->rollBack();
                departmentRespond(422, ['detail' => 'Complete the HOD assignment for every campus before saving this department.']);
            }
        }

        $pdo->commit();
        departmentRespond(200, [
            'message' => 'Department updated successfully.',
            'id' => (int)$id,
            'hod_assignments' => departmentAssignments($pdo, (int)$id),
        ]);
    }

    if ($method === 'DELETE' && $id !== null) {
        $pdo->beginTransaction();
        $check = $pdo->prepare('SELECT id, name FROM departments WHERE id = ? FOR UPDATE');
        $check->execute([(int)$id]);
        $department = $check->fetch(PDO::FETCH_ASSOC);
        if (!$department) {
            $pdo->rollBack();
            departmentRespond(404, ['detail' => 'Department not found. Reload the directory.']);
        }

        // users.program is currently the staff-profile field holding department.
        if (departmentTableExists($pdo, 'users') && in_array('program', departmentColumns($pdo, 'users'), true)) {
            $linked = $pdo->prepare("SELECT COUNT(*) FROM users WHERE UPPER(TRIM(COALESCE(program, ''))) = UPPER(TRIM(?))");
            $linked->execute([$department['name']]);
            if ((int)$linked->fetchColumn() > 0) {
                $pdo->rollBack();
                departmentRespond(409, ['detail' => 'This department is still assigned to staff profiles. Reassign those staff members before deleting the department.']);
            }
        }

        $pdo->prepare('DELETE FROM departments WHERE id = ?')->execute([(int)$id]);
        $pdo->commit();
        departmentRespond(204);
    }

    departmentRespond(405, ['detail' => 'Unsupported method or missing department ID.']);
} catch (PDOException $error) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) $pdo->rollBack();

    $sqlState = (string)$error->getCode();
    $driverCode = $error->errorInfo[1] ?? null;

    if ($method === 'DELETE' && in_array($sqlState, ['23503', '23000'], true)) {
        departmentRespond(409, ['detail' => 'This department or HOD assignment is linked to other records and cannot be deleted yet.']);
    }
    if ($sqlState === '23505' || $driverCode === 1062) {
        departmentRespond(409, ['detail' => 'A conflicting department or campus HOD assignment already exists.']);
    }

    departmentRespond(500, ['detail' => 'Database error: ' . $error->getMessage()]);
} catch (Throwable $error) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) $pdo->rollBack();
    departmentRespond(500, ['detail' => 'Department service error: ' . $error->getMessage()]);
}
