<?php
// =============================================================
//  GET /api/v1/admin_students/list
//
//  Clinical Student account directory — mirrors app/manage_clinical_
//  students.php's own SELECT exactly (same columns, same ordering).
//  Read-only; the write actions (create/update/toggle status/toggle
//  rotation/delete) are their own endpoints in this module, each
//  independently permission-gated the same way the web page's own AJAX
//  actions are. This is account management (onboarding/deactivating a
//  student), distinct from rotations/student_list.php's read-only
//  "who's under my charge" roster.
// =============================================================

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

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

$account = api_authenticate();
api_require_permission('view_all_users');

$stmt = $conn->prepare("
    SELECT id, firstname, surname, email, phone, gender, student_id, school_name,
           level, programme, supervisor_name, rotation_status, status, profile,
           created_at, last_login
    FROM clinical_students
    ORDER BY created_at DESC
");
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

Api::success([
    'students' => $rows,
    'can' => [
        'create'     => PermissionManager::sessionCan('create_user'),
        'edit'       => PermissionManager::sessionCan('edit_user'),
        'deactivate' => PermissionManager::sessionCan('deactivate_user'),
        'delete'     => PermissionManager::sessionCan('delete_user'),
    ],
]);
