<?php
// Publish Servers Management

// Prevent output before JSON responses
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Start output buffering immediately
    ob_start();
    // Suppress all error display to prevent HTML corruption of JSON
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    error_reporting(E_ALL);
}

require_once '../includes/auth.php';
require_once '../includes/db.php';
require_once 'publish_generators.php';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Capture any unwanted output
    ob_start();
    
    // Suppress all error display to prevent HTML output
    ini_set('display_errors', 0);
    error_reporting(0);
    
    // Clean any previous output
    if (ob_get_level()) {
        ob_clean();
    }
    
    header('Content-Type: application/json');
    
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_server':
                $event_id = (int)$_POST['event_id'];
                $name = trim($_POST['name']);
                $host = trim($_POST['host']);
                $port = (int)($_POST['port'] ?: 21);
                $username = trim($_POST['username']);
                $password = $_POST['password'];
                $remote_path = trim($_POST['remote_path']);
                $data_types = json_encode($_POST['data_types'] ?? []);
                $update_interval = (int)($_POST['update_interval'] ?: 30);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                try {
                    $stmt = $pdo->prepare("
                        INSERT INTO publish_servers 
                        (event_id, name, host, port, username, password, remote_path, data_types, update_interval, is_active, created_at, updated_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                    ");
                    $stmt->execute([$event_id, $name, $host, $port, $username, $password, $remote_path, $data_types, $update_interval, $is_active]);
                    
                    ob_clean();
                    echo json_encode(['success' => true, 'message' => 'Publish server added successfully']);
                    exit;
                } catch (Exception $e) {
                    ob_clean();
                    echo json_encode(['success' => false, 'message' => 'Error adding server: ' . $e->getMessage()]);
                    exit;
                }
                
            case 'edit_server':
                $id = (int)$_POST['id'];
                $name = trim($_POST['name']);
                $host = trim($_POST['host']);
                $port = (int)($_POST['port'] ?: 21);
                $username = trim($_POST['username']);
                $password = $_POST['password'];
                $remote_path = trim($_POST['remote_path']);
                $data_types = json_encode($_POST['data_types'] ?? []);
                $update_interval = (int)($_POST['update_interval'] ?: 30);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                try {
                    $stmt = $pdo->prepare("
                        UPDATE publish_servers 
                        SET name = ?, host = ?, port = ?, username = ?, password = ?, remote_path = ?, 
                            data_types = ?, update_interval = ?, is_active = ?, updated_at = NOW()
                        WHERE id = ?
                    ");
                    $stmt->execute([$name, $host, $port, $username, $password, $remote_path, $data_types, $update_interval, $is_active, $id]);
                    
                    echo json_encode(['success' => true, 'message' => 'Publish server updated successfully']);
                } catch (Exception $e) {
                    echo json_encode(['success' => false, 'message' => 'Error updating server: ' . $e->getMessage()]);
                }
                exit;
                
            case 'delete_server':
                $id = (int)$_POST['id'];
                
                try {
                    $stmt = $pdo->prepare("DELETE FROM publish_servers WHERE id = ?");
                    $stmt->execute([$id]);
                    
                    echo json_encode(['success' => true, 'message' => 'Publish server deleted successfully']);
                } catch (Exception $e) {
                    echo json_encode(['success' => false, 'message' => 'Error deleting server: ' . $e->getMessage()]);
                }
                exit;
                
            case 'test_connection':
                $host = trim($_POST['host']);
                $port = (int)($_POST['port'] ?: 21);
                $username = trim($_POST['username']);
                $password = $_POST['password'];
                
                $result = testFtpConnection($host, $port, $username, $password);
                echo json_encode($result);
                exit;
                
            case 'publish_now':
                $id = (int)$_POST['id'];
                
                // Enhanced error handling and output buffering
                ob_start();
                $old_error_reporting = error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR);
                $old_display_errors = ini_get('display_errors');
                ini_set('display_errors', 0);
                
                try {
                    $stmt = $pdo->prepare("SELECT * FROM publish_servers WHERE id = ?");
                    $stmt->execute([$id]);
                    $server = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($server) {
                        error_log("Publishing to server: " . $server['name']);
                        $result = publishToServer($server, $pdo);
                        error_log("Publish result: " . json_encode($result));
                        
                        // Ensure completely clean JSON output
                        ob_end_clean();
                        ob_start();
                        header('Content-Type: application/json');
                        echo json_encode($result);
                        exit;
                    } else {
                        ob_end_clean();
                        ob_start();
                        header('Content-Type: application/json');
                        echo json_encode(['success' => false, 'message' => 'Server not found']);
                        exit;
                    }
                } catch (Exception $e) {
                    error_log("Publish error: " . $e->getMessage());
                    error_log("Stack trace: " . $e->getTraceAsString());
                    
                    ob_end_clean();
                    ob_start();
                    header('Content-Type: application/json');
                    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
                    exit;
                } finally {
                    // Restore error settings
                    error_reporting($old_error_reporting);
                    ini_set('display_errors', $old_display_errors);
                }
                break;
                
            case 'debug_generate':
                $event_id = (int)$_POST['event_id'];
                
                try {
                    $temp_dir = sys_get_temp_dir() . '/stylescore_debug_' . $event_id . '_' . time();
                    mkdir($temp_dir, 0755, true);
                    
                    $debug_info = [];
                    
                    // Test HTML generation
                    try {
                        $files = generateHTMLDashboard($event_id, $temp_dir, $pdo);
                        $debug_info['html_dashboard'] = [
                            'success' => true,
                            'file_count' => count($files),
                            'files' => array_map(function($f) {
                                return [
                                    'remote' => $f['remote'],
                                    'size' => file_exists($f['local']) ? filesize($f['local']) : 0
                                ];
                            }, $files)
                        ];
                    } catch (Exception $e) {
                        $debug_info['html_dashboard'] = [
                            'success' => false,
                            'error' => $e->getMessage()
                        ];
                    }
                    
                    // Test JSON generation
                    try {
                        $files = generateJSONData($event_id, $temp_dir, $pdo);
                        $debug_info['json_data'] = [
                            'success' => true,
                            'file_count' => count($files),
                            'files' => array_map(function($f) {
                                return [
                                    'remote' => $f['remote'],
                                    'size' => file_exists($f['local']) ? filesize($f['local']) : 0
                                ];
                            }, $files)
                        ];
                    } catch (Exception $e) {
                        $debug_info['json_data'] = [
                            'success' => false,
                            'error' => $e->getMessage()
                        ];
                    }
                    
                    // Test CSV generation
                    try {
                        $files = generateCSVData($event_id, $temp_dir, $pdo);
                        $debug_info['csv_data'] = [
                            'success' => true,
                            'file_count' => count($files),
                            'files' => array_map(function($f) {
                                return [
                                    'remote' => $f['remote'],
                                    'size' => file_exists($f['local']) ? filesize($f['local']) : 0
                                ];
                            }, $files)
                        ];
                    } catch (Exception $e) {
                        $debug_info['csv_data'] = [
                            'success' => false,
                            'error' => $e->getMessage()
                        ];
                    }
                    
                    // Clean up
                    if (is_dir($temp_dir)) {
                        $files = glob($temp_dir . '/*');
                        foreach ($files as $file) {
                            if (is_file($file)) unlink($file);
                        }
                        rmdir($temp_dir);
                    }
                    
                    ob_clean();
                    echo json_encode([
                        'success' => true,
                        'message' => 'Debug generation complete',
                        'debug_info' => $debug_info,
                        'temp_dir' => $temp_dir
                    ]);
                    exit;
                    
                } catch (Exception $e) {
                    ob_clean();
                    echo json_encode(['success' => false, 'message' => 'Debug error: ' . $e->getMessage()]);
                    exit;
                }
                break;
                
            case 'export_local':
                $id = (int)$_POST['id'];
                
                try {
                    $stmt = $pdo->prepare("SELECT * FROM publish_servers WHERE id = ?");
                    $stmt->execute([$id]);
                    $server = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($server) {
                        $event_id = $server['event_id'];
                        $temp_dir = sys_get_temp_dir() . '/stylescore_export_' . $event_id . '_' . time();
                        mkdir($temp_dir, 0755, true);
                        
                        $all_files = [];
                        
                        // Generate all types
                        try {
                            $html_files = generateHTMLDashboard($event_id, $temp_dir, $pdo);
                            $all_files = array_merge($all_files, $html_files);
                        } catch (Exception $e) {
                            error_log("HTML generation error: " . $e->getMessage());
                        }
                        
                        try {
                            $json_files = generateJSONData($event_id, $temp_dir, $pdo);
                            $all_files = array_merge($all_files, $json_files);
                        } catch (Exception $e) {
                            error_log("JSON generation error: " . $e->getMessage());
                        }
                        
                        try {
                            $csv_files = generateCSVData($event_id, $temp_dir, $pdo);
                            $all_files = array_merge($all_files, $csv_files);
                        } catch (Exception $e) {
                            error_log("CSV generation error: " . $e->getMessage());
                        }
                        
                        // Create ZIP file
                        $zip_file = $temp_dir . '/export.zip';
                        $zip = new ZipArchive();
                        
                        if ($zip->open($zip_file, ZipArchive::CREATE) === TRUE) {
                            foreach ($all_files as $file) {
                                if (file_exists($file['local'])) {
                                    $zip->addFile($file['local'], $file['remote']);
                                }
                            }
                            $zip->close();
                            
                            ob_clean();
                            echo json_encode([
                                'success' => true, 
                                'message' => 'Export created successfully',
                                'download_url' => '/v2/admin/download_export.php?file=' . basename($zip_file) . '&temp=' . basename($temp_dir),
                                'file_count' => count($all_files)
                            ]);
                            exit;
                        } else {
                            throw new Exception('Could not create ZIP file');
                        }
                    } else {
                        throw new Exception('Server not found');
                    }
                } catch (Exception $e) {
                    ob_clean();
                    echo json_encode(['success' => false, 'message' => 'Export error: ' . $e->getMessage()]);
                    exit;
                }
                break;
                
            case 'publish_all':
                $id = (int)$_POST['id'];
                
                try {
                    $stmt = $pdo->prepare("SELECT * FROM publish_servers WHERE id = ?");
                    $stmt->execute([$id]);
                    $server = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($server) {
                        error_log("Reupload ALL files to server: " . $server['name']);
                        
                        // Force all data types for reupload all - modify the server array directly
                        // Skip PDF for now as they need async generation
                        $server['data_types'] = json_encode(['html_dashboard', 'csv_summary', 'csv_startlist']);
                        error_log("Forced data types: " . $server['data_types']);
                        
                        $result = publishToServer($server, $pdo);
                        error_log("Reupload all result: " . json_encode($result));
                        
                        // Ensure clean JSON output
                        ob_clean();
                        echo json_encode($result);
                        exit;
                    } else {
                        ob_clean();
                        echo json_encode(['success' => false, 'message' => 'Server not found']);
                        exit;
                    }
                } catch (Exception $e) {
                    error_log("Reupload all error: " . $e->getMessage());
                    error_log("Stack trace: " . $e->getTraceAsString());
                    
                    ob_clean();
                    echo json_encode(['success' => false, 'message' => 'Error publishing: ' . $e->getMessage()]);
                    exit;
                }
        }
    }
}

