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

echo "<h2>Complete Publish System Test</h2>";

// Get first available event
try {
    $events_stmt = $pdo->query("SELECT id, name, status FROM events ORDER BY id ASC LIMIT 1");
    $event = $events_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$event) {
        echo "<p style='color: red;'>No events found!</p>";
        exit;
    }
    
    $event_id = $event['id'];
    echo "<p><strong>Testing with Event: {$event['name']} (ID: $event_id)</strong></p>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    exit;
}

// Test directory
$test_dir = sys_get_temp_dir() . '/publish_test_' . time();
if (!is_dir($test_dir)) {
    mkdir($test_dir, 0777, true);
}

echo "<h3>Testing Data Generation Functions</h3>";

// Test individual data functions
$tests = [
    'Overview Data' => function() use ($event_id, $pdo) {
        return getOverviewData($event_id, $pdo);
    },
    'Heats Data' => function() use ($event_id, $pdo) {
        return getHeatsData($event_id, $pdo);
    },
    'Scores Data' => function() use ($event_id, $pdo) {
        return getScoresData($event_id, $pdo);
    }
];

foreach ($tests as $test_name => $test_function) {
    echo "<h4>$test_name</h4>";
    
    try {
        $start_time = microtime(true);
        $result = $test_function();
        $end_time = microtime(true);
        $duration = round(($end_time - $start_time) * 1000, 2);
        
        if ($result && (isset($result['success']) ? $result['success'] : true)) {
            echo "<p style='color: green;'>✓ Success (${duration}ms)</p>";
            
            // Show data structure
            if (isset($result['heats'])) {
                $count = is_array($result['heats']) ? count($result['heats']) : 'object';
                echo "<p>Heats: $count</p>";
            }
            if (isset($result['scores'])) {
                $count = is_array($result['scores']) ? count($result['scores']) : 'object';
                echo "<p>Scores: $count</p>";
            }
            if (isset($result['event'])) {
                echo "<p>Event info: ✓</p>";
            }
            
            // Show sample data (first 500 chars)
            echo "<details><summary>Data Preview</summary>";
            echo "<pre>" . htmlspecialchars(substr(json_encode($result, JSON_PRETTY_PRINT), 0, 500)) . "...</pre>";
            echo "</details>";
            
        } else {
            echo "<p style='color: red;'>✗ Failed</p>";
            if (isset($result['error'])) {
                echo "<p>Error: " . htmlspecialchars($result['error']) . "</p>";
            }
        }
        
    } catch (Exception $e) {
        echo "<p style='color: red;'>✗ Exception: " . htmlspecialchars($e->getMessage()) . "</p>";
    }
}

echo "<h3>Testing Complete HTML Dashboard Generation</h3>";

try {
    $start_time = microtime(true);
    $files = generateHTMLDashboard($event_id, $test_dir, $pdo);
    $end_time = microtime(true);
    $duration = round(($end_time - $start_time) * 1000, 2);
    
    echo "<p style='color: green;'>✓ Generated " . count($files) . " files (${duration}ms)</p>";
    
    echo "<table border='1' style='width: 100%; margin-top: 1rem;'>";
    echo "<tr><th>File</th><th>Size</th><th>Content Type</th><th>Preview</th></tr>";
    
    foreach ($files as $file) {
        $exists = file_exists($file['local']);
        $size = $exists ? filesize($file['local']) : 0;
        $content_type = '';
        $preview = '';
        
        if ($exists && $size > 0) {
            $content = file_get_contents($file['local']);
            
            if (strpos($file['remote'], '.json') !== false) {
                $content_type = 'JSON';
                $json_data = json_decode($content, true);
                if ($json_data !== null) {
                    $preview = "Valid JSON";
                    if (isset($json_data['heats'])) {
                        $preview .= " (" . (is_array($json_data['heats']) ? count($json_data['heats']) : 'object') . " heats)";
                    }
                    if (isset($json_data['scores'])) {
                        $preview .= " (" . (is_array($json_data['scores']) ? count($json_data['scores']) : 'object') . " scores)";
                    }
                } else {
                    $preview = "Invalid JSON";
                }
            } elseif (strpos($file['remote'], '.html') !== false) {
                $content_type = 'HTML';
                $preview = "HTML Document (" . strlen($content) . " chars)";
            } elseif (strpos($file['remote'], '.csv') !== false) {
                $content_type = 'CSV';
                $lines = substr_count($content, "\n");
                $preview = "CSV file ($lines lines)";
            } else {
                $content_type = 'Other';
                $preview = substr($content, 0, 50) . "...";
            }
        } else {
            $preview = "File not found or empty";
        }
        
        echo "<tr>";
        echo "<td>" . htmlspecialchars($file['remote']) . "</td>";
        echo "<td>" . $size . " bytes</td>";
        echo "<td>$content_type</td>";
        echo "<td>$preview</td>";
        echo "</tr>";
    }
    echo "</table>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>✗ Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}

// Test the remote dashboard template
echo "<h3>Testing Remote Dashboard Template</h3>";

$dashboard_file = $test_dir . '/index.html';
if (file_exists($dashboard_file)) {
    echo "<p style='color: green;'>✓ Dashboard template generated</p>";
    
    // Check if it contains our updated JavaScript
    $dashboard_content = file_get_contents($dashboard_file);
    if (strpos($dashboard_content, 'Object.values(this.heatsData.heats)') !== false) {
        echo "<p style='color: green;'>✓ Dashboard contains updated heats handling</p>";
    } else {
        echo "<p style='color: orange;'>⚠ Dashboard may not have updated heats handling</p>";
    }
    
    if (strpos($dashboard_content, 'score.score_value') !== false) {
        echo "<p style='color: green;'>✓ Dashboard contains updated scores handling</p>";
    } else {
        echo "<p style='color: orange;'>⚠ Dashboard may not have updated scores handling</p>";
    }
    
} else {
    echo "<p style='color: red;'>✗ Dashboard template not found</p>";
}

// Clean up
if (is_dir($test_dir)) {
    $files = glob($test_dir . '/*');
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file);
        }
    }
    rmdir($test_dir);
    echo "<p>✓ Cleaned up test directory</p>";
}

echo "<h3>Summary</h3>";
echo "<p>All data generation functions have been updated to work with the correct database structure from the API.</p>";
echo "<p>The remote dashboard has been updated to handle both array and object formats for heats data.</p>";
echo "<p>Ready for testing with a live publish server!</p>";
?>
