<?php
// =============================================================
//  GET /api/v1/attendance/student_pending[?date=2026-08-16]
//
//  Staff-facing "who hasn't been marked yet today" list for Clinical
//  Students, grouped by unit — the mobile equivalent of
//  app/clinical_attendance.php's pending-students query. Requires the
//  'assess_students' permission, matching that page's own guard (NOT
//  'mark_attendance' — Nurse_Manager, who manages nurses only, deliberately
//  lacks 'assess_students' and is correctly excluded here just as it is on
//  the web page).
// =============================================================

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

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

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

$today = date('Y-m-d');
$sel_date = trim((string)($_GET['date'] ?? $today));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $sel_date)) {
    $sel_date = $today;
}

// Mirrors app/clinical_attendance.php's $pending_sql exactly.
$pending_sql = "
    SELECT
        srd.unit_id,
        srd.unit_name,
        srd.clinical_rotation_id AS rotation_id,
        cr.batch_name,
        cs.id AS student_id,
        cs.firstname,
        cs.surname,
        cs.school_name,
        cs.level,
        cs.programme
    FROM   student_rotation_details srd
    JOIN   clinical_students  cs ON cs.id  = srd.clinical_student_id  AND cs.status  = 'Active'
    JOIN   clinical_rotations cr ON cr.id  = srd.clinical_rotation_id AND cr.status != 'Cancelled'
    JOIN   units              u  ON u.id   = srd.unit_id               AND u.cancelled_at IS NULL
    WHERE  srd.status != 'Cancelled'
      AND  srd.start_date <= ?
      AND  srd.end_date   >= ?
      AND  NOT EXISTS (
               SELECT 1 FROM clinical_attendance ca
               WHERE  ca.clinical_student_id  = cs.id
                 AND  ca.clinical_rotation_id = srd.clinical_rotation_id
                 AND  ca.unit_id              = srd.unit_id
                 AND  ca.attendance_date      = ?
           )
    ORDER BY srd.unit_name, cs.firstname, cs.surname
";
$stmt = $conn->prepare($pending_sql);
$stmt->bind_param('sss', $sel_date, $sel_date, $sel_date);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$groups = [];
foreach ($rows as $row) {
    $key = $row['unit_id'] . '_' . $row['rotation_id'];
    if (!isset($groups[$key])) {
        $groups[$key] = [
            'unit_id'     => (int)$row['unit_id'],
            'unit_name'   => $row['unit_name'],
            'rotation_id' => (int)$row['rotation_id'],
            'batch_name'  => $row['batch_name'],
            'students'    => [],
        ];
    }
    $groups[$key]['students'][] = [
        'student_id'  => (int)$row['student_id'],
        'full_name'   => trim($row['firstname'] . ' ' . $row['surname']),
        'school_name' => $row['school_name'],
        'level'       => $row['level'],
        'programme'   => $row['programme'],
    ];
}

$expected_stmt = $conn->prepare("
    SELECT COUNT(*) AS total
    FROM   student_rotation_details srd
    JOIN   clinical_students  cs ON cs.id  = srd.clinical_student_id  AND cs.status  = 'Active'
    JOIN   clinical_rotations cr ON cr.id  = srd.clinical_rotation_id AND cr.status != 'Cancelled'
    JOIN   units              u  ON u.id   = srd.unit_id               AND u.cancelled_at IS NULL
    WHERE  srd.status != 'Cancelled'
      AND  srd.start_date <= ? AND srd.end_date >= ?
");
$expected_stmt->bind_param('ss', $sel_date, $sel_date);
$expected_stmt->execute();
$total_active = (int)$expected_stmt->get_result()->fetch_assoc()['total'];
$expected_stmt->close();

$total_pending = count($rows);
$total_marked  = max(0, $total_active - $total_pending);

Api::success([
    'date'   => $sel_date,
    'groups' => array_values($groups),
    'stats'  => [
        'total_active'  => $total_active,
        'total_pending' => $total_pending,
        'total_marked'  => $total_marked,
        'percent_done'  => $total_active > 0 ? (int)round(($total_marked / $total_active) * 100) : 0,
    ],
]);
