<?php
// Test scoring layout configuration database integration
require_once 'includes/db.php';

echo "<h2>Testing Scoring Layout Configuration Database Integration</h2>";

// 1. Check if columns exist
echo "<h3>1. Database Schema Check</h3>";

try {
    // Check events table for scoring_layout_config column
    $eventsCheck = $pdo->query("DESCRIBE events");
    $eventsColumns = $eventsCheck->fetchAll(PDO::FETCH_COLUMN);
    
    $hasEventsColumn = in_array('scoring_layout_config', $eventsColumns);
    echo "<strong>Events table scoring_layout_config column:</strong> " . 
         ($hasEventsColumn ? "<span style='color:green'>EXISTS</span>" : "<span style='color:red'>MISSING</span>") . "<br>";
    
    // Check event_heat_settings table for scoring_layout_config column
    $heatCheck = $pdo->query("DESCRIBE event_heat_settings");
    $heatColumns = $heatCheck->fetchAll(PDO::FETCH_COLUMN);
    
    $hasHeatColumn = in_array('scoring_layout_config', $heatColumns);
    echo "<strong>Event_heat_settings table scoring_layout_config column:</strong> " . 
         ($hasHeatColumn ? "<span style='color:green'>EXISTS</span>" : "<span style='color:red'>MISSING</span>") . "<br>";
    
    if (!$hasEventsColumn || !$hasHeatColumn) {
        echo "<div style='background:#ffebee; padding:10px; margin:10px 0; border-left:4px solid #f44336;'>";
        echo "<strong>ACTION REQUIRED:</strong> Missing database columns. Run this SQL to add them:<br><br>";
        if (!$hasEventsColumn) {
            echo "<code>ALTER TABLE events ADD COLUMN scoring_layout_config JSON NULL;</code><br>";
        }
        if (!$hasHeatColumn) {
            echo "<code>ALTER TABLE event_heat_settings ADD COLUMN scoring_layout_config JSON NULL;</code><br>";
        }
        echo "</div>";
    }
    
} catch (Exception $e) {
    echo "<span style='color:red'>Error checking database schema: " . $e->getMessage() . "</span><br>";
}

