<?php
// =============================================================
//  GET /api/v1/lessons/staff_nurse_list[?nurse_id=NN&status=submitted|draft|missing]
//
//  Mobile equivalent of app/nurse_lessons.php's list — every nurse unit
//  block with In_Progress/Completed status, joined to its lesson
//  submission (if any), scoped the same way as everywhere else in this
//  API (scope_helper.php: Admin/Chief_Preceptor see everyone,
//  Preceptor/Nurse_Manager their department, In_Charge their unit(s)).
// =============================================================

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

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

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

$filterNurse  = (int)($_GET['nurse_id'] ?? 0);
$filterStatus = trim((string)($_GET['status'] ?? ''));

$where  = ["nrs.status IN ('In_Progress','Completed')", "rn.status = 'Active'"];
$params = [];
$types  = '';

if ($filterNurse) {
    $where[]  = 'rn.id = ?';
    $params[] = $filterNurse;
    $types   .= 'i';
}
if ($filterStatus === 'submitted') {
    $where[] = "nl.status = 'submitted'";
} elseif ($filterStatus === 'draft') {
    $where[] = "nl.status = 'draft'";
} elseif ($filterStatus === 'missing') {
    $where[] = 'nl.id IS NULL';
}

$scope = scopeNurseWhere('nrs');
if ($scope['sql']) {
    $where[] = $scope['sql'];
    $params  = array_merge($params, $scope['params']);
    $types  .= $scope['types'];
}

$sql = "
    SELECT
        rn.id AS nurse_id, CONCAT(rn.firstname,' ',rn.surname) AS nurse_name,
        rn.specialty_name, rn.student_id AS nurse_number,
        nrs.id AS schedule_id, nrs.unit_name, nrs.department_name,
        nrs.start_week, nrs.end_week,
        nl.id AS lesson_id, nl.lesson_count, nl.status AS lesson_status, nl.submitted_at
    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_lessons nl
           ON nl.rotation_nurse_id = rn.id AND nl.nurse_rotation_schedule_id = nrs.id
    WHERE " . implode(' AND ', $where) . "
    ORDER BY nl.status DESC, rn.surname ASC
";
$stmt = $conn->prepare($sql);
if ($types) $stmt->bind_param($types, ...$params);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

foreach ($records as &$r) {
    $r['lesson_count'] = (int)($r['lesson_count'] ?? 0);
}
unset($r);

Api::success([
    'records' => $records,
    'stats' => [
        'total'     => count($records),
        'submitted' => count(array_filter($records, fn($r) => $r['lesson_status'] === 'submitted')),
        'draft'     => count(array_filter($records, fn($r) => $r['lesson_status'] === 'draft')),
        'missing'   => count(array_filter($records, fn($r) => !$r['lesson_id'])),
    ],
]);
