<?php
// Debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// FTP Credentials
$ftpServer = 'ftp.motorclub.gr';
$ftpUser = 'carimageswv@motorclub.gr';
$ftpPass = 'xH60v]chZIUQ';
$remoteDir = '/';  // CORRECTED: relative to FTP user home

// Local Image Directory (Backoffice)
$sourceDir = '/home/motorclu/public_html/motorclub-admin/carimages/';

// Check if the source directory exists
if (!is_dir($sourceDir)) {
    die("❌ Source directory does not exist: $sourceDir");
}

// Connect to FTP
$conn = ftp_connect($ftpServer);
if (!$conn) {
    die('❌ Could not connect to FTP server');
}
echo "✅ Connected to FTP server<br>";

// Login to FTP
if (!ftp_login($conn, $ftpUser, $ftpPass)) {
    ftp_close($conn);
    die('❌ Could not login to FTP server');
}
echo "✅ Logged into FTP server<br>";

// Enable Passive Mode
ftp_pasv($conn, true);
echo "✅ Passive mode enabled<br>";

// Scan files in the directory
$files = scandir($sourceDir);
$transferred = 0;
$failed = 0;

foreach ($files as $file) {
    if ($file === '.' || $file === '..') {
        continue;
    }

    $localFile = $sourceDir . $file;
    $remoteFile = $remoteDir . $file;

    echo "DEBUG: Local file path being used: $localFile<br>";
    echo "DEBUG: Remote file path being used: $remoteFile<br>";

    if (!file_exists($localFile)) {
        echo "❌ ERROR: File does not exist locally: $localFile<br>";
        continue;
    }

    if (ftp_put($conn, $remoteFile, $localFile, FTP_BINARY)) {
        echo "✅ Transferred: $file<br>";
        $transferred++;
    } else {
        echo "❌ Failed to transfer: $file<br>";
        $failed++;
    }
}

// Close FTP connection
ftp_close($conn);

// Summary
echo "<hr>";
echo "✅ Transfer Complete<br>";
echo "➡️ Total Transferred: $transferred<br>";
echo "❌ Total Failed: $failed<br>";
?>
