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

$event_id = $_GET['event_id'] ?? 0;
$heat_number = $_GET['heat'] ?? 1;

header('Content-Type: application/json');

$query = "
    SELECT 
        p.bib, p.first_name, p.last_name, p.category, p.club,
        r.run_number, r.id AS run_id,
        AVG(s.score_value) as avg_score,
        GROUP_CONCAT(CONCAT(j.name, ': ', s.score_value, ' (', s.status, ')') ORDER BY j.id SEPARATOR ', ') as judges_scores
    FROM runs r
    JOIN event_participants ep ON r.event_participant_id = ep.id
    JOIN participants p ON ep.participant_id = p.id
    LEFT JOIN scores s ON r.id = s.run_id
    LEFT JOIN judges j ON s.judge_id = j.id
    WHERE ep.event_id = ?
      AND ep.heat_number = ?
    GROUP BY r.id
    ORDER BY avg_score DESC
";

$stmt = $pdo->prepare($query);
$stmt->execute([$event_id, $heat_number]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($results);
?>
