<?php
ob_start();
require __DIR__ . '/app/bootstrap.php';
require_roles('super_admin');

@set_time_limit(0);
@ignore_user_abort(true);
@ini_set('zlib.output_compression', '0');

$name = basename((string)request('file'));
if ($name === '' || !preg_match('/^[a-z0-9_.-]+\.sqlite$/i', $name)) {
    while (ob_get_level() > 0) @ob_end_clean();
    http_response_code(400);
    exit('Backup inválido.');
}

$backupRoot = dirname((string)config('db_path')) . '/backups';
$rootReal = realpath($backupRoot);
$path = $backupRoot . '/' . $name;
$pathReal = realpath($path);

if (!$rootReal || !$pathReal || strpos($pathReal, $rootReal . DIRECTORY_SEPARATOR) !== 0 || !is_file($pathReal) || !is_readable($pathReal)) {
    while (ob_get_level() > 0) @ob_end_clean();
    http_response_code(404);
    exit('Backup não encontrado.');
}

try {
    try { log_activity('download_server_backup', 'settings', null, $name); } catch (Throwable $ignored) {}

    clearstatcache(true, $pathReal);
    $size = (int)filesize($pathReal);
    if ($size < 16) throw new RuntimeException('Arquivo de backup vazio ou inválido.');

    $check = @fopen($pathReal, 'rb');
    $signature = $check ? fread($check, 16) : '';
    if (is_resource($check)) fclose($check);
    if ($signature !== "SQLite format 3\000") throw new RuntimeException('Arquivo não é um SQLite válido.');

    if (session_status() === PHP_SESSION_ACTIVE) @session_write_close();
    while (ob_get_level() > 0) @ob_end_clean();

    header('Content-Type: application/vnd.sqlite3');
    header('Content-Disposition: attachment; filename="' . $name . '"; filename*=UTF-8\'\'' . rawurlencode($name));
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . $size);
    header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: 0');
    header('X-Content-Type-Options: nosniff');

    $fp = @fopen($pathReal, 'rb');
    if (!$fp) throw new RuntimeException('Não foi possível acessar o arquivo.');
    while (!feof($fp)) {
        $chunk = fread($fp, 1024 * 1024);
        if ($chunk === false) break;
        echo $chunk;
        @flush();
    }
    fclose($fp);
    exit;
} catch (Throwable $e) {
    while (ob_get_level() > 0) @ob_end_clean();
    @error_log('Server backup download: ' . $e->getMessage());
    http_response_code(500);
    header('Content-Type: text/plain; charset=UTF-8');
    exit('Não foi possível baixar este backup. Tente novamente.');
}
