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

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

// Debug: Log session ID and all session data
error_log("get_participants.php - Session ID: " . session_id());
error_log("get_participants.php - SESSION DATA: " . json_encode($_SESSION));
error_log("get_participants.php - Cookie: " . ($_COOKIE[session_name()] ?? 'NO COOKIE'));

$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;

// Get judge_id from session - ONLY use user_id (judge_id is deprecated/legacy)
$judge_id = $_SESSION['user_id'] ?? 0;

if (!$judge_id) {
    echo json_encode(['error' => 'No judge ID found in session']);
    exit;
}

// Debug: Log the judge_id being used
error_log("get_participants.php - Judge ID: $judge_id, Event: $event_id, Heat: $heat_number, Run: $run_number");

// Get all participants for this heat
$stmt = $pdo->prepare("SELECT ep.id as ep_id, p.first_name, p.last_name, p.country, 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 (regardless of head judge approval)
// A judge shouldn't be able to score the same participant twice, even if not yet approved
$scored_stmt = $pdo->prepare("
    SELECT DISTINCT r.event_participant_id
    FROM scores s
    JOIN runs r ON s.run_id = r.id
    JOIN event_participants ep ON r.event_participant_id = ep.id
    WHERE s.judge_id = ? 
      AND r.run_number = ? 
      AND 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);

// Debug: Log which participants are scored
error_log("get_participants.php - Scored event_participant_ids for judge $judge_id (run $run_number): " . json_encode($scored));

foreach ($participants as &$p) {
    $p['locked'] = in_array($p['ep_id'], $scored);
    // Debug: Log each participant's lock status
    if ($p['locked']) {
        error_log("get_participants.php - Locking participant BIB {$p['bib']} (ep_id: {$p['ep_id']})");
    }
}

// Add debug info to response
$response = [
    'participants' => $participants,
    'debug' => [
        'judge_id' => $judge_id,
        'event_id' => $event_id,
        'heat_number' => $heat_number,
        'run_number' => $run_number,
        'scored_ep_ids' => $scored,
        'total_locked' => count($scored)
    ]
];

echo json_encode($response);
?>
