<?php
header('Content-Type: application/json');
include('pdo_config.php'); // this defines $conn as PDO connection

$session = $_GET['session'] ?? 'All';
$date = date('Y-m-d');

$sql = "SELECT * FROM checkins WHERE 1";
$params = [];

if ($session === 'Morning') {
    $sql .= " AND (DATE(am_in) = ? OR DATE(am_out) = ?)";
    $params[] = $date;
    $params[] = $date;
} elseif ($session === 'Afternoon') {
    $sql .= " AND (DATE(pm_in) = ? OR DATE(pm_out) = ?)";
    $params[] = $date;
    $params[] = $date;
} else {
    $sql .= " AND (DATE(am_in) = ? OR DATE(pm_in) = ?)";
    $params[] = $date;
    $params[] = $date;
}

try {
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    $students = [];

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $am_status = (!empty($row['am_in']) && !empty($row['am_out'])) ? "Present"
                   : ((!empty($row['am_in'])) ? "Partial" : "Absent");

        $pm_status = (!empty($row['pm_in']) && !empty($row['pm_out'])) ? "Present"
                   : ((!empty($row['pm_in'])) ? "Partial" : "Absent");

        $students[] = [
            'name' => $row['name'],
            'grade' => $row['grade'],
            'am_in' => $row['am_in'],
            'am_out' => $row['am_out'],
            'pm_in' => $row['pm_in'],
            'pm_out' => $row['pm_out'],
            'am_status' => $am_status,
            'pm_status' => $pm_status,
        ];
    }

    echo json_encode($students);

} catch (PDOException $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>
