<?php
// =============================================================
//  GET /api/v1/attendance/nurse_mine[?status=Present&month=2026-08]
//
//  The authenticated Rotation Nurse's own attendance history — same
//  filters app/nurse/my_attendance.php supports.
// =============================================================

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

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

$account = api_authenticate();
if ($account->getTable() !== 'rotation_nurses') {
    Api::error(403, 'Forbidden', 'This endpoint is for Rotation Nurses only');
}

$where  = ['na.rotation_nurse_id = ?'];
$params = [$account->getId()];
$types  = 'i';

$status = trim((string)($_GET['status'] ?? ''));
if (in_array($status, ['Present', 'Absent', 'Late', 'Excused'], true)) {
    $where[] = 'na.status = ?';
    $params[] = $status;
    $types   .= 's';
}
$month = trim((string)($_GET['month'] ?? ''));
if (preg_match('/^\d{4}-\d{2}$/', $month)) {
    $where[] = "DATE_FORMAT(na.attendance_date, '%Y-%m') = ?";
    $params[] = $month;
    $types   .= 's';
}

$sql = "
    SELECT na.id, na.unit_name, na.department_name, na.attendance_date, na.status, na.remarks, na.is_self_checkin
    FROM nurse_attendance na
    WHERE " . implode(' AND ', $where) . "
    ORDER BY na.attendance_date DESC
    LIMIT 500
";
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$present = count(array_filter($rows, fn($r) => $r['status'] === 'Present'));
Api::success([
    'attendance' => $rows,
    'summary' => [
        'total'             => count($rows),
        'present'           => $present,
        'attendance_rate'   => count($rows) > 0 ? round(($present / count($rows)) * 100) : null,
    ],
]);
