<?php
// =============================================================
//  GET /api/v1/attendance/nurse_pending[?date=2026-08-16]
//
//  Staff-facing "who hasn't been marked yet today" list, grouped by unit —
//  the mobile equivalent of app/nurse_attendance.php's pending-nurses
//  query. Requires the 'mark_attendance' permission (held by all five
//  staff roles — see include/PermissionManager.php's role_permissions).
//
//  Deliberately NOT scoped to the caller's own department/unit: neither
//  is the web page it mirrors (app/nurse_attendance.php runs the same
//  system-wide query for every role holding 'mark_attendance'), so this
//  keeps mobile and web behaviourally identical rather than inventing a
//  stricter rule the web app doesn't actually enforce.
// =============================================================

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

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

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

$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/nurse_attendance.php's $pending_sql exactly.
$pending_sql = "
    SELECT DISTINCT
        nrs.id AS schedule_id,
        nrs.unit_id,
        nrs.unit_name,
        nrs.department_id,
        nrs.department_name,
        nr.id AS rotation_id,
        rn.id AS nurse_id,
        rn.firstname,
        rn.surname,
        rn.school_name,
        rn.student_id
    FROM nurse_rotation_schedules nrs
    JOIN nurse_rotations nr ON nrs.nurse_rotation_id = nr.id
    JOIN rotation_nurses rn ON nrs.rotation_nurse_id = rn.id
    WHERE rn.status = 'Active'
      AND nr.status IN ('Inprogress', 'Completed')
      AND nrs.status NOT IN ('Completed', 'Missed', 'Reassigned')
      AND nr.start_date <= ?
      AND nr.end_date >= ?
      AND NOT EXISTS (
          SELECT 1 FROM nurse_attendance na
          WHERE na.rotation_nurse_id = rn.id
            AND na.unit_id = nrs.unit_id
            AND na.attendance_date = ?
      )
    ORDER BY nrs.unit_name, rn.firstname, rn.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['department_id'];
    if (!isset($groups[$key])) {
        $groups[$key] = [
            'unit_id'         => (int)$row['unit_id'],
            'unit_name'       => $row['unit_name'],
            'department_id'   => $row['department_id'] !== null ? (int)$row['department_id'] : null,
            'department_name' => $row['department_name'],
            'rotation_id'     => (int)$row['rotation_id'],
            'schedule_id'     => (int)$row['schedule_id'],
            'nurses'          => [],
        ];
    }
    $groups[$key]['nurses'][] = [
        'nurse_id'    => (int)$row['nurse_id'],
        'full_name'   => trim($row['firstname'] . ' ' . $row['surname']),
        'school_name' => $row['school_name'],
        'student_id'  => $row['student_id'],
    ];
}

// Stats block matches the web page's header counters.
$expected_stmt = $conn->prepare("
    SELECT COUNT(DISTINCT nrs.rotation_nurse_id) AS total
    FROM nurse_rotation_schedules nrs
    JOIN nurse_rotations nr ON nrs.nurse_rotation_id = nr.id
    JOIN rotation_nurses rn ON nrs.rotation_nurse_id = rn.id
    WHERE rn.status = 'Active'
      AND nr.status IN ('Inprogress', 'Completed')
      AND nrs.status NOT IN ('Completed', 'Missed', 'Reassigned')
      AND nr.start_date <= ? AND nr.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,
    ],
]);
