<?php
// PHP backup using PharData class
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', '2048M');

// 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');
$tar_file = "{$backup_dir}/backup_app.anesoft.com_files_{$date}.tar";
$backup_file = "{$backup_dir}/backup_app.anesoft.com_files_{$date}.tar.gz";

// 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 PharData
$success = false;
$log[] = "Creating TAR archive";

try {
    // Make sure no old archives remain with the same name
    if (file_exists($tar_file)) {
        unlink($tar_file);
    }
    if (file_exists($backup_file)) {
        unlink($backup_file);
    }
    
    // Create new tar archive
    $phar = new PharData($tar_file);
    
    // Add the entire directory recursively
    $baseDir = dirname($source_dir);
    $relativeDir = basename($source_dir);
    
    $log[] = "Adding files to archive";
    $phar->buildFromDirectory($source_dir);
    $log[] = "Files added to archive successfully";
    
    // Compress the tar file
    $log[] = "Compressing TAR to GZIP";
    $phar->compress(Phar::GZ);
    
    // Remove the uncompressed tar
    unlink($tar_file);
    
    // 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";
    }
} 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;
?>