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

echo "<h2>Scoring Layout Configuration Check</h2>";

// Check for event 3 specifically
$stmt = $pdo->prepare("SELECT * FROM scoring_layout_configs WHERE event_id = ?");
$stmt->execute([3]);
$configs = $stmt->fetchAll();

echo "<h3>Event 3 Configurations:</h3>";
if (empty($configs)) {
    echo "<p><strong>No configurations found for Event 3</strong></p>";
    
    // Show all available configurations
    $allStmt = $pdo->query("SELECT * FROM scoring_layout_configs ORDER BY event_id, heat_number");
    $allConfigs = $allStmt->fetchAll();
    
    echo "<h3>All Available Configurations:</h3>";
    if (empty($allConfigs)) {
        echo "<p><em>No scoring layout configurations exist in database</em></p>";
    } else {
        echo "<table border='1' style='border-collapse: collapse;'>";
        echo "<tr><th>Event ID</th><th>Heat Number</th><th>Configuration (first 200 chars)</th></tr>";
        foreach ($allConfigs as $config) {
            $configPreview = substr($config['configuration'], 0, 200);
            echo "<tr>";
            echo "<td>" . htmlspecialchars($config['event_id']) . "</td>";
            echo "<td>" . htmlspecialchars($config['heat_number'] ?? 'ALL') . "</td>";
            echo "<td>" . htmlspecialchars($configPreview) . "...</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
} else {
    echo "<table border='1' style='border-collapse: collapse;'>";
    echo "<tr><th>Event ID</th><th>Heat Number</th><th>Configuration</th></tr>";
    foreach ($configs as $config) {
        echo "<tr>";
        echo "<td>" . htmlspecialchars($config['event_id']) . "</td>";
        echo "<td>" . htmlspecialchars($config['heat_number'] ?? 'ALL') . "</td>";
        echo "<td><pre>" . htmlspecialchars($config['configuration']) . "</pre></td>";
        echo "</tr>";
    }
    echo "</table>";
}

// Test the ScoringLayoutConfig class directly
echo "<h3>Testing ScoringLayoutConfig for Event 3:</h3>";
try {
    require_once 'includes/ScoringLayoutConfig.php';
    $effectiveConfig = ScoringLayoutConfig::getEffectiveConfig($pdo, 3, 1);
    
    if ($effectiveConfig) {
        echo "<p><strong>Effective configuration found:</strong></p>";
        echo "<pre>" . htmlspecialchars(print_r($effectiveConfig, true)) . "</pre>";
        
        echo "<h4>Generated JavaScript:</h4>";
        $script = ScoringLayoutConfig::generateApplyScript($effectiveConfig);
        echo "<textarea style='width:100%; height:200px;'>" . htmlspecialchars($script) . "</textarea>";
    } else {
        echo "<p><em>No effective configuration for Event 3, Heat 1</em></p>";
    }
} catch (Exception $e) {
    echo "<p style='color:red;'>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
}

// Check if the judge panel is loading the configuration properly
echo "<h3>Judge Panel Configuration Loading Test:</h3>";
echo "<a href='judge/score.php?event_id=3&heat_number=1' target='_blank'>Open Judge Panel for Event 3</a>";
?>