<?php
session_start();
include '../includes/auth.php';
include '../includes/db.php';

$event_id = $_GET['event_id'] ?? null;
$heat_number = $_GET['heat_number'] ?? null;

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

$output = fopen("php://output", "w");
fputcsv($output, ['Heat', 'BIB', 'Name', 'Club', 'Category']);

$stmt = $pdo->prepare("
    SELECT ep.heat_number, p.bib, CONCAT(p.first_name, ' ', p.last_name) AS name, p.club, p.category
    FROM event_participants ep
    JOIN participants p ON ep.participant_id = p.id
    WHERE ep.event_id = ? AND (? IS NULL OR ep.heat_number = ?)
    ORDER BY ep.heat_number, p.bib
");
$stmt->execute([$event_id, $heat_number, $heat_number]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    fputcsv($output, $row);
}
fclose($output);
exit;
?>
