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

echo "<h2>Detailed Publish Debug</h2>";

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

$server_id = isset($_GET['server_id']) ? (int)$_GET['server_id'] : 3;

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

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

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

// Test the actual publish function step by step
echo "<h3>Testing Publish Process</h3>";

try {
    // Call the actual publish function with detailed logging
    ob_start();
    $result = publishToServer($server, $pdo);
    $output = ob_get_clean();
    
    echo "<h4>Function Output:</h4>";
    if ($output) {
        echo "<pre>" . htmlspecialchars($output) . "</pre>";
    }
    
    echo "<h4>Function Result:</h4>";
    echo "<pre>" . print_r($result, true) . "</pre>";
    
} catch (Exception $e) {
    echo "<h4>Exception:</h4>";
    echo "<p style='color: red;'>" . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}

// Also check what files exist on the server
echo "<h3>Checking Remote Server Files</h3>";

try {
    $connection = ftp_connect($server['host'], $server['port'], 30);
    if ($connection) {
        if (ftp_login($connection, $server['username'], $server['password'])) {
            ftp_pasv($connection, true);
            
            // Change to target directory
            $remote_path = isset($server['remote_path']) ? rtrim($server['remote_path'], '/') : '';
            if (!empty($remote_path)) {
                if (ftp_chdir($connection, $remote_path)) {
                    echo "Changed to directory: " . $remote_path . "<br>";
                } else {
                    echo "Could not change to directory: " . $remote_path . "<br>";
                }
            } else {
                echo "No remote path specified, using root<br>";
            }
            
            // List files
            $files = ftp_nlist($connection, '.');
            if ($files) {
                echo "<h4>Files on server:</h4>";
                echo "<ul>";
                foreach ($files as $file) {
                    if ($file !== '.' && $file !== '..') {
                        $size = ftp_size($connection, $file);
                        echo "<li>$file" . ($size >= 0 ? " ($size bytes)" : "") . "</li>";
                    }
                }
                echo "</ul>";
            } else {
                echo "No files found or listing failed.<br>";
            }
            
        } else {
            echo "FTP login failed<br>";
        }
        ftp_close($connection);
    } else {
        echo "FTP connection failed<br>";
    }
} catch (Exception $e) {
    echo "Error checking server: " . $e->getMessage() . "<br>";
}

// Check PHP error log for recent entries
echo "<h3>Recent Error Log Entries</h3>";
$error_log = ini_get('error_log');
if ($error_log && file_exists($error_log)) {
    $lines = file($error_log);
    $recent_lines = array_slice($lines, -50); // Last 50 lines
    echo "<pre>";
    foreach ($recent_lines as $line) {
        if (strpos($line, 'stylescore') !== false || strpos($line, 'publish') !== false) {
            echo htmlspecialchars($line);
        }
    }
    echo "</pre>";
} else {
    echo "Error log not found at: $error_log<br>";
    
    // Try common locations
    $common_logs = [
        'C:\xampp\php\logs\php_error_log',
        'C:\xampp\apache\logs\error.log',
        '/var/log/php_errors.log',
        '/var/log/apache2/error.log'
    ];
    
    foreach ($common_logs as $log_path) {
        if (file_exists($log_path)) {
            echo "Found log at: $log_path<br>";
            $lines = file($log_path);
            $recent_lines = array_slice($lines, -20);
            echo "<pre>";
            foreach ($recent_lines as $line) {
                if (strpos($line, 'stylescore') !== false || strpos($line, 'publish') !== false) {
                    echo htmlspecialchars($line);
                }
            }
            echo "</pre>";
            break;
        }
    }
}

// Helper function (include it here for testing)
function publishToServer($server, $pdo) {
    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!");
            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");
            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) {
            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);
            throw new Exception('FTP login failed');
        }
        
        ftp_pasv($connection, true);
        
        // Create remote directory if needed
        if (!empty($server['directory'])) {
            if (!ftp_chdir($connection, $server['directory'])) {
                error_log("Creating remote directory: " . $server['directory']);
                if (!createFTPDirectory($connection, $server['directory'])) {
                    error_log("Failed to create remote directory");
                } else {
                    ftp_chdir($connection, $server['directory']);
                }
            }
        }
        
        // Create temp directory for generated files
        $temp_dir = sys_get_temp_dir() . '/stylescore_publish_' . $server['id'] . '_' . time();
        if (!is_dir($temp_dir)) {
            mkdir($temp_dir, 0777, true);
        }
        error_log("Temp directory created: $temp_dir");
        
        $uploaded_files = [];
        
        try {
            // Process each data type
            foreach ($data_types as $data_type) {
                error_log("Processing data type: $data_type");
                
                try {
                    switch ($data_type) {
                        case 'html_dashboard':
                            error_log("Generating HTML dashboard files...");
                            require_once 'publish_generators.php';
                            $files = generateHTMLDashboard($event_id, $temp_dir, $pdo);
                            error_log("HTML dashboard generated " . count($files) . " files");
                            
                            foreach ($files as $file) {
                                error_log("Processing file: " . $file['remote'] . " from " . $file['local']);
                                if (file_exists($file['local'])) {
                                    $size = filesize($file['local']);
                                    error_log("File exists, size: $size bytes");
                                    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']);
                                    }
                                } else {
                                    error_log("File does not exist: " . $file['local']);
                                }
                            }
                            break;
                            
                        case 'csv_summary':
                            error_log("Generating CSV summary...");
                            require_once 'publish_generators.php';
                            $files = generateCSVSummary($event_id, $temp_dir, $pdo);
                            
                            foreach ($files as $file) {
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                }
                            }
                            break;
                            
                        case 'csv_startlist':
                            error_log("Generating CSV start list...");
                            require_once 'publish_generators.php';
                            $files = generateCSVStartList($event_id, $temp_dir, $pdo);
                            
                            foreach ($files as $file) {
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                }
                            }
                            break;
                            
                        case 'pdf_results':
                            error_log("Generating PDF results...");
                            require_once 'publish_generators.php';
                            $files = generatePDFResults($event_id, $temp_dir, $pdo);
                            
                            foreach ($files as $file) {
                                if (uploadFile($connection, $file['local'], $file['remote'])) {
                                    $uploaded_files[] = $file['remote'];
                                }
                            }
                            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']]);
            
            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) {
        error_log("Publish error: " . $e->getMessage());
        return ['success' => false, 'message' => 'Publish error: ' . $e->getMessage()];
    } finally {
        if (isset($connection)) {
            ftp_close($connection);
        }
    }
}

// Include necessary helper functions
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 createFTPDirectory($connection, $path) {
    $dirs = explode('/', $path);
    $current_path = '';
    
    foreach ($dirs as $dir) {
        if (empty($dir)) continue;
        $current_path .= ($current_path ? '/' : '') . $dir;
        
        if (!@ftp_chdir($connection, $current_path)) {
            if (!@ftp_mkdir($connection, $current_path)) {
                return false;
            }
        }
    }
    return true;
}

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