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

$event_id = $_GET['event_id'] ?? 3;

echo "=== EVENT $event_id DEBUG ===\n\n";

// Check event exists
try {
    $stmt = $pdo->prepare("SELECT * FROM events WHERE id = ?");
    $stmt->execute([$event_id]);
    $event = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($event) {
        echo "✅ Event found: " . $event['name'] . "\n";
    } else {
        echo "❌ Event $event_id not found!\n";
        exit;
    }
} catch (Exception $e) {
    echo "❌ Database error: " . $e->getMessage() . "\n";
    exit;
}

// Check participants
try {
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM event_participants WHERE event_id = ?");
    $stmt->execute([$event_id]);
    $result = $stmt->fetch();
    echo "Participants: {$result['count']}\n";
} catch (Exception $e) {
    echo "❌ Participants check error: " . $e->getMessage() . "\n";
}

// Check publish servers for this event
try {
    $stmt = $pdo->prepare("SELECT * FROM publish_servers WHERE event_id = ?");
    $stmt->execute([$event_id]);
    $servers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "\nPublish Servers for Event $event_id:\n";
    foreach ($servers as $server) {
        echo "- {$server['name']}: {$server['data_types']}\n";
        $decoded = json_decode($server['data_types'], true);
        echo "  Decoded: " . implode(', ', $decoded ?: []) . "\n";
    }
} catch (Exception $e) {
    echo "❌ Servers check error: " . $e->getMessage() . "\n";
}

// Test file generation
echo "\n=== FILE GENERATION TEST ===\n";
$temp_dir = sys_get_temp_dir() . '/debug_event_' . $event_id . '_' . time();
mkdir($temp_dir, 0755, true);

// Test each type
$types = ['HTML', 'JSON', 'CSV'];
foreach ($types as $type) {
    echo "\nTesting $type generation...\n";
    try {
        switch ($type) {
            case 'HTML':
                $files = generateHTMLDashboard($event_id, $temp_dir, $pdo);
                break;
            case 'JSON':
                $files = generateJSONData($event_id, $temp_dir, $pdo);
                break;
            case 'CSV':
                $files = generateCSVData($event_id, $temp_dir, $pdo);
                break;
        }
        
        echo "✅ $type: Generated " . count($files) . " files\n";
        foreach ($files as $file) {
            $size = file_exists($file['local']) ? filesize($file['local']) : 0;
            $exists = file_exists($file['local']) ? '✅' : '❌';
            echo "  $exists {$file['remote']} ($size bytes)\n";
        }
    } catch (Exception $e) {
        echo "❌ $type generation failed: " . $e->getMessage() . "\n";
        echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    }
}

// Clean up
$files = glob($temp_dir . '/*');
foreach ($files as $file) {
    if (is_file($file)) unlink($file);
}
rmdir($temp_dir);

echo "\nDebug complete!\n";
?>
