<?php

session_start();
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    die('Unauthorized');
}

require_once '../includes/auth.php';
require_once '../classes/Database.php';
require_once '../classes/LocalBackupManager.php';

$database = new Database();
$conn = $database->getConnection();

if (!$conn) {
    http_response_code(500);
    die('Database connection failed');
}

$auth = new Auth($conn);
if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    http_response_code(403);
    die('Access denied');
}

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    http_response_code(400);
    die('Invalid backup ID');
}

$backupId = (int)$_GET['id'];

$localBackupManager = new LocalBackupManager($conn);

$filePath = $localBackupManager->getBackupFilePath($backupId);

if (!$filePath || !file_exists($filePath)) {
    http_response_code(404);
    die('Backup file not found');
}

$backupDir = realpath(__DIR__ . '/../backups/archive');
$fileRealPath = realpath($filePath);

if (!$fileRealPath || strpos($fileRealPath, $backupDir) !== 0) {
    http_response_code(403);
    die('Access denied');
}

$fileName = basename($filePath);
$fileSize = filesize($filePath);

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . $fileSize);
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

if (ob_get_level()) {
    ob_clean();
}

readfile($filePath);

require_once '../classes/Logger.php';
$logger = new Logger($conn, $_SESSION['user_id']);
$logger->log(
    'DOWNLOAD_LOCAL_BACKUP',
    'backups',
    "Downloaded local backup ID: $backupId, File: $fileName",
    $backupId,
    'backup_history'
);

exit;
?>