// Get events for dropdown
$events_stmt = $pdo->query("SELECT id, name FROM events ORDER BY name");
$events = $events_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get publish servers
$servers_stmt = $pdo->query("
    SELECT ps.*, e.name as event_name 
    FROM publish_servers ps 
    LEFT JOIN events e ON ps.event_id = e.id 
    ORDER BY e.name, ps.name
");
$servers = $servers_stmt->fetchAll(PDO::FETCH_ASSOC);

// Test FTP connection function
function testFtpConnection($host, $port, $username, $password) {
    try {
        $connection = ftp_connect($host, $port, 10);
        if (!$connection) {
            return ['success' => false, 'message' => 'Could not connect to FTP server'];
        }
        
        $login = ftp_login($connection, $username, $password);
        if (!$login) {
            ftp_close($connection);
            return ['success' => false, 'message' => 'FTP login failed'];
        }
        
        ftp_pasv($connection, true);
        $pwd = ftp_pwd($connection);
        ftp_close($connection);
        
        return ['success' => true, 'message' => 'Connection successful', 'current_dir' => $pwd];
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Connection error: ' . $e->getMessage()];
    }
}

// Publish to server function
function publishToServer($server, $pdo) {
    // Capture any potential output
    ob_start();
    
    try {
        error_log("=== PUBLISH TO SERVER START ===");
        error_log("Server name: " . $server['name']);
        error_log("Server ID: " . $server['id']);
        $event_id = $server['event_id'];
        error_log("Event ID: $event_id");
        
        // Debug data types processing
        error_log("Raw data_types from server: " . $server['data_types']);
        $data_types = json_decode($server['data_types'], true);
        
        if ($data_types === null) {
            error_log("JSON decode failed! Attempting to fix...");
            $data_types = [$server['data_types']]; // fallback
        }
        
        if (!is_array($data_types)) {
            error_log("Data types is not an array: " . gettype($data_types));
            $data_types = [];
        }
        
        error_log("Decoded data_types: " . print_r($data_types, true));
        error_log("Data types count: " . count($data_types));
        
        if (empty($data_types)) {
            error_log("ERROR: No data types configured!");
            ob_end_clean(); // Clean any captured output
            return ['success' => false, 'message' => 'No data types configured for this server'];
        }
        
        // Check if FTP extension is available
        if (!extension_loaded('ftp')) {
            error_log("ERROR: FTP extension not loaded");
            ob_end_clean(); // Clean any captured output
            throw new Exception('FTP extension is not loaded in PHP. Please enable php_ftp extension or contact your server administrator.');
        }
        
        $connection = @ftp_connect($server['host'], $server['port'], 30);
        if (!$connection) {
            ob_end_clean(); // Clean any captured output
            throw new Exception('Could not connect to FTP server: ' . $server['host'] . ':' . $server['port']);
        }
        
        error_log("Logging in to FTP with username: " . $server['username']);
        $login = @ftp_login($connection, $server['username'], $server['password']);
        if (!$login) {
            @ftp_close($connection);
            ob_end_clean(); // Clean any captured output
            throw new Exception('FTP login failed');
        }
        
        @ftp_pasv($connection, true);
        
        // Create remote directory if needed
        $remote_path = rtrim($server['remote_path'], '/');
        if ($remote_path && !ftp_chdir($connection, $remote_path)) {
            // Try to create the directory
            if (!ftp_mkdir($connection, $remote_path)) {
                ftp_close($connection);
                throw new Exception('Could not create or access remote directory: ' . $remote_path);
            }
            ftp_chdir($connection, $remote_path);
        }
        
        $uploaded_files = [];
        $temp_dir = sys_get_temp_dir() . '/stylescore_publish_' . $event_id . '_' . time();
        error_log("Creating temp directory: $temp_dir");
        mkdir($temp_dir, 0755, true);
        
        try {
            // Test mode - create a simple test file first
            $test_file = $temp_dir . '/test.txt';
            file_put_contents($test_file, "Test publish at " . date('Y-m-d H:i:s'));
            
            if (uploadFile($connection, $test_file, 'test.txt')) {
                $uploaded_files[] = 'test.txt';
                error_log("Test file uploaded successfully");
            } else {
                throw new Exception("Failed to upload test file");
            }
            
            // Generate and upload files based on selected data types
            foreach ($data_types as $data_type) {
                error_log("Generating data type: $data_type");
                try {
                    switch ($data_type) {
                        case 'html_dashboard':
                            $files = generateStaticHTMLDashboard($event_id, $temp_dir, $pdo, $data_types);
                            error_log("Generated " . count($files) . " files for html_dashboard");
                            foreach ($files as $file) {
                                error_log("Attempting to upload: " . $file['local'] . " -> " . $file['remote']);
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                    error_log("Successfully uploaded: " . $file['remote']);
                                } else {
                                    error_log("Failed to upload: " . $file['remote']);
                                }
                            }
                            break;
                            
                        case 'csv_summary':
                            $files = generateCSVSummary($event_id, $temp_dir, $pdo);
                            error_log("Generated " . count($files) . " files for csv_summary");
                            foreach ($files as $file) {
                                error_log("Attempting to upload: " . $file['local'] . " -> " . $file['remote']);
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                    error_log("Successfully uploaded: " . $file['remote']);
                                } else {
                                    error_log("Failed to upload: " . $file['remote']);
                                }
                            }
                            break;
                            
                        case 'csv_startlist':
                            $files = generateCSVStartList($event_id, $temp_dir, $pdo);
                            error_log("Generated " . count($files) . " files for csv_startlist");
                            foreach ($files as $file) {
                                error_log("Attempting to upload: " . $file['local'] . " -> " . $file['remote']);
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                    error_log("Successfully uploaded: " . $file['remote']);
                                } else {
                                    error_log("Failed to upload: " . $file['remote']);
                                }
                            }
                            break;
                            
                        case 'pdf_results':
                            $files = generatePDFResults($event_id, $temp_dir, $pdo);
                            error_log("Generated " . count($files) . " files for pdf_results");
                            foreach ($files as $file) {
                                error_log("Attempting to upload: " . $file['local'] . " -> " . $file['remote']);
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                    error_log("Successfully uploaded: " . $file['remote']);
                                } else {
                                    error_log("Failed to upload: " . $file['remote']);
                                }
                            }
                            break;
                            
                        // Legacy support for old data type names
                        case 'json_data':
                            $files = generateJSONData($event_id, $temp_dir, $pdo);
                            error_log("Generated " . count($files) . " files for json_data");
                            foreach ($files as $file) {
                                error_log("Attempting to upload: " . $file['local'] . " -> " . $file['remote']);
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                    error_log("Successfully uploaded: " . $file['remote']);
                                } else {
                                    error_log("Failed to upload: " . $file['remote']);
                                }
                            }
                            break;
                            
                        case 'csv_data':
                            $files = generateCSVData($event_id, $temp_dir, $pdo);
                            error_log("Generated " . count($files) . " files for csv_data");
                            foreach ($files as $file) {
                                error_log("Attempting to upload: " . $file['local'] . " -> " . $file['remote']);
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                    error_log("Successfully uploaded: " . $file['remote']);
                                } else {
                                    error_log("Failed to upload: " . $file['remote']);
                                }
                            }
                            break;
                            
                        case 'participant_photos':
                            $files = generateParticipantPhotos($event_id, $temp_dir, $pdo);
                            error_log("Generated " . count($files) . " files for participant_photos");
                            foreach ($files as $file) {
                                error_log("Attempting to upload: " . $file['local'] . " -> " . $file['remote']);
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                    error_log("Successfully uploaded: " . $file['remote']);
                                } else {
                                    error_log("Failed to upload: " . $file['remote']);
                                }
                            }
                            break;
                            
                        default:
                            error_log("Unknown data type: $data_type");
                            break;
                    }
                    error_log("Successfully processed $data_type");
                } catch (Exception $e) {
                    error_log("Error generating $data_type: " . $e->getMessage());
                    error_log("Stack trace: " . $e->getTraceAsString());
                    // Continue with other data types instead of failing completely
                }
            }
            
            // Update last publish time
            $update_stmt = $pdo->prepare("UPDATE publish_servers SET last_publish = NOW() WHERE id = ?");
            $update_stmt->execute([$server['id']]);
            
            // Clean any captured output before returning
            ob_end_clean();
            
            return [
                'success' => true, 
                'message' => 'Published successfully', 
                'uploaded_files' => $uploaded_files,
                'file_count' => count($uploaded_files)
            ];
            
        } finally {
            // Cleanup temp directory
            deleteDirectory($temp_dir);
        }
        
    } catch (Exception $e) {
        // Clean any captured output before returning
        ob_end_clean();
        return ['success' => false, 'message' => 'Publish error: ' . $e->getMessage()];
    } finally {
        if (isset($connection)) {
            @ftp_close($connection);
        }
    }
}