// 2. Test data operations (only if columns exist)
if ($hasEventsColumn && $hasHeatColumn) {
    echo "<h3>2. Data Operations Test</h3>";
    
    // Get a test event
    $testEventQuery = $pdo->query("SELECT id, name, scoring_layout_config FROM events LIMIT 1");
    $testEvent = $testEventQuery->fetch(PDO::FETCH_ASSOC);
    
    if ($testEvent) {
        echo "<strong>Test Event:</strong> ID {$testEvent['id']} - {$testEvent['name']}<br>";
        
        // Show current configuration
        $currentConfig = $testEvent['scoring_layout_config'];
        echo "<strong>Current Configuration:</strong> ";
        if ($currentConfig) {
            echo "<pre>" . htmlspecialchars($currentConfig) . "</pre>";
            $decoded = json_decode($currentConfig, true);
            if ($decoded) {
                echo "<strong>Decoded Configuration:</strong><br>";
                echo "<pre>" . print_r($decoded, true) . "</pre>";
            }
        } else {
            echo "<em>NULL (no configuration set)</em><br>";
        }
        
        // Test saving a sample configuration
        $sampleConfig = [
            'cards' => [
                'criteriaInputGrid' => ['enabled' => true],
                'finalCalculatedScore' => ['enabled' => true],
                'figuresCard' => ['enabled' => false],
                'latestScores' => ['enabled' => true]
            ],
            'layout' => [
                'compactMode' => false,
                'hideEmptyCards' => false
            ]
        ];
        
        $configJson = json_encode($sampleConfig);
        echo "<h4>Testing Configuration Save</h4>";
        echo "<strong>Sample Configuration to Save:</strong><br>";
        echo "<pre>" . htmlspecialchars($configJson) . "</pre>";
        
        try {
            $updateStmt = $pdo->prepare("UPDATE events SET scoring_layout_config = ? WHERE id = ?");
            $result = $updateStmt->execute([$configJson, $testEvent['id']]);
            
            if ($result) {
                echo "<span style='color:green'>✓ Configuration saved successfully!</span><br>";
                
                // Verify it was saved
                $verifyStmt = $pdo->prepare("SELECT scoring_layout_config FROM events WHERE id = ?");
                $verifyStmt->execute([$testEvent['id']]);
                $savedConfig = $verifyStmt->fetchColumn();
                
                echo "<strong>Verified Saved Configuration:</strong><br>";
                echo "<pre>" . htmlspecialchars($savedConfig) . "</pre>";
                
                $decodedSaved = json_decode($savedConfig, true);
                if ($decodedSaved) {
                    echo "<span style='color:green'>✓ Configuration can be decoded properly!</span><br>";
                    echo "<strong>Decoded Saved Configuration:</strong><br>";
                    echo "<pre>" . print_r($decodedSaved, true) . "</pre>";
                } else {
                    echo "<span style='color:red'>✗ Error decoding saved configuration!</span><br>";
                }
                
            } else {
                echo "<span style='color:red'>✗ Failed to save configuration!</span><br>";
            }
            
        } catch (Exception $e) {
            echo "<span style='color:red'>Error saving configuration: " . $e->getMessage() . "</span><br>";
        }
        
        // Test heat-level configuration
        echo "<h4>Testing Heat-Level Configuration</h4>";
        
        $heatQuery = $pdo->prepare("SELECT * FROM event_heat_settings WHERE event_id = ? LIMIT 1");
        $heatQuery->execute([$testEvent['id']]);
        $testHeat = $heatQuery->fetch(PDO::FETCH_ASSOC);
        
        if ($testHeat) {
            echo "<strong>Test Heat:</strong> Heat {$testHeat['heat_number']} for Event {$testEvent['id']}<br>";
            
            $heatSampleConfig = [
                'cards' => [
                    'criteriaInputGrid' => ['enabled' => false], // Override event default
                    'figuresCard' => ['enabled' => true]         // Override event default
                ],
                'layout' => [
                    'compactMode' => true // Override event default
                ]
            ];
            
            $heatConfigJson = json_encode($heatSampleConfig);
            echo "<strong>Sample Heat Configuration to Save:</strong><br>";
            echo "<pre>" . htmlspecialchars($heatConfigJson) . "</pre>";
            
            try {
                $heatUpdateStmt = $pdo->prepare("UPDATE event_heat_settings SET scoring_layout_config = ? WHERE id = ?");
                $heatResult = $heatUpdateStmt->execute([$heatConfigJson, $testHeat['id']]);
                
                if ($heatResult) {
                    echo "<span style='color:green'>✓ Heat configuration saved successfully!</span><br>";
                    
                    // Verify heat configuration
                    $heatVerifyStmt = $pdo->prepare("SELECT scoring_layout_config FROM event_heat_settings WHERE id = ?");
                    $heatVerifyStmt->execute([$testHeat['id']]);
                    $savedHeatConfig = $heatVerifyStmt->fetchColumn();
                    
                    echo "<strong>Verified Saved Heat Configuration:</strong><br>";
                    echo "<pre>" . htmlspecialchars($savedHeatConfig) . "</pre>";
                    
                } else {
                    echo "<span style='color:red'>✗ Failed to save heat configuration!</span><br>";
                }
                
            } catch (Exception $e) {
                echo "<span style='color:red'>Error saving heat configuration: " . $e->getMessage() . "</span><br>";
            }
            
        } else {
            echo "<em>No heat settings found for this event</em><br>";
        }
        
        // Test ScoringLayoutConfig helper class
        echo "<h4>Testing ScoringLayoutConfig Helper Class</h4>";
        
        if (file_exists(__DIR__ . '/includes/ScoringLayoutConfig.php')) {
            require_once 'includes/ScoringLayoutConfig.php';
            
            try {
                $effectiveConfig = ScoringLayoutConfig::getEffectiveConfig($pdo, $testEvent['id'], 1);
                echo "<strong>Effective Configuration (Event + Heat 1):</strong><br>";
                echo "<pre>" . print_r($effectiveConfig, true) . "</pre>";
                
                // Test component checks
                $testComponents = ['criteriaInputGrid', 'finalCalculatedScore', 'figuresCard', 'latestScores'];
                foreach ($testComponents as $component) {
                    $enabled = ScoringLayoutConfig::isComponentEnabled($effectiveConfig, $component);
                    echo "• {$component}: " . ($enabled ? "<span style='color:green'>ENABLED</span>" : "<span style='color:red'>DISABLED</span>") . "<br>";
                }
                
            } catch (Exception $e) {
                echo "<span style='color:red'>Error testing ScoringLayoutConfig: " . $e->getMessage() . "</span><br>";
            }
            
        } else {
            echo "<span style='color:orange'>ScoringLayoutConfig.php not found</span><br>";
        }
        
    } else {
        echo "<em>No events found in database for testing</em><br>";
    }
}

echo "<h3>3. Integration Test Complete</h3>";
echo "<p>If all checks pass, the scoring layout configuration should be working properly in the admin interfaces.</p>";
?>