<?php
// =============================================================
//  GET /api/v1/rotations/nurse_list
//
//  Staff-facing list of rotation nurses, scoped exactly like the
//  existing web list pages: Admin/Chief_Preceptor see everyone,
//  Preceptor/Nurse_Manager see their department, In_Charge sees their
//  unit(s) — via include/scope_helper.php, untouched. Each nurse is
//  enriched with their current placement (if any), computed in SQL from
//  the same start_date + start_week/end_week fields
//  include/RotationScheduleHelpers.php uses, so a scan across many
//  nurses doesn't need one query per nurse.
// =============================================================

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 = scopeNurseWhere('nrs');

$sql = "
    SELECT DISTINCT rn.id, rn.firstname, rn.surname, rn.student_id, rn.school_name,
           rn.specialty_name, rn.rotation_status, rn.status,
           cur.department_name AS current_department, cur.unit_name AS current_unit,
           cur.date_to AS current_placement_ends
    FROM rotation_nurses rn
    JOIN nurse_rotations nr ON nr.nurse_id = rn.id
    JOIN nurse_rotation_schedules nrs ON nrs.nurse_rotation_id = nr.id
    LEFT JOIN (
        SELECT nrs2.rotation_nurse_id, nrs2.department_name, nrs2.unit_name,
               DATE_ADD(nr2.start_date, INTERVAL (nrs2.end_week * 7 - 1) DAY) AS date_to
        FROM nurse_rotation_schedules nrs2
        JOIN nurse_rotations nr2 ON nr2.id = nrs2.nurse_rotation_id
        WHERE CURDATE() BETWEEN DATE_ADD(nr2.start_date, INTERVAL (nrs2.start_week - 1) * 7 DAY)
                             AND DATE_ADD(nr2.start_date, INTERVAL (nrs2.end_week * 7 - 1) DAY)
    ) cur ON cur.rotation_nurse_id = rn.id
    WHERE rn.status = 'Active'
";
if ($scope['sql']) $sql .= " AND {$scope['sql']}";
$sql .= " ORDER BY rn.surname, rn.firstname";

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

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