// Helper functions for file upload
function uploadFile($connection, $local_file, $remote_file) {
    error_log("uploadFile called: $local_file -> $remote_file");
    
    // Check if local file exists
    if (!file_exists($local_file)) {
        error_log("ERROR: Local file does not exist: $local_file");
        return false;
    }
    
    $file_size = filesize($local_file);
    error_log("Local file size: $file_size bytes");
    
    if ($file_size === 0) {
        error_log("WARNING: Local file is empty: $local_file");
    }
    
    // Create remote directory if it doesn't exist
    $remote_dir = dirname($remote_file);
    if ($remote_dir && $remote_dir !== '.' && $remote_dir !== '/') {
        error_log("Creating remote directory: $remote_dir");
        
        // Split the path and create directories progressively
        $dirs = explode('/', $remote_dir);
        $current_path = '';
        
        foreach ($dirs as $dir) {
            if (empty($dir)) continue;
            $current_path .= ($current_path ? '/' : '') . $dir;
            
            // Try to change to directory, if it fails, create it
            if (!@ftp_chdir($connection, $current_path)) {
                error_log("Creating directory: $current_path");
                if (!@ftp_mkdir($connection, $current_path)) {
                    error_log("Failed to create directory: $current_path");
                } else {
                    error_log("Successfully created directory: $current_path");
                }
            } else {
                error_log("Directory already exists: $current_path");
            }
        }
        
        // Go back to root directory
        @ftp_chdir($connection, '/');
    }
    
    error_log("Attempting FTP upload...");
    $result = ftp_put($connection, $remote_file, $local_file, FTP_BINARY);
    
    if ($result) {
        error_log("✅ Successfully uploaded: $remote_file");
    } else {
        $ftp_error = error_get_last();
        error_log("❌ Failed to upload: $remote_file");
        if ($ftp_error) {
            error_log("FTP Error: " . $ftp_error['message']);
        }
    }
    
    return $result;
}

