<?php

declare(strict_types=1);

/**
 * Public contract view + Sign contract (public) on /contracts/sign/{sign_token}
 *
 * @var \App\Models\ContractPublicViewResult $result
 * @var array<string,mixed> $contract
 * @var array<string,mixed> $rawData
 * @var string|null $errorCode
 * @var int $httpStatus
 * @var string $signTokenDisplay
 * @var string $formAction
 * @var string $legacySignUrl
 * @var array<string,mixed>|null $signResult
 * @var bool $canSign
 */

require_once dirname(__DIR__, 2) . '/includes/layout.php';

force_customer_locale_de();

render_header('title_public_contract_sign', [
    'layout' => 'public',
    'nav' => false,
    'hide_lang_switcher' => true,
]);
?>

<div class="max-w-3xl mx-auto animate-fade-in">
    <div class="mb-6 text-center">
        <p class="text-xs uppercase tracking-wide text-karvi-500 mb-1">Sign contract (public)</p>
        <h1 class="font-display font-bold text-2xl text-karvi-950"><?= e(__('public_contract_sign_heading')) ?></h1>
    </div>

    <?php if (is_array($signResult)): ?>
    <div class="mb-6 p-4 rounded-2xl border <?= !empty($signResult['success']) ? 'border-green-200 bg-green-50 text-green-900' : 'border-karvi-950 bg-karvi-950 text-white' ?>">
        <div class="flex items-start gap-3">
            <span class="material-symbols-rounded shrink-0"><?= !empty($signResult['success']) ? 'check_circle' : 'error' ?></span>
            <p class="text-sm font-medium"><?= e((string)($signResult['message'] ?? '')) ?></p>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!$result->success): ?>
    <div class="card-elevated text-center">
        <div class="empty-state-icon mx-auto mb-4">
            <span class="material-symbols-rounded">link_off</span>
        </div>
        <h2 class="font-display font-bold text-xl text-karvi-950 mb-2"><?= e(__('public_contract_view_error_title')) ?></h2>
        <p class="text-karvi-600 text-sm"><?= e($result->message) ?></p>
        <?php if (!empty($errorCode)): ?>
        <p class="text-xs font-mono text-karvi-400 mt-3"><?= e((string)$errorCode) ?></p>
        <?php endif; ?>
    </div>
    <?php else: ?>

    <?php if ($result->message !== '' && $result->message !== 'OK' && empty($signResult['success'])): ?>
    <div class="mb-4 flex items-start gap-3 p-4 rounded-2xl border border-karvi-200 bg-karvi-50 text-karvi-800">
        <span class="material-symbols-rounded shrink-0 text-base">info</span>
        <p class="text-sm"><?= e($result->message) ?></p>
    </div>
    <?php endif; ?>

    <div class="card !p-5 sm:!p-6 mb-6">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5 pb-4 border-b border-karvi-200">
            <div>
                <h2 class="font-display font-bold text-lg text-karvi-950"><?= e($contract['restaurant_name'] ?? __('partnership_agreement')) ?></h2>
                <?php if (!empty($contract['brand'])): ?>
                <p class="text-sm text-karvi-500 mt-0.5"><?= e((string)$contract['brand']) ?></p>
                <?php endif; ?>
            </div>
            <?php if (!empty($contract['contract_status'])): ?>
            <span class="status-badge status-<?= e(strtolower((string)$contract['contract_status'])) ?> self-start">
                <?= e((string)$contract['contract_status']) ?>
            </span>
            <?php endif; ?>
        </div>

        <dl>
            <?php contract_details_render_field_rows([
                __('field_restaurant_name') => $contract['restaurant_name'] ?? '',
                __('field_brand') => $contract['brand'] ?? '',
                __('field_owner_name') => $contract['owner_name'] ?? '',
                __('field_company_phone') => $contract['company_phone'] ?? '',
                __('field_address') => contract_details_address($contract),
                __('field_email') => $contract['email'] ?? '',
                'contract_url' => $contract['contract_url'] ?? '',
                'type' => $contract['type'] ?? '',
                'contract_status' => $contract['contract_status'] ?? '',
                __('field_created_at') => $contract['created_at'] ?? '',
                'viewed_at' => $contract['viewed_at'] ?? '',
                'signed_at' => $contract['signed_at'] ?? '',
            ]); ?>
        </dl>
    </div>

    <?php if ($rawData !== []): ?>
    <div class="card !p-5 sm:!p-6 mb-6">
        <h3 class="font-display font-bold text-base text-karvi-950 mb-4 pb-3 border-b border-karvi-200">raw_data</h3>
        <?php contract_details_render_raw_data($rawData); ?>
    </div>
    <?php endif; ?>

    <?php if ($canSign): ?>
    <div class="card !p-5 sm:!p-6">
        <h3 class="font-display font-bold text-base text-karvi-950 mb-4"><?= e(__('public_sign_form_heading')) ?></h3>
        <form method="POST" action="<?= e($formAction) ?>" id="publicSignForm" class="space-y-4">
            <input type="hidden" name="signed_from" value="customer page">
            <input type="hidden" name="user_agent" id="signUserAgent" value="">
            <input type="hidden" name="browser" id="signBrowser" value="">
            <input type="hidden" name="device_type" id="signDeviceType" value="">
            <input type="hidden" name="os" id="signOs" value="">
            <input type="hidden" name="screen_resolution" id="signScreen" value="">
            <input type="hidden" name="timezone" id="signTimezone" value="">

            <div class="p-4 rounded-xl bg-karvi-50 border border-karvi-200">
                <label class="inline-flex items-start gap-3 cursor-pointer">
                    <input type="checkbox" name="terms_accepted" value="1" required class="mt-1">
                    <span class="text-sm text-karvi-800">
                        <?= e(__('public_sign_terms_label')) ?>
                        <?php if (!empty($contract['contract_url'])): ?>
                        <a href="<?= e((string)$contract['contract_url']) ?>" target="_blank" rel="noopener noreferrer" class="underline font-medium"><?= e(__('public_sign_terms_link')) ?></a>
                        <?php endif; ?>
                    </span>
                </label>
            </div>

            <details class="text-sm">
                <summary class="cursor-pointer text-karvi-600 hover:text-karvi-950"><?= e(__('public_sign_raw_data_optional')) ?></summary>
                <textarea name="raw_data_json" class="form-input font-mono text-xs min-h-[80px] mt-2 w-full" placeholder='{"note":"optional extra fields"}'></textarea>
            </details>

            <button type="submit" class="btn-primary w-full !py-3" id="publicSignSubmit">
                <span class="material-symbols-rounded">draw</span>
                <?= e(__('public_sign_submit')) ?>
            </button>
        </form>
        <p class="text-xs text-karvi-500 mt-4 text-center">
            <?= e(__('public_sign_legacy_hint')) ?>
            <a href="<?= e($legacySignUrl) ?>" class="underline"><?= e(__('public_sign_legacy_link')) ?></a>
        </p>
    </div>
    <?php endif; ?>

    <?php endif; ?>
