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

echo "=== HEAT SETTINGS FOR EVENT 6 ===\n\n";
$stmt = $pdo->query("SELECT heat_number, categories, runs_count FROM event_heat_settings WHERE event_id = 6 ORDER BY heat_number");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "Heat {$row['heat_number']}:\n";
    echo "  Categories JSON: {$row['categories']}\n";
    echo "  Runs: {$row['runs_count']}\n";
    
    if ($row['categories']) {
        $cat_ids = json_decode($row['categories'], true);
        if (is_array($cat_ids)) {
            echo "  Category IDs: " . implode(', ', $cat_ids) . "\n";
            
            foreach ($cat_ids as $cid) {
                $cat_stmt = $pdo->prepare("SELECT category_name FROM event_categories WHERE id = ?");
                $cat_stmt->execute([$cid]);
                $cat_name = $cat_stmt->fetchColumn();
                echo "    - ID $cid: $cat_name\n";
            }
        }
    }
    echo "\n";
}

echo "\n=== PARTICIPANT CATEGORY ASSIGNMENTS ===\n\n";
$stmt = $pdo->query("
    SELECT 
        p.bib_number,
        p.first_name,
        p.last_name,
        ep.category,
        ep.category_id,
        ep.heat_number,
        ec.category_name
    FROM event_participants ep
    JOIN participants p ON ep.participant_id = p.id
    LEFT JOIN event_categories ec ON ep.category_id = ec.id
    WHERE ep.event_id = 6
    ORDER BY ep.heat_number, p.bib_number
");

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "BIB {$row['bib_number']} - Heat {$row['heat_number']}: {$row['first_name']} {$row['last_name']}\n";
    echo "  Old category field: '{$row['category']}'\n";
    echo "  category_id: " . ($row['category_id'] ?? 'NULL') . "\n";
    echo "  Resolved name: " . ($row['category_name'] ?? 'NULL') . "\n\n";
}
