<?php
// =============================================================
//  GET /api/v1/rotations/student_list
//
//  Staff-facing list of clinical students, scoped exactly like the
//  existing web list pages via include/scope_helper.php's
//  scopeStudentWhere()/scopeStudentJoin() (untouched). Each student is
//  enriched with their current unit (the unit whose day-rows are
//  currently 'Ongoing'), via a correlated subquery rather than a join,
//  so it can't multiply rows against the scoping join.
// =============================================================

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

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

$account = api_authenticate();
api_require_staff_role($account, ['Admin', 'Chief_Preceptor', 'Preceptor', 'Nurse_Manager', 'In_Charge']);

$scope = scopeStudentWhere('srd', 'u');
$join  = $scope['needs_unit_join'] ? scopeStudentJoin('srd') : '';

$sql = "
    SELECT DISTINCT cs.id, cs.firstname, cs.surname, cs.student_id, cs.school_name,
           cs.level, cs.programme, cs.rotation_status, cs.status,
           (SELECT srd2.unit_name FROM student_rotation_details srd2
             WHERE srd2.clinical_student_id = cs.id AND srd2.status = 'Ongoing'
             ORDER BY srd2.id DESC LIMIT 1) AS current_unit
    FROM clinical_students cs
    JOIN student_rotation_details srd ON srd.clinical_student_id = cs.id
    {$join}
    WHERE cs.status = 'Active'
";
if ($scope['sql']) $sql .= " AND {$scope['sql']}";
$sql .= " ORDER BY cs.surname, cs.firstname";

$stmt = $conn->prepare($sql);
if ($scope['types']) $stmt->bind_param($scope['types'], ...$scope['params']);
$stmt->execute();
$students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

Api::success(['students' => $students, 'scope' => getScopeLabel()]);
