<?php
session_start();
require_once 'config.php';

// Check if user is logged in and is admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== 1) {
    http_response_code(403);
    die('Unauthorized access');
}

$filename = $_GET['file'] ?? '';

if (empty($filename)) {
    http_response_code(400);
    die('No file specified');
}

// Security: Only allow files from reports directory
$reportsDir = 'reports/';
if (strpos($filename, $reportsDir) !== 0) {
    http_response_code(403);
    die('Invalid file path');
}

// Check if file exists
if (!file_exists($filename)) {
    http_response_code(404);
    die('File not found');
}

// Get file extension to determine content type
$fileExtension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$contentType = 'application/octet-stream';

switch ($fileExtension) {
    case 'pdf':
        $contentType = 'application/pdf';
        break;
    case 'xlsx':
        $contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        break;
    case 'html':
        $contentType = 'text/html';
        break;
}

// Set headers for download
header('Content-Type: ' . $contentType);
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Length: ' . filesize($filename));
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');

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