<?php
// Stream a PDF inline in the browser to avoid download prompts
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Base directories that contain PDF files
$documentDir = realpath(__DIR__ . '/../data/File/Document');
$goDocumentDir = realpath(__DIR__ . '/../data/File/GoDocument');

$fileParam = isset($_GET['file']) ? (string)$_GET['file'] : '';
if ($fileParam === '') {
    http_response_code(400);
    echo 'Missing file parameter';
    exit;
}

// Convert to absolute path relative to project root if needed
// Support both absolute and relative inputs from DB
$candidate = $fileParam;
if (!preg_match('/^([a-zA-Z]:\\|\\\\|\/)?.*/', $candidate)) {
    $candidate = '../' . ltrim($candidate, '/\\');
}

$absPath = realpath(__DIR__ . '/../' . ltrim($fileParam, '/\\'));
if ($absPath === false) {
    // Try relative to documentDir first, then goDocumentDir
    if ($documentDir) {
        $absPath = realpath($documentDir . DIRECTORY_SEPARATOR . basename($fileParam));
    }
    if ($absPath === false && $goDocumentDir) {
        $absPath = realpath($goDocumentDir . DIRECTORY_SEPARATOR . basename($fileParam));
    }
}

// Check if file is in allowed directories
$isInDocumentDir = $documentDir && strpos($absPath, $documentDir) === 0;
$isInGoDocumentDir = $goDocumentDir && strpos($absPath, $goDocumentDir) === 0;

if ($absPath === false || (!$isInDocumentDir && !$isInGoDocumentDir)) {
    http_response_code(404);
    echo 'File not found or not in allowed directory';
    exit;
}

if (!is_file($absPath) || !is_readable($absPath)) {
    http_response_code(404);
    echo 'File not readable';
    exit;
}

// Headers for inline PDF display
header('X-Content-Type-Options: nosniff');
header('Cache-Control: private, no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-Type: application/pdf');
$filename = basename($absPath);
header('Content-Disposition: inline; filename="' . rawurlencode($filename) . '"');
header('Accept-Ranges: bytes');
header('Content-Length: ' . filesize($absPath));

// Stream file
readfile($absPath);
exit;
?>


