<?php
// =============================================================
//  GET /api/v1/rotations/nurse_eligible
//
//  Nurses eligible to be selected into a NEW rotation-generation batch —
//  the population POST /rotations/nurse_generate can actually act on.
//
//  Deliberately NOT rotations/nurse_list.php: that endpoint INNER JOINs
//  nurse_rotations/nurse_rotation_schedules to enrich each row with a
//  current placement, which structurally excludes every nurse who has no
//  rotation yet — exactly the population this generation picker needs to
//  show. Mirrors app/create_nurse_rotation.php's own step-1 query field-
//  for-field instead (status Active, rotation_status Not_started, not
//  already mid-rotation, specialty compatible with at least one active
//  department), rather than a client-side filter over the wrong endpoint.
// =============================================================

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

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

api_authenticate();
api_require_permission('assign_rotations');

$result = $conn->query("
    SELECT rn.id, rn.firstname, rn.surname,
           rn.school_name, rn.student_id,
           rn.specialty_id, rn.specialty_name
    FROM rotation_nurses rn
    WHERE rn.status = 'Active'
      AND rn.rotation_status = 'Not_started'
      AND rn.id NOT IN (
          SELECT nr.nurse_id
          FROM nurse_rotations nr
          WHERE nr.status IN ('Inprogress')
      )
      AND rn.specialty_id IN (
          SELECT DISTINCT sdw.specialty_id
          FROM specialty_department_weeks sdw
          JOIN departments d ON sdw.department_id = d.id
          WHERE d.status = 'Active'
            AND sdw.is_active = 'Active'
      )
    ORDER BY rn.firstname, rn.surname
");

Api::success(['nurses' => $result->fetch_all(MYSQLI_ASSOC)]);
