<?php
session_start();

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    header('HTTP/1.1 403 Forbidden');
    exit('Unauthorized access');
}

include 'layouts/dbconn.php';
include 'includes/AuditLogger.php';

// Initialize the audit logger
$logger = new AuditLogger($conn, $_SESSION['user_id']);

// Backup directory
$backup_dir = 'backups/';

// Get and sanitize filename
$filename = basename($_GET['file'] ?? '');
$filepath = $backup_dir . $filename;

// Validate file exists and is within backup directory
if (empty($filename) || !file_exists($filepath) || dirname(realpath($filepath)) !== realpath($backup_dir)) {
    header('HTTP/1.1 404 Not Found');
    exit('File not found');
}

// Log the download
$logger->logConfigChange(
    'backup_download',
    "Downloaded backup file: $filename"
);

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

// Output file
readfile($filepath);
exit();
?>