<?php
/**
 * Download backup file - System Admin only
 */

require_once __DIR__ . '/../../includes/auth.php';
requireAuth();
requireSystemAdmin();

$fileName = $_GET['file'] ?? '';
if (!$fileName || !preg_match('/^[a-zA-Z0-9._-]+\.sql$/', $fileName)) {
    header('HTTP/1.0 400 Bad Request');
    die('Invalid file name.');
}

$backupDir = __DIR__ . '/../../backups';
$filePath = $backupDir . '/' . $fileName;

if (!file_exists($filePath) || !is_readable($filePath)) {
    header('HTTP/1.0 404 Not Found');
    die('Backup file not found.');
}

// Security: Ensure file is within backup directory
$realPath = realpath($filePath);
$realBackupDir = realpath($backupDir);
if (!$realPath || strpos($realPath, $realBackupDir) !== 0) {
    header('HTTP/1.0 403 Forbidden');
    die('Access denied.');
}

// Set headers for download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($fileName) . '"');
header('Content-Length: ' . filesize($filePath));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

// Stream the file
readfile($filePath);
exit;
