<?php

declare(strict_types=1);

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

force_customer_locale_de();

$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');
}

$pdfDirectUrl = contract_public_pdf_url($contract);
$backUrl = app_path('/contract/' . rawurlencode($token));

render_header('reg_pdf_modal_title', [
    'layout' => 'public',
    'nav' => false,
    'body_class' => 'reg-pdf-view-page hide-global-lang',
    'hide_lang_switcher' => true,
]);
?>

<div class="reg-pdf-view-page-shell">
    <header class="reg-pdf-view-page-head">
        <a href="<?= e($backUrl) ?>" class="reg-pdf-view-back" aria-label="<?= e(__('reg_back')) ?>">
            <span class="material-symbols-rounded">arrow_back</span>
        </a>
        <h1><?= e(__('reg_pdf_modal_title')) ?></h1>
    </header>

    <div id="regPdfViewerStatus" class="reg-pdf-viewer-status"><?= e(__('reg_pdf_loading')) ?></div>
    <div id="regPdfViewerHost" class="reg-pdf-viewer-host"></div>
    <div id="regPdfViewerError" class="reg-pdf-viewer-error hidden">
        <p><?= e(__('reg_pdf_view_error')) ?></p>
        <a href="<?= e($pdfDirectUrl) ?>" target="_blank" rel="noopener" class="btn-primary"><?= e(__('reg_open_pdf')) ?></a>
    </div>
</div>

<script src="<?= e(app_asset('vendor/pdfjs/pdf.min.js')) ?>"></script>
<script src="<?= e(app_asset('js/pdf-viewer.js')) ?>"></script>
<script>
(function () {
    'use strict';

    var pdfUrl = <?= json_encode($pdfDirectUrl, JSON_UNESCAPED_SLASHES) ?>;
    var host = document.getElementById('regPdfViewerHost');
    var status = document.getElementById('regPdfViewerStatus');
    var errorBox = document.getElementById('regPdfViewerError');

    function showError() {
        status.classList.add('hidden');
        host.classList.add('hidden');
        errorBox.classList.remove('hidden');
    }

    window.KarviPdfViewer.renderInto(pdfUrl, host)
        .then(function () {
            status.classList.add('hidden');
            host.classList.remove('hidden');
        })
        .catch(showError);
})();
</script>

<?php
render_footer(['layout' => 'public']);