</div>

<script>
(function () {
    var ua = navigator.userAgent || '';
    var fields = {
        signUserAgent: ua,
        signBrowser: (function () {
            if (ua.indexOf('Edg/') !== -1) return 'Edge';
            if (ua.indexOf('Chrome/') !== -1) return 'Chrome';
            if (ua.indexOf('Firefox/') !== -1) return 'Firefox';
            if (ua.indexOf('Safari/') !== -1) return 'Safari';
            return 'Other';
        })(),
        signDeviceType: /Mobi|Android/i.test(ua) ? 'mobile' : (/Tablet|iPad/i.test(ua) ? 'tablet' : 'desktop'),
        signOs: (function () {
            if (ua.indexOf('Windows') !== -1) return 'Windows';
            if (ua.indexOf('Mac OS') !== -1) return 'macOS';
            if (ua.indexOf('Android') !== -1) return 'Android';
            if (/iPhone|iPad|iPod/.test(ua)) return 'iOS';
            if (ua.indexOf('Linux') !== -1) return 'Linux';
            return 'Other';
        })(),
        signScreen: (window.screen ? window.screen.width + 'x' + window.screen.height : ''),
        signTimezone: (function () {
            try { return Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch (e) { return ''; }
        })()
    };
    Object.keys(fields).forEach(function (id) {
        var el = document.getElementById(id);
        if (el) el.value = fields[id];
    });
    var form = document.getElementById('publicSignForm');
    var btn = document.getElementById('publicSignSubmit');
    if (form && btn) {
        form.addEventListener('submit', function () {
            btn.disabled = true;
            btn.innerHTML = '<span class="material-symbols-rounded animate-spin">progress_activity</span> <?= e(__('submitting')) ?>';
        });
    }
})();
</script>

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