<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/api_service.php';
require_once __DIR__ . '/../includes/invoice_contract.php';

$token = trim($_GET['token'] ?? '');

if ($token === '') {
    http_response_code(404);
    exit('Not found');
}

try {
    $contract = api_find_contract($token);
} catch (Throwable) {
    http_response_code(502);
    exit('Unable to load document');
}

if (!$contract) {
    http_response_code(404);
    exit('Not found');
}

if (contract_signed_pdf_available($contract)) {
    $file = contract_signed_pdf_path($contract);
} else {
    $file = contract_resolve_contract_pdf_disk_path($contract) ?? '';

    if ($file === '' && invoice_contract_is($contract)) {
        require_once __DIR__ . '/../includes/invoice_pdf_generator.php';
        $generated = invoice_ensure_contract_pdf($contract);
        if ($generated !== null) {
            $file = $generated;
        }
    }

    if ($file === '' || !is_file($file)) {
        http_response_code(404);
        exit('PDF not available. Check vendor folder and uploads/contracts permissions.');
    }
}

if (!is_file($file)) {
    http_response_code(404);
    exit('PDF not found');
}

$filename = basename($file);
$download = isset($_GET['download']) && $_GET['download'] === '1';
$disposition = $download ? 'attachment' : 'inline';

header('Content-Type: application/pdf');
header('Content-Disposition: ' . $disposition . '; filename="' . $filename . '"');
header('Accept-Ranges: bytes');
header('Content-Length: ' . (string)filesize($file));
header('Cache-Control: private, max-age=3600');
header('X-Content-Type-Options: nosniff');

readfile($file);
exit;
