<?php
// =============================================================
//  GET /api/v1/assessments/nurse_pending
//
//  Staff-facing "who's awaiting assessment at MY stage right now" list —
//  mirrors app/nurse_assessments.php's eligible-schedule-blocks query and
//  its per-row stage-eligibility check (lines ~419-423 there), but only
//  returns rows the caller can actually act on, rather than the full
//  read-only pipeline view every assess_students-holder sees on the web.
//  That fuller read-only view isn't ported here — this endpoint is
//  deliberately scoped to "what do I need to do", matching the mobile
//  app's action-oriented pattern (attendance/nurse_pending.php etc.).
//
//  3-stage pipeline (app/nurse_assessment_form.php):
//    Stage 1 → In_Charge        (requires the nurse's lessons submitted)
//    Stage 2 → Nurse_Manager    (requires stage 1 submitted)
//    Stage 3 → Chief_Preceptor / Preceptor (requires stage 2 submitted)
// =============================================================

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

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

$account = api_authenticate();

$userType = $account->getUserType();
if ($userType === 'In_Charge') {
    $myStage = 1;
} elseif ($userType === 'Nurse_Manager') {
    $myStage = 2;
} elseif (in_array($userType, ['Chief_Preceptor', 'Preceptor'], true)) {
    $myStage = 3;
} else {
    $myStage = 0; // Admin — view-only on the web page; nothing actionable here either
}

// Deliberately NOT just 'assess_students' — Nurse_Manager holds
// 'assess_nurses_stage2' but not the generic 'assess_students' permission
// (see role_permissions), so gating on the generic name alone would lock
// Nurse_Manager out of Stage 2 entirely, exactly the bug found and fixed
// in app/nurse_assessment_form.php / nurse_assessments.php this session.
api_require_any_permission(['assess_students', "assess_nurses_stage{$myStage}"]);

if ($myStage === 0) {
    Api::success(['my_stage' => 0, 'nurses' => []]);
}

$scope = scopeNurseWhere('nrs');

$sql = "
    SELECT
        rn.id AS nurse_id, rn.firstname, rn.surname, rn.school_name, rn.student_id AS nurse_number,
        nr.id AS rotation_id,
        nrs.id AS schedule_id, nrs.unit_id, nrs.unit_name, nrs.department_id, nrs.department_name,
        na.id AS assessment_id,
        COALESCE(na.stage1_status, 'pending') AS stage1_status,
        COALESCE(na.stage2_status, 'pending') AS stage2_status,
        COALESCE(na.stage3_status, 'pending') AS stage3_status,
        nl.status AS lesson_status
    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 nurse_assessments na
           ON na.rotation_nurse_id = rn.id AND na.nurse_rotation_id = nr.id AND na.nurse_rotation_schedule_id = nrs.id
    LEFT JOIN nurse_lessons nl
           ON nl.rotation_nurse_id = rn.id AND nl.nurse_rotation_schedule_id = nrs.id
    WHERE nrs.status IN ('In_Progress', 'Completed') AND rn.status = 'Active'
";
if ($scope['sql']) $sql .= " AND {$scope['sql']}";
$sql .= " ORDER BY rn.surname ASC, nrs.start_week ASC";

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

$actionable = [];
foreach ($rows as $r) {
    $canAssess = false;
    if ($myStage === 1) {
        $canAssess = $r['stage1_status'] === 'pending' && $r['lesson_status'] === 'submitted';
    } elseif ($myStage === 2) {
        $canAssess = $r['stage2_status'] === 'pending' && $r['stage1_status'] === 'submitted';
    } elseif ($myStage === 3) {
        $canAssess = $r['stage3_status'] === 'pending' && $r['stage2_status'] === 'submitted';
    }
    if (!$canAssess) continue;

    $actionable[] = [
        'nurse_id'        => (int)$r['nurse_id'],
        'full_name'       => trim($r['firstname'] . ' ' . $r['surname']),
        'school_name'     => $r['school_name'],
        'nurse_number'    => $r['nurse_number'],
        'rotation_id'     => (int)$r['rotation_id'],
        'schedule_id'     => (int)$r['schedule_id'],
        'unit_id'         => (int)$r['unit_id'],
        'unit_name'       => $r['unit_name'],
        'department_id'   => $r['department_id'] !== null ? (int)$r['department_id'] : null,
        'department_name' => $r['department_name'],
    ];
}

Api::success(['my_stage' => $myStage, 'nurses' => $actionable]);
