<?php

declare(strict_types=1);

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

auth_require();

$token = trim((string)($_GET['token'] ?? ''));
$id = (int)($_GET['id'] ?? 0);

if ($token === '' && $id <= 0) {
    http_response_code(400);
    exit('Missing contract token.');
}

try {
    $contract = admin_resolve_download_contract($token, $id);
} catch (Throwable) {
    http_response_code(502);
    exit('Unable to load contract.');
}

if (!$contract) {
    http_response_code(404);
    exit('Contract not found.');
}

$filePath = '';
$filename = '';

$signedPdfPath = contract_resolve_signed_pdf_disk_path($contract);
if ($signedPdfPath !== null && !contract_signed_pdf_needs_regeneration($contract)) {
    $filePath = $signedPdfPath;
    $filename = basename($signedPdfPath);
} elseif (invoice_contract_is($contract)) {
    if (($contract['status'] ?? '') === 'signed' && contract_ensure_signed_pdf($contract)) {
        $signedPdfPath = contract_resolve_signed_pdf_disk_path($contract);
        if ($signedPdfPath !== null) {
            $filePath = $signedPdfPath;
            $filename = basename($signedPdfPath);
        }
    }

    if ($filePath === '') {
        require_once __DIR__ . '/../includes/invoice_pdf_generator.php';
        $previewPath = invoice_ensure_contract_pdf($contract);
        if ($previewPath !== null) {
            $filePath = $previewPath;
            $filename = basename($previewPath);
        }
    }
} else {
    $contractPdfPath = contract_resolve_contract_pdf_disk_path($contract);
    if ($contractPdfPath !== null) {
        $filePath = $contractPdfPath;
        $filename = basename($contractPdfPath);
    }

    if ($filePath === '' && contract_ensure_signed_pdf($contract)) {
        $signedPdfPath = contract_resolve_signed_pdf_disk_path($contract);
        if ($signedPdfPath !== null) {
            $filePath = $signedPdfPath;
            $filename = basename($signedPdfPath);
        }
    }
}

if ($filePath === '' || !is_file($filePath)) {
    http_response_code(404);
    exit(invoice_contract_is($contract)
        ? 'PDF could not be generated. Open test-pdf.php on the server or check vendor folder and uploads/contracts permissions.'
        : 'PDF file not found on server.');
}

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

readfile($filePath);
exit;
