<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db   = 'school_checkin';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=attendance_logs.csv');

$output = fopen('php://output', 'w');
fputcsv($output, ['LRN', 'Name', 'Grade', 'Category', 'Check-in Time', 'Check-out Time']);

function getCategory($grade) {
    $preschool = ['Nursery', 'Kinder 1', 'Kinder 2'];
    return in_array($grade, $preschool) ? 'Preschool' : 'Grade School';
}

$result = $conn->query("SELECT * FROM checkins ORDER BY id DESC");
while ($row = $result->fetch_assoc()) {
    $category = getCategory($row['grade']);
    fputcsv($output, [
        $row['lrn'],
        $row['name'],
        $row['grade'],
        $category,
        $row['checkin_time'],
        $row['checkout_time']
    ]);
}

fclose($output);
$conn->close();
exit;
