<?php

declare(strict_types=1);

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

force_customer_locale_de();

$token = $_GET['token'] ?? '';
$contract = null;
$apiError = null;

try {
    $contract = api_find_contract($token);
} catch (Throwable $e) {
    $apiError = api_error_message($e);
}

if (!$contract && !$apiError) {
    http_response_code(404);
    render_header('title_not_found', ['layout' => 'public', 'nav' => false, 'hide_lang_switcher' => true]);
    ?>
    <div class="card-elevated text-center max-w-md mx-auto animate-fade-in">
        <div class="empty-state-icon mx-auto mb-6">
            <span class="material-symbols-rounded">link_off</span>
        </div>
        <h2 class="font-display font-bold text-2xl text-karvi-950 mb-2"><?= e(__('reg_not_found_title')) ?></h2>
        <p class="text-karvi-500 text-sm"><?= e(__('reg_not_found_sub')) ?></p>
    </div>
    <?php
    render_footer(['layout' => 'public']);
    exit;
}

if ($apiError) {
    render_header('title_error', ['layout' => 'public', 'nav' => false, 'hide_lang_switcher' => true]);
    ?>
    <div class="card-elevated text-center max-w-md mx-auto">
        <span class="material-symbols-rounded text-5xl text-karvi-400 mb-4">cloud_off</span>
        <h2 class="font-display font-bold text-xl text-karvi-950 mb-2"><?= e(__('unable_load')) ?></h2>
        <p class="text-karvi-500 text-sm"><?= e($apiError) ?></p>
    </div>
    <?php
    render_footer(['layout' => 'public']);
    exit;
}

$signatures = api_get_signatures_for_token($token);
$isSigned = registration_is_fully_signed($contract, $signatures);
$ownerCount = registration_owner_count($contract);
$ownerNames = registration_owner_names($contract);
$completedSignatures = registration_completed_signature_count($contract, $signatures);
$signedPdfPath = $contract['signed_pdf_path'] ?? ($token . '_signed.pdf');
$signedPdfUrl = contract_signed_pdf_download_url($contract);
$summaryRows = registration_summary_rows($contract);
$pdfViewedAt = $contract['pdf_viewed_at'] ?? '';
$registrationEmail = trim((string)($contract['registration_email'] ?? $contract['email'] ?? $contract['partner_email'] ?? ''));
$initialStep = 1;
$initialOwnerIndex = $completedSignatures;

if ($completedSignatures > 0 && !$isSigned) {
    $initialStep = 3;
}

$config = app_config();
$requireLocation = (bool)($config['require_contract_location'] ?? true);
$regBodyClass = 'reg-page hide-global-lang' . ($requireLocation ? ' reg-location-pending' : ' reg-location-ready');
$regGatedHidden = $requireLocation ? ' hidden' : '';
$locationScripts = $requireLocation ? ['/assets/js/contract-location.js'] : [];

render_header('reg_page_title', [
    'layout' => 'public',
    'nav' => false,
    'body_class' => $regBodyClass,
    'hide_lang_switcher' => true,
]);
?>

<?php if ($requireLocation): ?>
<div id="locationGate" class="reg-location-gate" data-token="<?= e($token) ?>" data-link-location-url="<?= e(app_path('/api/link-location')) ?>">
    <div class="reg-location-gate-inner">
        <span class="material-symbols-rounded reg-location-icon" aria-hidden="true">my_location</span>
        <h2 class="font-display font-bold text-xl text-karvi-950"><?= e(__('reg_location_title')) ?></h2>
        <p id="locationGateMessage" class="reg-location-message"><?= e(__('reg_location_loading')) ?></p>
        <div id="locationGateSpinner" class="reg-location-spinner" aria-hidden="true"></div>
        <button type="button" id="locationGateRetry" class="btn-primary reg-location-retry hidden"><?= e(__('reg_location_retry')) ?></button>
    </div>
</div>
<?php endif; ?>

<?php if ($isSigned): ?>
<div id="contractLocationTracker" class="reg-shell reg-shell-done reg-gated<?= $regGatedHidden ?> animate-fade-in" data-token="<?= e($token) ?>">
    <div class="reg-success-card">
        <div class="success-ring">
            <span class="material-symbols-rounded">verified</span>
        </div>
        <h2 class="font-display font-bold text-2xl text-karvi-950 mb-2"><?= e(__('reg_success_title')) ?></h2>
        <p class="text-karvi-500 text-sm max-w-md mx-auto"><?= e(__('reg_success_sub', ['date' => format_date($contract['signed_at'] ?? null)])) ?></p>
        <a href="<?= $signedPdfUrl ?>" target="_blank" class="btn-primary mt-8 inline-flex">
            <span class="material-symbols-rounded">download</span>
            <?= e(__('reg_download_pdf')) ?>
        </a>
    </div>
</div>
<?php
    render_footer(['layout' => 'public', 'scripts' => $locationScripts]);
else:
?>

<div
    id="regWizard"
    class="reg-shell reg-gated<?= $regGatedHidden ?>"
    data-token="<?= e($token) ?>"
    data-pdf-viewed="<?= e($pdfViewedAt) ?>"
    data-owner-count="<?= (int)$ownerCount ?>"
    data-owner-names="<?= e(json_encode($ownerNames, JSON_UNESCAPED_UNICODE)) ?>"
    data-completed-signatures="<?= (int)$completedSignatures ?>"
    data-registration-email="<?= e($registrationEmail) ?>"
    data-registration-email-url="<?= e(app_path('/api/registration-email')) ?>"
    data-pdf-viewed-url="<?= e(app_path('/api/pdf-viewed')) ?>"
    data-sign-url="<?= e(app_path('/api/sign')) ?>"
    data-initial-step="<?= (int)$initialStep ?>"
    data-initial-owner-index="<?= (int)$initialOwnerIndex ?>"
