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

echo "<h2>Find Events with Data</h2>";

// Find events with sport_discipline, location, and scoring_format
$stmt = $pdo->query("
    SELECT id, name, location, sport_discipline, scoring_format, scoring_mode, status, created_at 
    FROM events 
    WHERE sport_discipline IS NOT NULL 
       OR location IS NOT NULL 
       OR scoring_format IS NOT NULL
    ORDER BY id DESC
    LIMIT 10
");

$events = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($events)) {
    echo "<p>No events found with data. Let's create some test data.</p>";
    
    // Create a test event with data
    $stmt = $pdo->prepare("
        INSERT INTO events (name, location, sport_discipline, scoring_format, scoring_mode, status, date, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    $stmt->execute([
        'Test Event with Data',
        'Test Location Skate Park',
        'skateboarding', 
        '1', // Assuming format ID 1 exists
        'best',
        'draft',
        date('Y-m-d', strtotime('+1 week'))
    ]);
    
    $newEventId = $pdo->lastInsertId();
    echo "<p>Created test event with ID: $newEventId</p>";
    echo "<a href='event_edit.php?id=$newEventId'>Edit Test Event</a>";
    
} else {
    echo "<table border='1'>";
    echo "<tr><th>ID</th><th>Name</th><th>Location</th><th>Sport</th><th>Format</th><th>Mode</th><th>Actions</th></tr>";
    foreach ($events as $event) {
        echo "<tr>";
        echo "<td>{$event['id']}</td>";
        echo "<td>" . htmlspecialchars($event['name'] ?? '') . "</td>";
        echo "<td>" . htmlspecialchars($event['location'] ?? 'NULL') . "</td>";
        echo "<td>" . htmlspecialchars($event['sport_discipline'] ?? 'NULL') . "</td>";
        echo "<td>" . htmlspecialchars($event['scoring_format'] ?? 'NULL') . "</td>";
        echo "<td>" . htmlspecialchars($event['scoring_mode'] ?? 'NULL') . "</td>";
        echo "<td><a href='event_edit.php?id={$event['id']}'>Edit</a></td>";
        echo "</tr>";
    }
    echo "</table>";
}

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);
foreach ($sports as $sport) {
    echo "- $sport<br>";
}

echo "<h3>Available 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);
foreach ($formats as $format) {
    echo "- ID {$format['format_id']}: {$format['name']} ({$format['sport']})<br>";
}
?>