<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/functions_backup.php';
require_once dirname(__DIR__) . '/includes/auth.php';
requirePermission('backup_download');

$file = backupSafeFilename($_GET['file'] ?? '');
if ($file === '') {
    http_response_code(400);
    echo '잘못된 백업 파일 요청입니다.';
    exit;
}

$path = backupFilePath($file);
if (!$path || !is_file($path)) {
    http_response_code(404);
    echo '백업 파일을 찾을 수 없습니다.';
    exit;
}
writeAuditLog('backup_downloaded', 'Backup downloaded: ' . $file, 'success', 'info', 'backup', $file);

$contentType = preg_match('/\.json$/i', $file) ? 'application/json; charset=utf-8' : 'application/octet-stream';
header('Content-Type: ' . $contentType);
header('Content-Disposition: attachment; filename="' . rawurlencode($file) . '"');
header('Content-Length: ' . filesize($path));
header('X-Content-Type-Options: nosniff');
readfile($path);
exit;
