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

echo "<h1>🔧 Setup Scoring Layout Database Table</h1>";

try {
    // Create the scoring_layout_configs table
    $createTableSQL = "
    CREATE TABLE IF NOT EXISTS `scoring_layout_configs` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `event_id` int(11) NOT NULL,
        `heat_number` int(11) DEFAULT NULL COMMENT 'NULL means applies to all heats',
        `configuration` TEXT NOT NULL COMMENT 'JSON configuration for layout',
        `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
        `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        UNIQUE KEY `unique_event_heat` (`event_id`, `heat_number`),
        KEY `idx_event_id` (`event_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Scoring layout configurations for judge panels';
    ";
    
    $pdo->exec($createTableSQL);
    echo "<p><strong style='color: green; font-size: 18px;'>✅ Table 'scoring_layout_configs' created successfully!</strong></p>";
    
    // Now create a DRAMATIC test configuration for Event 3 that hides most components
    $testConfig = [
        'cards' => [
            'criteriaInputGrid' => ['enabled' => false], // HIDE criteria input
            'finalCalculatedScore' => ['enabled' => true],  // SHOW final score 
            'figuresCard' => ['enabled' => false], // HIDE figures card
            'latestScores' => ['enabled' => false], // HIDE latest scores table
            'otherHeatScores' => ['enabled' => false], // HIDE other scores
            'diversityValidation' => ['enabled' => false], // HIDE diversity validation
            'figureHistory' => ['enabled' => false], // HIDE figure history
            'formatInfo' => ['enabled' => false] // HIDE format info
        ],
        'layout' => [
            'compactMode' => false,
            'hideEmptyCards' => true
        ]
    ];
    
    // Delete any existing configuration for Event 3 first
    $deleteStmt = $pdo->prepare("DELETE FROM scoring_layout_configs WHERE event_id = ?");
    $deleteStmt->execute([3]);
    
    $stmt = $pdo->prepare("INSERT INTO scoring_layout_configs (event_id, heat_number, configuration, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())");
    
    $configJson = json_encode($testConfig);
    $stmt->execute([3, null, $configJson]); // null heat_number means applies to all heats
    
    echo "<p><strong style='color: red; font-size: 18px;'>⚠️ DRAMATIC Test configuration created for Event 3!</strong></p>";
    echo "<p style='background: #ffeb3b; padding: 10px; border-radius: 5px;'><strong>This configuration should make most components INVISIBLE on Event 3!</strong></p>";
    
    echo "<div style='display: flex; gap: 20px;'>";
    
    echo "<div style='background: #ffcdd2; padding: 15px; border-radius: 5px; flex: 1;'>";
    echo "<h3 style='color: #d32f2f;'>❌ HIDDEN Components on Event 3:</h3>";
    echo "<ul style='color: #d32f2f; font-weight: bold;'>";
    echo "<li>Criteria Input Grid</li>";
    echo "<li>Figures Card</li>";
    echo "<li>Latest Scores Table</li>";
    echo "<li>Other Heat Scores</li>";
    echo "<li>Diversity Validation</li>";
    echo "<li>Figure History</li>";
    echo "<li>Format Information</li>";
    echo "</ul>";
    echo "</div>";
    
    echo "<div style='background: #c8e6c9; padding: 15px; border-radius: 5px; flex: 1;'>";
    echo "<h3 style='color: #388e3c;'>✅ VISIBLE Components on Event 3:</h3>";
    echo "<ul style='color: #388e3c; font-weight: bold;'>";
    echo "<li>Final Score Display</li>";
    echo "<li>Participant Selection</li>";
    echo "<li>Submit Button</li>";
    echo "</ul>";
    echo "</div>";
    
    echo "</div>";
    
    // Create a normal configuration for Event 1 for comparison
    $normalConfig = [
        'cards' => [
            'criteriaInputGrid' => ['enabled' => true],
            'finalCalculatedScore' => ['enabled' => true],
            'figuresCard' => ['enabled' => true],
            'latestScores' => ['enabled' => true],
            'otherHeatScores' => ['enabled' => true],
            'diversityValidation' => ['enabled' => true],
            'figureHistory' => ['enabled' => true],
            'formatInfo' => ['enabled' => true]
        ],
        'layout' => [
            'compactMode' => false,
            'hideEmptyCards' => true
        ]
    ];
    
    // Delete any existing configuration for Event 1 first
    $deleteStmt->execute([1]);
    
    $normalConfigJson = json_encode($normalConfig);
    $stmt->execute([1, null, $normalConfigJson]);
    
    echo "<p><strong style='color: green; font-size: 18px;'>✅ Normal configuration (ALL components visible) created for Event 1!</strong></p>";
    
    echo "<h2 style='background: #2196f3; color: white; padding: 15px; border-radius: 5px;'>🧪 TEST THE DIFFERENCES:</h2>";
    
    echo "<div style='text-align: center; margin: 20px 0;'>";
    echo "<a href='judge/score.php?event_id=3&heat_number=1' target='_blank' style='background: #f44336; color: white; padding: 15px 30px; text-decoration: none; font-weight: bold; border-radius: 5px; margin: 10px; display: inline-block; font-size: 16px;'>🔴 EVENT 3 (Most Components HIDDEN)</a>";
    echo "<br><br>";
    echo "<a href='judge/score.php?event_id=1&heat_number=1' target='_blank' style='background: #4caf50; color: white; padding: 15px 30px; text-decoration: none; font-weight: bold; border-radius: 5px; margin: 10px; display: inline-block; font-size: 16px;'>🟢 EVENT 1 (All Components VISIBLE)</a>";
    echo "</div>";
    
    // Show the created configurations
    echo "<h3>📋 Database Configurations Created:</h3>";
    $checkStmt = $pdo->query("SELECT event_id, heat_number, configuration FROM scoring_layout_configs ORDER BY event_id");
    $configs = $checkStmt->fetchAll();
    
    echo "<table border='1' style='border-collapse: collapse; width: 100%; margin-top: 15px;'>";
    echo "<tr style='background: #f5f5f5;'><th style='padding: 10px;'>Event</th><th style='padding: 10px;'>Heat</th><th style='padding: 10px;'>Configuration Summary</th></tr>";
    foreach ($configs as $config) {
        $configData = json_decode($config['configuration'], true);
        $enabledComponents = [];
        $disabledComponents = [];
        
        foreach ($configData['cards'] as $component => $settings) {
            if ($settings['enabled']) {
                $enabledComponents[] = $component;
            } else {
                $disabledComponents[] = $component;
            }
        }
        
        echo "<tr>";
        echo "<td style='padding: 10px; font-weight: bold;'>" . $config['event_id'] . "</td>";
        echo "<td style='padding: 10px;'>" . ($config['heat_number'] ?? 'ALL') . "</td>";
        echo "<td style='padding: 10px;'>";
        echo "<strong style='color: #4caf50;'>✅ Enabled:</strong> " . implode(', ', $enabledComponents) . "<br>";
        echo "<strong style='color: #f44336;'>❌ Disabled:</strong> " . implode(', ', $disabledComponents);
        echo "</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    echo "<h2 style='color: #ff9800;'>🎯 Expected Results:</h2>";
    echo "<p><strong>When you open Event 3:</strong> You should see a very minimal interface with only essential components.</p>";
    echo "<p><strong>When you open Event 1:</strong> You should see the full interface with all components visible.</p>";
    echo "<p style='background: #e3f2fd; padding: 10px; border-radius: 5px;'><strong>💡 Tip:</strong> Open both links in separate tabs to compare side by side!</p>";
    
} catch (Exception $e) {
    echo "<p style='color:red; background: #ffebee; padding: 15px; border-radius: 5px;'><strong>❌ Error:</strong> " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<details>";
    echo "<summary>Stack trace:</summary>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
    echo "</details>";
}
?>

<style>
body { 
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
    margin: 20px; 
    line-height: 1.6;
}
table { 
    margin-top: 10px; 
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
th, td { 
    padding: 12px; 
    text-align: left; 
    border-bottom: 1px solid #ddd;
}
th { 
    background-color: #f8f9fa; 
    font-weight: 600;
}
h1, h2, h3 {
    margin-top: 30px;
}
</style>