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

echo "<h2>Fix Event 3 Data Mismatch</h2>";

// Check current event data
$stmt = $pdo->prepare("SELECT * FROM events WHERE id = 3");
$stmt->execute();
$event = $stmt->fetch(PDO::FETCH_ASSOC);

if ($event) {
    echo "<h3>Current Event 3 Data:</h3>";
    echo "<ul>";
    echo "<li><strong>sport_discipline:</strong> '{$event['sport_discipline']}'</li>";
    echo "<li><strong>scoring_format:</strong> '{$event['scoring_format']}'</li>";
    echo "<li><strong>scoring_mode:</strong> '{$event['scoring_mode']}'</li>";
    echo "<li><strong>location:</strong> '{$event['location']}'</li>";
    echo "</ul>";
}

// Check available sports
echo "<h3>Available Sports:</h3>";
$sports_stmt = $pdo->query("SELECT sport_name FROM figure_sports WHERE is_active = 1 ORDER BY sport_name");
$sports = $sports_stmt->fetchAll(PDO::FETCH_COLUMN);
echo "<ul>";
foreach ($sports as $sport) {
    $matches = $sport === $event['sport_discipline'];
    echo "<li><strong>$sport</strong>" . ($matches ? " ← MATCHES" : "") . "</li>";
}
echo "</ul>";

// Check available formats - look for both ID-based and name-based
echo "<h3>Available Scoring Formats:</h3>";
$formats_stmt = $pdo->query("SELECT format_id, name, sport FROM scoring_formats WHERE is_active = 1 ORDER BY sport, name");
$formats = $formats_stmt->fetchAll(PDO::FETCH_ASSOC);

echo "<table border='1' style='border-collapse: collapse;'>";
echo "<tr><th>Format ID</th><th>Name</th><th>Sport</th><th>Match Type</th></tr>";

$found_match = false;
foreach ($formats as $format) {
    $id_match = $format['format_id'] == $event['scoring_format'];
    $name_match = $format['name'] === $event['scoring_format'];
    $match_type = '';
    
    if ($id_match) {
        $match_type = 'ID MATCH';
        $found_match = true;
    } elseif ($name_match) {
        $match_type = 'NAME MATCH';  
        $found_match = true;
    }
    
    echo "<tr" . ($id_match || $name_match ? " style='background: yellow;'" : "") . ">";
    echo "<td>{$format['format_id']}</td>";
    echo "<td>" . htmlspecialchars($format['name']) . "</td>";
    echo "<td>" . htmlspecialchars($format['sport']) . "</td>";
    echo "<td><strong>$match_type</strong></td>";
    echo "</tr>";
}
echo "</table>";

if (!$found_match) {
    echo "<p style='color: red;'>❌ No matching format found for '{$event['scoring_format']}'</p>";
    
    // Try to find a close match
    echo "<h4>Looking for similar formats:</h4>";
    foreach ($formats as $format) {
        if (stripos($format['name'], 'snowboard') !== false || 
            stripos($format['sport'], 'snowboard') !== false ||
            stripos($format['name'], 'big_air') !== false) {
            echo "<div>Similar: ID {$format['format_id']} - {$format['name']} ({$format['sport']})</div>";
        }
    }
    
    echo "<h4>Fix Options:</h4>";
    echo "<p>1. <a href='?fix=create_format&id=3'>Create missing format 'snowboard_big_air_best_two'</a></p>";
    echo "<p>2. <a href='?fix=update_to_existing&id=3'>Update event to use existing format</a></p>";
}

// Handle fix actions
if (isset($_GET['fix'])) {
    if ($_GET['fix'] === 'create_format') {
        // Create the missing format
        $stmt = $pdo->prepare("
            INSERT IGNORE INTO scoring_formats (name, sport, is_active, description) 
            VALUES (?, 'snowboard', 1, 'Auto-created format for existing event')
        ");
        if ($stmt->execute(['snowboard_big_air_best_two'])) {
            $new_format_id = $pdo->lastInsertId();
            echo "<p style='color: green;'>✅ Created format with ID: $new_format_id</p>";
            
            // Update event to use the new numeric ID
            $update_stmt = $pdo->prepare("UPDATE events SET scoring_format = ? WHERE id = 3");
            if ($update_stmt->execute([$new_format_id])) {
                echo "<p style='color: green;'>✅ Updated event to use format ID: $new_format_id</p>";
            }
        }
    } elseif ($_GET['fix'] === 'update_to_existing') {
        // Find best existing format for snowboard
        $best_format = null;
        foreach ($formats as $format) {
            if (stripos($format['sport'], 'snowboard') !== false) {
                $best_format = $format;
                break;
            }
        }
        
        if ($best_format) {
            $update_stmt = $pdo->prepare("UPDATE events SET scoring_format = ? WHERE id = 3");
            if ($update_stmt->execute([$best_format['format_id']])) {
                echo "<p style='color: green;'>✅ Updated event to use format: {$best_format['name']} (ID: {$best_format['format_id']})</p>";
            }
        }
    }
}

echo "<hr><p><a href='event_edit.php?id=3' target='_blank'>Test Form Again</a></p>";
?>