<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('dashboard');

$root = realpath(__DIR__ . '/..');
if (!$root) { http_response_code(500); exit('Backup root not found'); }
$backupDir = $root . '/storage/backups';
if (!is_dir($backupDir)) mkdir($backupDir, 0775, true);
$filename = 'ugfx-backup-' . date('Ymd-His') . '.zip';
$zipPath = $backupDir . '/' . $filename;

$zip = new ZipArchive();
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
    http_response_code(500);
    exit('Could not create backup zip.');
}

$includeDirs = ['data', 'storage/uploads'];
foreach ($includeDirs as $rel) {
    $full = $root . '/' . $rel;
    if (!is_dir($full)) continue;
    $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($full, FilesystemIterator::SKIP_DOTS));
    foreach ($it as $file) {
        if (!$file->isFile()) continue;
        $path = $file->getPathname();
        $local = substr($path, strlen($root) + 1);
        $zip->addFile($path, $local);
    }
}
$zip->close();
ugfx_admin_log('backup_created', ['file' => $filename]);

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($zipPath));
readfile($zipPath);
exit;
