<?php
// =============================================================
//  GET /api/v1/lessons/staff_student_list
//
//  Mobile equivalent of app/clinical_lessons.php — every student's
//  lessons-learned submission per unit block. Deliberately unscoped
//  (matches the desktop exactly — no department/unit filter here, unlike
//  the nurse-side staff list), gated on 'view_student_evaluations'.
// =============================================================

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

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

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

$sql = "
    SELECT
        cs.id                                       AS student_id,
        CONCAT(cs.firstname, ' ', cs.surname)       AS student_name,
        cs.school_name,
        cs.level,
        cs.programme,
        cr.id                                       AS rotation_id,
        cr.batch_name,
        srd.unit_id,
        srd.unit_name,
        srd.supervisor_name,
        MIN(srd.rotation_date)                      AS unit_start,
        MAX(srd.rotation_date)                      AS unit_end,
        COUNT(DISTINCT cl.id)                       AS lesson_count,
        MAX(cl.submitted_at)                        AS submitted_at,
        MAX(CASE WHEN ca.id IS NOT NULL THEN 1 ELSE 0 END) AS is_assessed
    FROM clinical_lessons cl
    JOIN clinical_students  cs  ON cs.id  = cl.clinical_student_id
    JOIN clinical_rotations cr  ON cr.id  = cl.clinical_rotation_id
    JOIN student_rotation_details srd
        ON  srd.clinical_student_id  = cl.clinical_student_id
        AND srd.clinical_rotation_id = cl.clinical_rotation_id
        AND srd.unit_id              = cl.unit_id
        AND srd.status              != 'Cancelled'
    LEFT JOIN clinical_assessments ca
        ON  ca.clinical_student_id  = cl.clinical_student_id
        AND ca.clinical_rotation_id = cl.clinical_rotation_id
        AND ca.unit_id              = cl.unit_id
    WHERE cs.status = 'Active'
    GROUP BY
        cs.id, cr.id, cl.unit_id,
        cs.firstname, cs.surname, cs.school_name, cs.level, cs.programme,
        cr.batch_name, srd.unit_name, srd.supervisor_name
    ORDER BY
        cs.firstname ASC, cs.surname ASC, cr.batch_name ASC, srd.unit_name ASC
";
$result = $conn->query($sql);
$rows   = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

foreach ($rows as &$r) {
    $r['lesson_count'] = (int)$r['lesson_count'];
    $r['is_assessed']  = (bool)$r['is_assessed'];
}
unset($r);

Api::success([
    'records' => $rows,
    'stats' => [
        'total'   => count($rows),
        'assessed' => count(array_filter($rows, fn($r) => $r['is_assessed'])),
    ],
]);
