<?php
if (session_status() === PHP_SESSION_NONE) {
	session_start();
}

if (!defined('LUNA_APP')) {
	define('LUNA_APP', true);
}

$fileUrl = isset($_GET['file']) ? (string)$_GET['file'] : '';

if ($fileUrl === '') {
	die('Thiếu đường dẫn file');
}

// Ngăn traversal
$fileUrl = str_replace(['../', './', '\\'], ['','','/'], $fileUrl);

// Try multiple possible paths
$documentDir = realpath(__DIR__ . '/../data/File/Document');
$goDocumentDir = realpath(__DIR__ . '/../data/File/GoDocument');

// Try relative to project root first
$fullPath = realpath(__DIR__ . '/../' . $fileUrl);

// If not found, try in document directories
if ($fullPath === false || !is_file($fullPath)) {
    if ($documentDir) {
        $fullPath = realpath($documentDir . '/' . basename($fileUrl));
    }
    if (($fullPath === false || !is_file($fullPath)) && $goDocumentDir) {
        $fullPath = realpath($goDocumentDir . '/' . basename($fileUrl));
    }
}

if ($fullPath === false || !is_file($fullPath)) {
	die('Không tìm thấy file');
}

// Security check: ensure file is in allowed directories
$isInDocumentDir = $documentDir && strpos($fullPath, $documentDir) === 0;
$isInGoDocumentDir = $goDocumentDir && strpos($fullPath, $goDocumentDir) === 0;

if (!$isInDocumentDir && !$isInGoDocumentDir) {
	die('File không được phép truy cập');
}

// Chỉ cho phép PDF
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $fullPath);
finfo_close($finfo);

if ($mime !== 'application/pdf') {
	die('Không phải PDF');
}

// Set headers for PDF display
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . basename($fullPath) . '"');
header('Content-Length: ' . filesize($fullPath));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

// Output PDF content
readfile($fullPath);
?>
