<?php
/**
 * Debug Bracket Scores
 * Check if scores are being loaded correctly
 */

include 'includes/db.php';

$event_id = 6;

echo "<h2>Debug Bracket Scores for Event $event_id</h2>";

// Check participants
echo "<h3>Participants in Event</h3>";
$stmt = $pdo->prepare("SELECT id, first_name, last_name FROM participants WHERE event_id = ?");
$stmt->execute([$event_id]);
$participants = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($participants);
echo "</pre>";

// Check event_participants with heats
echo "<h3>Event Participants (with heats)</h3>";
$stmt = $pdo->prepare("SELECT id, participant_id, heat_number, bib_number FROM event_participants WHERE event_id = ?");
$stmt->execute([$event_id]);
$event_participants = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($event_participants);
echo "</pre>";

// Check runs
echo "<h3>Runs</h3>";
$stmt = $pdo->prepare("
    SELECT r.id, r.event_participant_id, r.run_number, ep.participant_id, ep.heat_number
    FROM runs r
    JOIN event_participants ep ON r.event_participant_id = ep.id
    WHERE ep.event_id = ?
");
$stmt->execute([$event_id]);
$runs = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($runs);
echo "</pre>";

// Check scores
echo "<h3>Scores</h3>";
$stmt = $pdo->prepare("
    SELECT s.id, s.run_id, s.score_value, s.is_approved, r.run_number, ep.participant_id, ep.heat_number
    FROM scores s
    JOIN runs r ON s.run_id = r.id
    JOIN event_participants ep ON r.event_participant_id = ep.id
    WHERE ep.event_id = ?
");
$stmt->execute([$event_id]);
$scores = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($scores);
echo "</pre>";

// Test the exact query from the API
echo "<h3>API Query Test (Approved Scores)</h3>";
$stmt = $pdo->prepare("
    SELECT ep.participant_id, r.run_number, s.score_value
    FROM event_participants ep
    JOIN runs r ON r.event_participant_id = ep.id
    JOIN scores s ON s.run_id = r.id
    WHERE ep.event_id = ? AND s.is_approved = 1
    ORDER BY ep.participant_id, r.run_number
");
$stmt->execute([$event_id]);
$api_scores = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($api_scores);
echo "</pre>";
echo "<p><strong>Count: " . count($api_scores) . " approved scores found</strong></p>";