function deleteDirectory($dir) {
    if (!is_dir($dir)) return;
    
    $files = array_diff(scandir($dir), ['.', '..']);
    foreach ($files as $file) {
        $path = $dir . DIRECTORY_SEPARATOR . $file;
        is_dir($path) ? deleteDirectory($path) : unlink($path);
    }
    rmdir($dir);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Publish Servers - StyleScore Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .server-card {
            transition: all 0.3s ease;
        }
        .server-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 8px;
        }
        .status-active { background-color: #28a745; }
        .status-inactive { background-color: #dc3545; }
        .status-publishing { background-color: #ffc107; animation: pulse 2s infinite; }
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        .log-entry {
            font-family: monospace;
            font-size: 0.9em;
        }
        .badge-data-type {
            margin: 2px;
        }
        .publish-progress {
            display: none;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="dashboard.php">
                <i class="fas fa-trophy me-2"></i>StyleScore Admin
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../dashboard.php">
                    <i class="fas fa-arrow-left me-1"></i>Back to Dashboard
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h2><i class="fas fa-server me-2"></i>Publish Servers</h2>
                    <p class="text-muted">Manage remote publishing of event data to external servers</p>
                </div>
                <div>
                    <button class="btn btn-outline-info me-2" onclick="debugGenerate()">
                        <i class="fas fa-bug"></i> Debug Generate
                    </button>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addServerModal">
                        <i class="fas fa-plus me-2"></i>Add Publish Server
                    </button>
                </div>
            </div>

            <!-- Servers List -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-list me-2"></i>Configured Servers</h5>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Name</th>
                                    <th>Event</th>
                                    <th>Host</th>
                                    <th>Data Types</th>
                                    <th>Interval</th>
                                    <th>Status</th>
                                    <th>Last Publish</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($servers as $server): ?>
                                <tr>
                                    <td>
                                        <strong><?= htmlspecialchars($server['name']) ?></strong>
                                    </td>
                                    <td>
                                        <span class="badge bg-info"><?= htmlspecialchars($server['event_name']) ?></span>
                                    </td>
                                    <td>
                                        <small class="text-muted">
                                            <?= htmlspecialchars($server['host']) ?>:<?= $server['port'] ?><br>
                                            <?= htmlspecialchars($server['remote_path']) ?>
                                        </small>
                                    </td>
                                    <td>
                                        <?php 
                                        $data_types = json_decode($server['data_types'], true) ?: [];
                                        foreach ($data_types as $type):
                                        ?>
                                        <span class="badge bg-secondary me-1"><?= htmlspecialchars($type) ?></span>
                                        <?php endforeach; ?>
                                    </td>
                                    <td>
                                        <small><?= $server['update_interval'] ?>s</small>
                                    </td>
                                    <td>
                                        <?php if ($server['is_active']): ?>
                                        <span class="badge bg-success">Active</span>
                                        <?php else: ?>
                                        <span class="badge bg-secondary">Inactive</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <small class="text-muted">
                                            <?= $server['last_publish'] ? date('M j, H:i', strtotime($server['last_publish'])) : 'Never' ?>
                                        </small>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <button class="btn btn-outline-success" onclick="publishNow(<?= $server['id'] ?>)" title="Publish Now (Selected Data Types)">
                                                <i class="fas fa-upload"></i>
                                            </button>
                                            <button class="btn btn-success" onclick="publishAll(<?= $server['id'] ?>)" title="Reupload ALL Files">
                                                <i class="fas fa-sync-alt"></i>
                                            </button>
                                            <button class="btn btn-outline-info" onclick="exportLocal(<?= $server['id'] ?>)" title="Export Files Locally (ZIP)">
                                                <i class="fas fa-download"></i>
                                            </button>
                                            <button class="btn btn-outline-warning" onclick="debugPublish(<?= $server['id'] ?>)" title="Debug Publish Process">
                                                <i class="fas fa-bug"></i>
                                            </button>
                                            <button class="btn btn-outline-primary" onclick="editServer(<?= $server['id'] ?>)" title="Edit">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-outline-danger" onclick="deleteServer(<?= $server['id'] ?>)" title="Delete">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                
                                <?php if (empty($servers)): ?>
                                <tr>
                                    <td colspan="8" class="text-center py-4 text-muted">
                                        <i class="fas fa-server fa-2x mb-2"></i><br>
                                        No publish servers configured yet
                                    </td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Server Modal -->
<div class="modal fade" id="addServerModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-plus me-2"></i>Add Publish Server</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addServerForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Server Name *</label>
                                <input type="text" class="form-control" name="name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Event *</label>
                                <select class="form-select" name="event_id" required>
                                    <option value="">Select Event</option>
                                    <?php foreach ($events as $event): ?>
                                    <option value="<?= $event['id'] ?>"><?= htmlspecialchars($event['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label class="form-label">FTP Host *</label>
                                <input type="text" class="form-control" name="host" required placeholder="ftp.example.com">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">Port</label>
                                <input type="number" class="form-control" name="port" value="21" min="1" max="65535">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Username *</label>
                                <input type="text" class="form-control" name="username" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Password *</label>
                                <input type="password" class="form-control" name="password" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Remote Path</label>
                        <input type="text" class="form-control" name="remote_path" placeholder="/public_html/events/" value="/">
                        <small class="form-text text-muted">Directory on the remote server where files will be uploaded</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Data Types to Publish *</label>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="html_dashboard" id="html_dashboard" checked>
                                    <label class="form-check-label" for="html_dashboard">
                                        <strong>HTML Dashboard</strong><br>
                                        <small class="text-muted">Complete interactive dashboard</small>
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="json_data" id="json_data" checked>
                                    <label class="form-check-label" for="json_data">
                                        <strong>JSON Data</strong><br>
                                        <small class="text-muted">Raw data in JSON format</small>
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="pdf_results" id="pdf_results">
                                    <label class="form-check-label" for="pdf_results">
                                        <strong>PDF Results</strong><br>
                                        <small class="text-muted">Printable result sheets</small>
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="participant_photos" id="participant_photos">
                                    <label class="form-check-label" for="participant_photos">
                                        <strong>Participant Photos</strong><br>
                                        <small class="text-muted">Participant photo files</small>
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="csv_data" id="csv_data" checked>
                                    <label class="form-check-label" for="csv_data">
                                        <strong>CSV Data</strong><br>
                                        <small class="text-muted">Spreadsheet compatible data</small>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Update Interval (seconds)</label>
                                <select class="form-select" name="update_interval">
                                    <option value="30">30 seconds</option>
                                    <option value="60">1 minute</option>
                                    <option value="300">5 minutes</option>
                                    <option value="600">10 minutes</option>
                                    <option value="1800">30 minutes</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <div class="form-check form-switch mt-4">
                                    <input class="form-check-input" type="checkbox" name="is_active" id="is_active" checked>
                                    <label class="form-check-label" for="is_active">
                                        Active
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-secondary" onclick="testConnection()">
                            <i class="fas fa-wifi me-2"></i>Test Connection
                        </button>
                        <div id="connectionResult" class="flex-grow-1"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>Add Server
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Server Modal -->
<div class="modal fade" id="editServerModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Publish Server</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editServerForm">
                <input type="hidden" name="id" id="edit_id">
                <div class="modal-body">
                    <!-- Same form fields as add modal -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Server Name *</label>
                                <input type="text" class="form-control" name="name" id="edit_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Event *</label>
                                <select class="form-select" name="event_id" id="edit_event_id" required>
                                    <option value="">Select Event</option>
                                    <?php foreach ($events as $event): ?>
                                    <option value="<?= $event['id'] ?>"><?= htmlspecialchars($event['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="mb-3">
                                <label class="form-label">FTP Host *</label>
                                <input type="text" class="form-control" name="host" id="edit_host" required>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">Port</label>
                                <input type="number" class="form-control" name="port" id="edit_port" min="1" max="65535">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Username *</label>
                                <input type="text" class="form-control" name="username" id="edit_username" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Password *</label>
                                <input type="password" class="form-control" name="password" id="edit_password" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Remote Path</label>
                        <input type="text" class="form-control" name="remote_path" id="edit_remote_path">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Data Types to Publish *</label>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="html_dashboard" id="edit_html_dashboard">
                                    <label class="form-check-label" for="edit_html_dashboard">
                                        <strong>HTML Dashboard</strong><br>
                                        <small class="text-muted">Complete interactive dashboard</small>
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="json_data" id="edit_json_data">
                                    <label class="form-check-label" for="edit_json_data">
                                        <strong>JSON Data</strong><br>
                                        <small class="text-muted">Raw data in JSON format</small>
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="pdf_results" id="edit_pdf_results">
                                    <label class="form-check-label" for="edit_pdf_results">
                                        <strong>PDF Results</strong><br>
                                        <small class="text-muted">Printable result sheets</small>
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="csv_data" id="edit_csv_data">
                                    <label class="form-check-label" for="edit_csv_data">
                                        <strong>CSV Data</strong><br>
                                        <small class="text-muted">Spreadsheet compatible data</small>
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="data_types[]" value="participant_photos" id="edit_participant_photos">
                                    <label class="form-check-label" for="edit_participant_photos">
                                        <strong>Participant Photos</strong><br>
                                        <small class="text-muted">Upload participant profile photos</small>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Update Interval (seconds)</label>
                                <select class="form-select" name="update_interval" id="edit_update_interval">
                                    <option value="30">30 seconds</option>
                                    <option value="60">1 minute</option>
                                    <option value="300">5 minutes</option>
                                    <option value="600">10 minutes</option>
                                    <option value="1800">30 minutes</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <div class="form-check form-switch mt-4">
                                    <input class="form-check-input" type="checkbox" name="is_active" id="edit_is_active">
                                    <label class="form-check-label" for="edit_is_active">
                                        Active
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-secondary" onclick="testConnectionEdit()">
                            <i class="fas fa-wifi me-2"></i>Test Connection
                        </button>
                        <div id="connectionResultEdit" class="flex-grow-1"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>Update Server
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Add server form submission
document.getElementById('addServerForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'add_server');
    
    fetch('publish_servers.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            if (window.notifySuccess) {
                window.notifySuccess('Success', data.message);
            } else {
                alert(data.message);
            }
            location.reload();
        } else {
            if (window.notifyError) {
                window.notifyError('Error', data.message);
            } else {
                alert('Error: ' + data.message);
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (window.notifyError) {
            window.notifyError('Error', 'Network error occurred');
        } else {
            alert('Network error occurred');
        }
    });
});

// Edit server form submission
document.getElementById('editServerForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'edit_server');
    
    fetch('publish_servers.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            if (window.notifySuccess) {
                window.notifySuccess('Success', data.message);
            } else {
                alert(data.message);
            }
            location.reload();
        } else {
            if (window.notifyError) {
                window.notifyError('Error', data.message);
            } else {
                alert('Error: ' + data.message);
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (window.notifyError) {
            window.notifyError('Error', 'Network error occurred');
        } else {
            alert('Network error occurred');
        }
    });
});

// Test connection function
function testConnection() {
    const form = document.getElementById('addServerForm');
    const formData = new FormData(form);
    formData.append('action', 'test_connection');
    
    const resultDiv = document.getElementById('connectionResult');
    resultDiv.innerHTML = '<div class="alert alert-info py-1"><i class="fas fa-spinner fa-spin me-2"></i>Testing connection...</div>';
    
    fetch('publish_servers.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            resultDiv.innerHTML = `<div class="alert alert-success py-1"><i class="fas fa-check me-2"></i>${data.message}</div>`;
        } else {
            resultDiv.innerHTML = `<div class="alert alert-danger py-1"><i class="fas fa-times me-2"></i>${data.message}</div>`;
        }
    })
    .catch(error => {
        resultDiv.innerHTML = '<div class="alert alert-danger py-1"><i class="fas fa-times me-2"></i>Network error</div>';
    });
}

// Test connection for edit form
function testConnectionEdit() {
    const form = document.getElementById('editServerForm');
    const formData = new FormData(form);
    formData.append('action', 'test_connection');
    
    const resultDiv = document.getElementById('connectionResultEdit');
    resultDiv.innerHTML = '<div class="alert alert-info py-1"><i class="fas fa-spinner fa-spin me-2"></i>Testing connection...</div>';
    
    fetch('publish_servers.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            resultDiv.innerHTML = `<div class="alert alert-success py-1"><i class="fas fa-check me-2"></i>${data.message}</div>`;
        } else {
            resultDiv.innerHTML = `<div class="alert alert-danger py-1"><i class="fas fa-times me-2"></i>${data.message}</div>`;
        }
    })
    .catch(error => {
        resultDiv.innerHTML = '<div class="alert alert-danger py-1"><i class="fas fa-times me-2"></i>Network error</div>';
    });
}

