<?php
include '../includes/auth.php';
include '../includes/db.php';

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

$event_id = isset($_GET['event_id']) ? intval($_GET['event_id']) : 0;
$heat_number = isset($_GET['heat_number']) ? intval($_GET['heat_number']) : 0;
$run_number = isset($_GET['run_number']) ? intval($_GET['run_number']) : 0;
$judge_id = $_SESSION['judge_id'];

// Get all participants for this heat
$stmt = $pdo->prepare("SELECT ep.id as ep_id, p.first_name, p.last_name, ep.bib_number as bib, ep.heat_number
                       FROM event_participants ep
                       JOIN participants p ON ep.participant_id = p.id
                       WHERE ep.event_id = ? AND ep.heat_number = ?
                       ORDER BY ep.sort_order ASC, ep.bib_number ASC");
$stmt->execute([$event_id, $heat_number]);
$participants = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Check which ones have been scored by this judge
$scored_stmt = $pdo->prepare("
    SELECT r.event_participant_id
    FROM scores s
    JOIN runs r ON s.run_id = r.id
    WHERE s.judge_id = ? AND r.run_number = ? AND r.event_participant_id IN (
        SELECT ep.id FROM event_participants ep WHERE ep.event_id = ? AND ep.heat_number = ?
    )
");
$scored_stmt->execute([$judge_id, $run_number, $event_id, $heat_number]);
$scored = $scored_stmt->fetchAll(PDO::FETCH_COLUMN);

foreach ($participants as &$p) {
    $p['locked'] = in_array($p['ep_id'], $scored);
}

echo json_encode($participants);
?>
