<?php
/**
 * Digify OS - Automated Daily Backup & FTP Transfer
 * Optimized for: ftp.pragatisalt.com 
 * Version: FileZilla Emulation Mode
 */

// --- PERFORMANCE TUNING ---
set_time_limit(0);           
ini_set('memory_limit', '512M'); 
ignore_user_abort(true);     

// ========== CONFIGURATION ========== //

define('DB_HOST', 'localhost');
define('DB_USER', 'cybsoul_loyality');
define('DB_PASSWORD', 'Digital@1270');
define('DB_NAME', 'cybsoul_taskapp');

$backup_dir = '/home6/cybsoul/backups'; 
$source_dir = '/home6/cybsoul/kids.eventsnews.in';

// FTP Details (Server B)
$ftp_server   = "ftp.pragatisalt.com";
$ftp_user     = "app@digifyinfotech.in";
$ftp_pass     = "Hvsk@9024";
$ftp_port     = 21;

/** * REMOTE PATH SETTING:
 * Agar FileZilla mein login karte hi aap sahi folder mein hote hain,
 * toh ise khali "" chhodein.
 */
$remote_target_path = "app"; 

$retention_days = 30;

// ========== BACKUP PROCESS START ========== //

echo "--- Backup process started at " . date('Y-m-d H:i:s') . " ---\n";

if (!is_dir($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

$date = date('Y-m-d');
$db_backup_file = $backup_dir . '/db_backup_' . $date . '.sql.gz';
$files_backup_file = $backup_dir . '/files_backup_' . $date . '.zip';

// --- 1. Database Backup ---
echo "💾 Exporting Database... ";
$command_db = "mysqldump --host=" . DB_HOST . " --user=" . DB_USER . " --password='" . DB_PASSWORD . "' " . DB_NAME . " | gzip > " . $db_backup_file;
system($command_db, $result_db);
echo ($result_db === 0) ? "✅ Success\n" : "❌ Failed\n";

// --- 2. Files Backup ---
if (file_exists($files_backup_file)) { unlink($files_backup_file); }
echo "📦 Zipping Files... ";
$command_files = "zip -r -q " . $files_backup_file . " " . $source_dir . " -x '*/uploads/*'";
system($command_files, $result_files);

if ($result_files === 0 && file_exists($files_backup_file)) {
    echo "✅ Success (" . round(filesize($files_backup_file)/1024/1024, 2) . " MB)\n";
} else {
    echo "❌ Failed\n";
}

// --- 3. FTP Transfer ---
if (file_exists($db_backup_file) || file_exists($files_backup_file)) {
    echo "🚀 Connecting to FTP: $ftp_server...\n";
    
    // Connect with extended timeout
    $conn_id = ftp_connect($ftp_server, $ftp_port, 300); 
    if ($conn_id) {
        $login_result = @ftp_login($conn_id, $ftp_user, $ftp_pass);
        
        // Passive mode on (Crucial for Shared Hosting)
        ftp_pasv($conn_id, true); 

        if ($login_result) {
            echo "✅ FTP Login Successful.\n";
            $current_dir = ftp_pwd($conn_id);
            echo "Working Directory: " . $current_dir . "\n";

            // PERMISSION TEST: Creating a test file using FileZilla style path
            $test_name = "test_upload_" . time() . ".txt";
            if (ftp_put($conn_id, "./" . $test_name, $db_backup_file, FTP_BINARY)) {
                echo "📝 Write Test: OK (File created successfully)\n";
                ftp_delete($conn_id, "./" . $test_name);
            } else {
                echo "❌ Write Test: FAILED. Server is still rejecting files.\n";
            }

            // DB Upload
            if (file_exists($db_backup_file)) {
                $remote_db = "./" . basename($db_backup_file);
                echo "   -> Sending DB ($remote_db)... ";
                if (ftp_put($conn_id, $remote_db, $db_backup_file, FTP_BINARY)) {
                    echo "Done.\n";
                } else {
                    echo "FAILED.\n";
                }
            }

            // ZIP Upload
            if (file_exists($files_backup_file)) {
                $remote_zip = "./" . basename($files_backup_file);
                echo "   -> Sending ZIP ($remote_zip)... ";
                if (ftp_put($conn_id, $remote_zip, $files_backup_file, FTP_BINARY)) {
                    echo "Done.\n";
                } else {
                    echo "FAILED.\n";
                }
            }
            ftp_close($conn_id);
        } else {
            echo "❌ FTP Login Failed.\n";
        }
    } else {
        echo "❌ FTP Connection Failed.\n";
    }
}

// --- 4. Cleanup ---
echo "🧹 Cleaning up local old backups...\n";
$files = glob($backup_dir . '/*');
foreach ($files as $file) {
    if (is_file($file) && (time() - filemtime($file) >= ($retention_days * 86400))) {
        unlink($file);
    }
}

echo "--- Backup process finished at " . date('H:i:s') . " ---\n";
?>