<?php
header('Content-Type: application/json');

if (!isset($baseDir)) {
    $baseDir = $_SERVER['DOCUMENT_ROOT'];
}

require_once $baseDir . '/../scripts/session_functions.php';

ini_wkvs_session();

check_user_permission('wk_leitung');


if (!isset($_GET['order_id']) || intval($_GET['order_id']) < 1) {
    echo json_encode(['success' => false, 'message' => 'Keine Id angegeben']);
    http_response_code(422);
    exit; 
}

if (!isset($baseDir)) {
	$baseDir = $_SERVER['DOCUMENT_ROOT'];
}

$id = intval($_GET['order_id']);

$filename = basename($id . '.pdf');

$filePath = $baseDir . '/../private-files/rechnungen/' . $filename;

if (!file_exists($filePath)) {
    http_response_code(404);
    exit('File not found');
}

// 5. Send headers
header('Content-Description: File Transfer');
header('Content-Type: application/pdf'); // adjust if needed
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Length: ' . filesize($filePath));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: public');

// 6. Clean output buffer
ob_clean();
flush();

// 7. Stream file
readfile($filePath);
exit;