>
    <header class="reg-header">
        <h1 class="font-display font-bold text-2xl text-karvi-950"><?= e(__('reg_page_title')) ?></h1>
        <p class="text-sm text-karvi-500 mt-1"><?= e(__('reg_page_sub', ['name' => $contract['restaurant_name'] ?? $contract['partner_name'] ?? ''])) ?></p>
        <ul class="reg-steps-simple">
            <li data-step-indicator="1">1. <?= e(__('reg_step_1')) ?></li>
            <li data-step-indicator="2">2. <?= e(__('reg_step_2')) ?></li>
            <li data-step-indicator="3">3. <?= e(__('reg_step_3')) ?></li>
        </ul>
    </header>

    <main class="reg-main">
        <section class="reg-panel reg-panel-step1" data-step-panel="1">
            <div class="reg-panel-head reg-panel-head-compact">
                <h2><?= e(__('reg_step_1_title')) ?></h2>
                <p><?= e(__('reg_step_1_sub')) ?></p>
            </div>
            <div class="reg-summary-card">
                <ul class="reg-summary-list">
                    <?php foreach ($summaryRows as $labelKey => $value): ?>
                    <li class="reg-summary-list-item">
                        <span class="reg-summary-label"><?= e(__($labelKey)) ?></span>
                        <span class="reg-summary-value"><?= e($value) ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </section>

        <section class="reg-panel reg-panel-step2 hidden" data-step-panel="2">
            <div class="reg-panel-head reg-panel-head-compact">
                <h2><?= e(__('reg_step_2_title')) ?></h2>
                <p class="reg-step-2-text"><?= e(__('reg_step_2_text')) ?></p>
            </div>

            <div class="reg-doc-email-field">
                <label for="registrationEmail" class="reg-doc-email-label"><?= e(__('reg_document_email_label')) ?></label>
                <input
                    type="email"
                    id="registrationEmail"
                    name="registration_email"
                    class="form-input reg-doc-email-input"
                    value="<?= e($registrationEmail) ?>"
                    placeholder="<?= e(__('reg_document_email_placeholder')) ?>"
                    autocomplete="email"
                    inputmode="email"
                >
            </div>

            <div id="regDocCard" class="reg-doc-card">
                <div id="regDocScroll" class="reg-doc-scroll" tabindex="0" aria-label="<?= e(__('reg_doc_scroll_label')) ?>">
                    <?= render_contract_document_html($contract) ?>
                </div>
            </div>
        </section>

        <section class="reg-panel reg-panel-step3 hidden" data-step-panel="3">
            <form id="signForm" class="reg-sign-form">
                <input type="hidden" name="token" value="<?= e($token) ?>">
                <input type="hidden" name="owner_index" id="ownerIndex" value="0">
                <input type="hidden" id="signerName" name="signer_name" value="">

                <div id="signChoiceScreen" class="reg-sign-choice">
                    <p id="signerDisplayName" class="reg-signer-name"></p>

                    <div id="signMethodButtons" class="reg-sign-method-grid">
                        <button type="button" id="btnOpenDraw" class="reg-sign-method-btn">
                            <span class="material-symbols-rounded">gesture</span>
                            <?= e(__('reg_sign_draw_btn')) ?>
                        </button>
                        <button type="button" id="btnOpenUpload" class="reg-sign-method-btn">
                            <span class="material-symbols-rounded">upload</span>
                            <?= e(__('reg_sign_upload_btn')) ?>
                        </button>
                    </div>

                    <div id="uploadPanel" class="reg-sign-upload-panel hidden">
                        <label class="reg-sign-upload-simple" for="signatureUpload">
                            <span class="material-symbols-rounded">add_photo_alternate</span>
                            <span><?= e(__('reg_tap_to_upload')) ?></span>
                            <input type="file" id="signatureUpload" accept="image/png,image/jpeg,image/jpg">
                        </label>
                        <img id="uploadPreview" class="reg-sign-upload-preview hidden" alt="">
                    </div>

                    <div id="drawPanel" class="reg-sign-draw-panel hidden">
                        <div id="regDrawStage" class="reg-sign-draw-stage-inline">
                            <div class="reg-sign-draw-frame">
                                <p class="reg-sign-draw-hint" aria-hidden="true"><?= e(__('reg_sign_here')) ?></p>
                                <canvas id="signatureCanvas" class="signature-canvas"></canvas>
                            </div>
                        </div>
                        <button type="button" id="clearSignature" class="reg-sign-draw-clear">
                            <?= e(__('clear_signature')) ?>
                        </button>
                    </div>
                </div>
            </form>
        </section>

        <section class="reg-panel hidden" data-step-panel="success">
            <div class="reg-success-card">
                <div class="success-ring">
                    <span class="material-symbols-rounded">check_circle</span>
                </div>
                <h2 class="font-display font-bold text-2xl text-karvi-950 mb-2"><?= e(__('reg_success_title')) ?></h2>
                <p class="text-karvi-500 text-sm"><?= e(__('reg_success_sub_short')) ?></p>
            </div>
        </section>
    </main>

    <footer class="reg-footer">
        <button type="button" id="regBackBtn" class="btn-secondary reg-footer-back hidden" aria-label="<?= e(__('reg_back')) ?>">
            <span class="material-symbols-rounded">arrow_back</span>
        </button>
        <button type="button" id="regNextBtn" class="btn-primary reg-footer-action"><?= e(__('reg_next')) ?></button>
    </footer>
</div>

<?php
render_footer([
    'layout' => 'public',
    'scripts' => array_merge($locationScripts, [
        '/assets/js/signature.js',
        '/assets/js/registration-wizard.js',
    ]),
]);
endif;