// Edit server function
function editServer(id) {
    // Get server data and populate edit form
    const servers = <?= json_encode($servers) ?>;
    const server = servers.find(s => s.id == id);
    
    if (server) {
        document.getElementById('edit_id').value = server.id;
        document.getElementById('edit_name').value = server.name;
        document.getElementById('edit_event_id').value = server.event_id;
        document.getElementById('edit_host').value = server.host;
        document.getElementById('edit_port').value = server.port;
        document.getElementById('edit_username').value = server.username;
        document.getElementById('edit_password').value = server.password;
        document.getElementById('edit_remote_path').value = server.remote_path;
        document.getElementById('edit_update_interval').value = server.update_interval;
        document.getElementById('edit_is_active').checked = server.is_active == 1;
        
        // Set data types checkboxes
        const dataTypes = JSON.parse(server.data_types || '[]');
        document.querySelectorAll('#editServerModal input[name="data_types[]"]').forEach(cb => {
            cb.checked = dataTypes.includes(cb.value);
        });
        
        new bootstrap.Modal(document.getElementById('editServerModal')).show();
    }
}

// Delete server function
function deleteServer(id) {
    if (!confirm('Are you sure you want to delete this publish server?')) return;
    
    const formData = new FormData();
    formData.append('action', 'delete_server');
    formData.append('id', id);
    
    fetch('publish_servers.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            if (window.notifySuccess) {
                window.notifySuccess('Success', data.message);
            } else {
                alert(data.message);
            }
            location.reload();
        } else {
            if (window.notifyError) {
                window.notifyError('Error', data.message);
            } else {
                alert('Error: ' + data.message);
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (window.notifyError) {
            window.notifyError('Error', 'Network error occurred');
        } else {
            alert('Network error occurred');
        }
    });
}

