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

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

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

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

function respond($ok, $message, $data = []) {
	echo json_encode([
		'success' => $ok ? true : false,
		'message' => $message,
		'data' => $data,
	], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
	exit;
}

error_log("pdf_data.php called with fileUrl: " . $fileUrl);

if ($fileUrl === '') {
	error_log("pdf_data.php: Empty fileUrl");
	respond(false, '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));
    }
}

error_log("pdf_data.php: fullPath = " . $fullPath);

if ($fullPath === false || !is_file($fullPath)) {
	error_log("pdf_data.php: File not found: " . $fullPath);
	respond(false, '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) {
	error_log("pdf_data.php: File not in allowed directory: " . $fullPath);
	respond(false, '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);
error_log("pdf_data.php: MIME type = " . $mime);

if ($mime !== 'application/pdf') {
	error_log("pdf_data.php: Not a PDF file");
	respond(false, 'Không phải PDF');
}

$content = @file_get_contents($fullPath);
if ($content === false) {
	error_log("pdf_data.php: Cannot read file");
	respond(false, 'Không đọc được file');
}

$base64 = base64_encode($content);
error_log("pdf_data.php: Base64 length = " . strlen($base64));
respond(true, 'OK', ['base64' => $base64, 'filename' => basename($fullPath)]);
?>


