<?php
// =============================================================
//  GET /api/v1/passwords/list
//
//  Mirrors app/manage_password.php's own fetch exactly — every Active
//  account across all three tables (Staff, Rotation Nurse, Clinical
//  Student), each with its password_change_required flag, plus the same
//  four summary counts that page's stat cards show. Gated on
//  'assign_role', matching that page's own requirePermission() call
//  (not 'edit_user', which api/v1/staff/reset_password.php uses for its
//  narrower staff-only reset action — the two mobile endpoints cover
//  different scopes of the same desktop feature, so they keep the
//  desktop's own distinct permission gates rather than being merged
//  onto one).
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Api::error(405, 'MethodNotAllowed', 'Use GET');
}

api_authenticate();
api_require_permission('assign_role');

function passwords_col_exists(mysqli $db, string $table, string $col): bool {
    $r = $db->query("SHOW COLUMNS FROM `$table` LIKE '$col'");
    return $r && $r->num_rows > 0;
}

$staff = $conn->query("
    SELECT id, firstname, surname, usertype, email, password_change_required
    FROM users
    WHERE status = 'Active'
    ORDER BY firstname, surname
")->fetch_all(MYSQLI_ASSOC);

$nurses = $conn->query("
    SELECT id, firstname, surname, school_name, specialty_name, password_change_required
    FROM rotation_nurses
    WHERE status = 'Active'
    ORDER BY firstname, surname
")->fetch_all(MYSQLI_ASSOC);

$csLevel     = passwords_col_exists($conn, 'clinical_students', 'level')     ? 'level'     : 'NULL AS level';
$csProgramme = passwords_col_exists($conn, 'clinical_students', 'programme') ? 'programme' : 'NULL AS programme';

$students = $conn->query("
    SELECT id, firstname, surname, school_name, $csLevel, $csProgramme, password_change_required
    FROM clinical_students
    WHERE status = 'Active'
    ORDER BY firstname, surname
")->fetch_all(MYSQLI_ASSOC);

$countPending = fn(array $rows) => count(array_filter($rows, fn($r) => (int)$r['password_change_required'] === 1));

Api::success([
    'staff' => $staff,
    'nurses' => $nurses,
    'students' => $students,
    'stats' => [
        'total_all' => count($staff) + count($nurses) + count($students),
        'total_pending' => $countPending($staff) + $countPending($nurses) + $countPending($students),
        'total_staff' => count($staff),
        'total_nurses_and_students' => count($nurses) + count($students),
    ],
]);
