<?php
/**
 * GET /api/backup.php
 * Descarcă un backup consistent al bazei de date SQLite (un singur fișier .sqlite).
 * Folosește VACUUM INTO → copie curată, inclusiv datele din WAL.
 */
require_once __DIR__ . '/../includes/db.php';

try {
    $pdo = db(); // asigură migrațiile

    $tmp = tempnam(sys_get_temp_dir(), 'gnp_bk');
    @unlink($tmp);                 // VACUUM INTO cere o cale care NU există
    $tmp .= '.sqlite';

    $pdo->exec("VACUUM INTO '" . str_replace("'", "''", $tmp) . "'");

    if (!is_file($tmp)) {
        throw new RuntimeException('Backup-ul nu a putut fi creat.');
    }

    $fname = 'gestionare-backup-' . date('Ymd-His') . '.sqlite';
    header('Content-Type: application/x-sqlite3');
    header('Content-Disposition: attachment; filename="' . $fname . '"');
    header('Content-Length: ' . filesize($tmp));
    header('Cache-Control: no-store');
    readfile($tmp);
    @unlink($tmp);
    exit;
} catch (Throwable $e) {
    error_log('[backup] ' . $e->getMessage());
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Eroare backup: ' . $e->getMessage();
}
