<?php
require_once '../includes/auth.php';
require_once '../includes/fpdf/fpdf.php';
require_once '../includes/db.php';

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

class PDF extends FPDF {
    function Header() {
        //$this->Image('../assets/logo.png', 10, 6, 30);
        $this->SetFont('Arial', 'B', 14);
        $this->Cell(0, 10, 'Heat Assignments Report', 0, 1, 'C');
        $this->Ln(5);
    }
}

$pdf = new PDF();
$pdf->AddPage();
$pdf->SetFont('Arial', '', 12);

$header = ['Heat', 'BIB', 'Name', 'Club', 'Category'];
foreach ($header as $col) {
    $pdf->Cell(38, 10, $col, 1);
}
$pdf->Ln();

$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_NUM)) {
    foreach ($row as $col) {
        $pdf->Cell(38, 10, $col, 1);
    }
    $pdf->Ln();
}
$pdf->Output('D', 'heat_assignments.pdf');
exit;
?>
