<?php
// Pure PHP backup solution - no shell commands
ini_set('display_errors', 0);
error_reporting(0);

// Set longer time limits for this script
set_time_limit(600); // 10 minutes
ini_set('memory_limit', '512M');

// Tell browser we're returning JSON
header('Content-Type: application/json');

// Paths
$source_dir = "/home/anesoft/public_html/app.anesoft.com";
$backup_dir = "/home/anesoft/public_html/backups";
$date = date('Y-m-d_H-i');
$backup_file = "{$backup_dir}/backup_app.anesoft.com_files_{$date}.zip"; // Using ZIP instead of TGZ

// Log array 
$log = array();
$log[] = "Starting backup at " . date('Y-m-d H:i:s');

// Create backup directory if needed
if (!is_dir($backup_dir)) {
    mkdir($backup_dir, 0755, true);
    $log[] = "Created backup directory";
}

// Create backup using PHP's ZipArchive
$success = false;
$log[] = "Creating ZIP archive";

try {
    // Initialize ZIP archive
    $zip = new ZipArchive();
    if ($zip->open($backup_file, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
        $log[] = "Initialized ZIP file";
        
        // Helper function to add files to ZIP
        function addDirToZip($zip, $dir, $basePath, &$log) {
            $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::LEAVES_ONLY
            );
            
            $count = 0;
            foreach ($files as $file) {
                if (!$file->isDir()) {
                    // Get real and relative path for current file
                    $filePath = $file->getRealPath();
                    $relativePath = substr($filePath, strlen($basePath) + 1);
                    
                    // Add current file to archive
                    $zip->addFile($filePath, $relativePath);
                    $count++;
                    
                    // Log progress periodically
                    if ($count % 1000 == 0) {
                        $log[] = "Added $count files to ZIP";
                    }
                }
            }
            return $count;
        }
        
        // Add files to ZIP
        $fileCount = addDirToZip($zip, $source_dir, dirname($source_dir), $log);
        $log[] = "Added $fileCount files to ZIP archive";
        
        // Close ZIP
        $zip->close();
        $log[] = "Closed ZIP archive";
        
        // Check if file exists and has size
        if (file_exists($backup_file) && filesize($backup_file) > 0) {
            $size = filesize($backup_file);
            $size_text = ($size > 1048576) ? round($size/1048576, 2) . " MB" : round($size/1024, 2) . " KB";
            $log[] = "Backup created successfully: " . $size_text;
            $success = true;
        } else {
            $log[] = "Backup file not created or has zero size";
            $success = false;
            $size_text = "0 KB";
        }
    } else {
        $log[] = "Failed to create ZIP file";
        $success = false;
        $size_text = "N/A";
    }
} catch (Exception $e) {
    $log[] = "Error: " . $e->getMessage();
    $success = false;
    $size_text = "N/A";
}

$log[] = "Finished backup at " . date('Y-m-d H:i:s');

// Prepare response array
$response = array(
    'success' => $success,
    'log' => $log,
    'backup_file' => $backup_file,
    'backup_size' => $size_text,
    'timestamp' => date('Y-m-d H:i:s')
);

// Output JSON response
echo json_encode($response);
exit;
?>