<?php
// =============================================================
//  GET /api/v1/attendance/student_mine[?status=Present&month=2026-08]
//
//  The authenticated Clinical Student's own attendance history — same
//  shape as attendance/nurse_mine.php, against clinical_attendance.
// =============================================================

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

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

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

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

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

$sql = "
    SELECT ca.id, ca.unit_name, ca.attendance_date, ca.status, ca.remarks, ca.is_self_checkin
    FROM clinical_attendance ca
    WHERE " . implode(' AND ', $where) . "
    ORDER BY ca.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,
    ],
]);
