<?php
/**
 * Download Database Backup
 */

require_once __DIR__ . '/../includes/config.php';

// Check admin access
if (empty($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    http_response_code(403);
    exit('Unauthorized');
}

$filename = basename($_GET['file'] ?? '');

if (empty($filename) || !preg_match('/^backup_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.sql$/', $filename)) {
    http_response_code(400);
    exit('Invalid backup file');
}

$backup_dir = __DIR__ . '/../backups';
$filepath = $backup_dir . '/' . $filename;

if (!file_exists($filepath)) {
    http_response_code(404);
    exit('Backup file not found');
}

// Force download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($filepath));
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

readfile($filepath);
?>
