<?php
// =============================================================
//  GET /api/v1/assessments/student_pending
//
//  Staff-facing "who's eligible for assessment" list — mirrors
//  app/clinical_assessments.php's eligibility query exactly: a unit block
//  is eligible once at least one of its daily rows is 'Completed' and no
//  clinical_assessments row exists yet for that student+unit+rotation
//  (any status, including 'draft' — matched exactly, not narrowed).
//
//  Deliberately NOT scoped by department/unit — neither is the web page
//  it mirrors, unlike nurse_assessments.php. Single-stage, single
//  permission ('assess_students'), unlike the nurse pipeline.
// =============================================================

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

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

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

$sql = "
    SELECT
        cs.id AS student_id, cs.firstname, cs.surname, cs.school_name, cs.level, cs.programme,
        cr.id AS rotation_id, cr.batch_name,
        srd.unit_id, srd.unit_name
    FROM student_rotation_details srd
    JOIN clinical_rotations cr ON cr.id = srd.clinical_rotation_id
    JOIN clinical_students  cs ON cs.id = srd.clinical_student_id
    JOIN units               u ON u.id  = srd.unit_id
    WHERE cr.status != 'Cancelled'
      AND cs.status = 'Active'
      AND u.cancelled_at IS NULL
      AND srd.status != 'Cancelled'
      AND EXISTS (
          SELECT 1 FROM student_rotation_details y
          WHERE y.clinical_student_id = cs.id AND y.clinical_rotation_id = cr.id
            AND y.unit_id = srd.unit_id AND y.status = 'Completed'
      )
      AND NOT EXISTS (
          SELECT 1 FROM clinical_assessments ca
          WHERE ca.clinical_student_id = cs.id AND ca.unit_id = srd.unit_id AND ca.clinical_rotation_id = cr.id
      )
    GROUP BY cs.id, cr.id, srd.unit_id, srd.unit_name, cs.school_name, cs.level, cs.programme,
             cs.firstname, cs.surname, cr.batch_name
    ORDER BY cs.firstname ASC, cs.surname ASC
";
$rows = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);

$students = array_map(fn($r) => [
    'student_id'  => (int)$r['student_id'],
    'full_name'   => trim($r['firstname'] . ' ' . $r['surname']),
    'school_name' => $r['school_name'],
    'level'       => $r['level'],
    'programme'   => $r['programme'],
    'rotation_id' => (int)$r['rotation_id'],
    'batch_name'  => $r['batch_name'],
    'unit_id'     => (int)$r['unit_id'],
    'unit_name'   => $r['unit_name'],
], $rows);

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