// Publish now function
function publishNow(id) {
    if (!confirm('Publish data to this server now?')) return;
    
    const formData = new FormData();
    formData.append('action', 'publish_now');
    formData.append('id', id);
    
    fetch('publish_servers.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            if (window.notifySuccess) {
                window.notifySuccess('Success', `${data.message}. Uploaded ${data.file_count} files.`);
            } else {
                alert(`${data.message}. Uploaded ${data.file_count} files.`);
            }
            location.reload();
        } else {
            if (window.notifyError) {
                window.notifyError('Error', data.message);
            } else {
                alert('Error: ' + data.message);
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (window.notifyError) {
            window.notifyError('Error', 'Network error occurred');
        } else {
            alert('Network error occurred');
        }
    });
}

// Publish all files function  
function debugPublish(id) {
    // Open debug page in new window
    window.open(`debug_publish_detailed.php?server_id=${id}`, '_blank');
}

function publishAll(id) {
    if (!confirm('Reupload ALL files (HTML dashboard, JSON data, CSV data, photos, assets) to this server? This will replace all existing files.')) return;
    
    const formData = new FormData();
    formData.append('action', 'publish_all');
    formData.append('id', id);
    
    fetch('publish_servers.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            if (window.notifySuccess) {
                window.notifySuccess('Success', `${data.message}. Uploaded ${data.file_count} files including photos and assets.`);
            } else {
                alert(`${data.message}. Uploaded ${data.file_count} files including photos and assets.`);
            }
            location.reload();
        } else {
            if (window.notifyError) {
                window.notifyError('Error', data.message);
            } else {
                alert('Error: ' + data.message);
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (window.notifyError) {
            window.notifyError('Error', 'Network error occurred');
        } else {
            alert('Network error occurred');
        }
    });
}

