<?php
// Direct publish test with maximum debugging
require_once __DIR__ . '/../includes/db.php';

echo "<h2>Direct Publish Test with Debugging</h2>";

// Enable all error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

$server_id = 3;

echo "<h3>Step 1: Get Server Configuration</h3>";

$stmt = $pdo->prepare("SELECT * FROM publish_servers WHERE id = ?");
$stmt->execute([$server_id]);
$server = $stmt->fetch();

if (!$server) {
    die("Server not found!");
}

echo "<table border='1'>";
foreach ($server as $key => $value) {
    echo "<tr><td><strong>$key</strong></td><td>" . htmlspecialchars($value) . "</td></tr>";
}
echo "</table>";

echo "<h3>Step 2: Test FTP Connection</h3>";

$connection = ftp_connect($server['host'], $server['port'], 30);
if ($connection) {
    echo "✓ FTP connection successful<br>";
    
    if (ftp_login($connection, $server['username'], $server['password'])) {
        echo "✓ FTP login successful<br>";
        ftp_pasv($connection, true);
        
        // Try to change to directory
        if (!empty($server['directory'])) {
            if (ftp_chdir($connection, $server['directory'])) {
                echo "✓ Changed to directory: " . $server['directory'] . "<br>";
            } else {
                echo "✗ Could not change to directory: " . $server['directory'] . "<br>";
            }
        }
        
        // List current files
        $current_files = ftp_nlist($connection, '.');
        if ($current_files) {
            echo "Current files on server:<br>";
            foreach ($current_files as $file) {
                if ($file !== '.' && $file !== '..') {
                    $size = ftp_size($connection, $file);
                    echo "- $file" . ($size >= 0 ? " ($size bytes)" : "") . "<br>";
                }
            }
        }
        
    } else {
        echo "✗ FTP login failed<br>";
    }
} else {
    echo "✗ FTP connection failed<br>";
}

echo "<h3>Step 3: Generate Files</h3>";

require_once 'publish_generators.php';

$event_id = $server['event_id'];
$temp_dir = sys_get_temp_dir() . '/stylescore_direct_test_' . time();

if (!is_dir($temp_dir)) {
    mkdir($temp_dir, 0777, true);
}

echo "Event ID: $event_id<br>";
echo "Temp Directory: $temp_dir<br>";

// Parse data types
$data_types = json_decode($server['data_types'], true);
if ($data_types === null) {
    $data_types = [$server['data_types']];
}

echo "Data types to generate: " . implode(', ', $data_types) . "<br>";

$all_generated_files = [];

foreach ($data_types as $data_type) {
    echo "<h4>Generating: $data_type</h4>";
    
    try {
        switch ($data_type) {
            case 'html_dashboard':
                $files = generateHTMLDashboard($event_id, $temp_dir, $pdo);
                break;
            case 'csv_summary':
                $files = generateCSVSummary($event_id, $temp_dir, $pdo);
                break;
            case 'csv_startlist':
                $files = generateCSVStartList($event_id, $temp_dir, $pdo);
                break;
            case 'pdf_results':
                $files = generatePDFResults($event_id, $temp_dir, $pdo);
                break;
            default:
                echo "Unknown data type: $data_type<br>";
                continue 2;
        }
        
        echo "Generated " . count($files) . " files:<br>";
        echo "<table border='1' style='width:100%'>";
        echo "<tr><th>Remote Name</th><th>Local Path</th><th>Exists</th><th>Size</th><th>Type</th><th>Test Upload</th></tr>";
        
        foreach ($files as $file) {
            $exists = file_exists($file['local']);
            $size = $exists ? filesize($file['local']) : 0;
            $extension = pathinfo($file['local'], PATHINFO_EXTENSION);
            
            echo "<tr>";
            echo "<td>" . htmlspecialchars($file['remote']) . "</td>";
            echo "<td>" . htmlspecialchars(basename($file['local'])) . "</td>";
            echo "<td>" . ($exists ? "✓" : "✗") . "</td>";
            echo "<td>$size bytes</td>";
            echo "<td>$extension</td>";
            
            // Test upload
            if ($exists && $connection) {
                if (ftp_put($connection, $file['remote'], $file['local'], FTP_BINARY)) {
                    echo "<td style='color: green;'>✓ Uploaded</td>";
                } else {
                    echo "<td style='color: red;'>✗ Upload failed</td>";
                }
            } else {
                echo "<td>Cannot test</td>";
            }
            
            echo "</tr>";
        }
        echo "</table>";
        
        $all_generated_files = array_merge($all_generated_files, $files);
        
    } catch (Exception $e) {
        echo "<p style='color: red;'>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
    }
}

echo "<h3>Step 4: Final Server Check</h3>";

if ($connection) {
    // List files again after upload
    $final_files = ftp_nlist($connection, '.');
    if ($final_files) {
        echo "Files after upload:<br>";
        foreach ($final_files as $file) {
            if ($file !== '.' && $file !== '..') {
                $size = ftp_size($connection, $file);
                echo "- $file" . ($size >= 0 ? " ($size bytes)" : "") . "<br>";
            }
        }
    }
    
    ftp_close($connection);
}

echo "<h3>Summary</h3>";
echo "Total files generated: " . count($all_generated_files) . "<br>";

// Cleanup
if (is_dir($temp_dir)) {
    $files = glob($temp_dir . '/*');
    foreach ($files as $file) {
        if (is_file($file)) {
            unlink($file);
        }
    }
    rmdir($temp_dir);
    echo "Temp directory cleaned up<br>";
}
?>
