<?php
session_start();

/**
 * Full Website Backup API
 * Generates a ZIP archive of the entire website and triggers a download.
 */

// Basic security check (matching pattern in other APIs)
if (!isset($_SESSION['userid']) || empty($_SESSION['userid'])) {
    http_response_code(403);
    die("Unauthorized access.");
}

// Increase time and memory limit for potentially large backups
set_time_limit(0);
ini_set('memory_limit', '1024M');

// Website root directory (going up from APIs/ folder)
$rootPath = realpath(__DIR__ . '/../../');
$zipFileName = 'madrasa_full_backup_' . date('Y-m-d_H-i-s') . '.zip';
$tempFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $zipFileName;

try {
    // Initialize ZipArchive
    $zip = new ZipArchive();
    if ($zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
        throw new Exception("Could not create backup file in temporary directory.");
    }

    // Create recursive directory iterator
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($rootPath),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file) {
        // Skip directories (ZipArchive handles them)
        if (!$file->isDir()) {
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($rootPath) + 1);

            // Add file to zip
            $zip->addFile($filePath, $relativePath);
        }
    }

    // Close and save zip
    $zip->close();

    // Send download headers
    if (file_exists($tempFile)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . basename($zipFileName) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($tempFile));

        // Clear output buffer to avoid corruption
        if (ob_get_level()) {
            ob_end_clean();
        }

        // Read and output in chunks to be memory-efficient
        $handle = fopen($tempFile, 'rb');
        while (!feof($handle)) {
            echo fread($handle, 1024 * 64); // 64KB chunks
            flush();
        }
        fclose($handle);

        // Delete temporary file from server after download
        unlink($tempFile);
        exit;
    } else {
        throw new Exception("Backup file generation failed.");
    }
} catch (Exception $e) {
    http_response_code(500);
    echo "Error generating backup: " . $e->getMessage();
}