// Debug generate function
function debugGenerate() {
    const eventId = new URLSearchParams(window.location.search).get('event_id') || 1;
    
    const formData = new FormData();
    formData.append('action', 'debug_generate');
    formData.append('event_id', eventId);
    
    fetch('publish_servers.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            let message = `Debug Generation Results:\n\n`;
            for (const [type, info] of Object.entries(data.debug_info)) {
                message += `${type.toUpperCase()}:\n`;
                if (info.success) {
                    message += `  ✅ Success - Generated ${info.file_count} files\n`;
                    info.files.forEach(file => {
                        message += `    - ${file.remote} (${file.size} bytes)\n`;
                    });
                } else {
                    message += `  ❌ Error: ${info.error}\n`;
                }
                message += `\n`;
            }
            alert(message);
        } else {
            alert('Debug Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Network error occurred');
    });
}

// Export local function
function exportLocal(id) {
    if (!confirm('Export all files to a ZIP download? This will generate HTML, JSON, CSV, photos and assets.')) return;
    
    const formData = new FormData();
    formData.append('action', 'export_local');
    formData.append('id', id);
    
    fetch('publish_servers.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            alert(`Export created with ${data.file_count} files. Download will start automatically.`);
            window.open(data.download_url, '_blank');
        } else {
            alert('Export Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Network error occurred');
    });
}
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

<?php include 'footer.php'; ?>
