<?php

declare(strict_types=1);

const KARVI_LOCALES = ['en', 'de'];
const KARVI_LANG_COOKIE = 'karvi_lang';

function init_i18n(): void
{
    if (!empty($GLOBALS['karvi_translations'])) {
        return;
    }

    $locale = resolve_locale();
    $GLOBALS['karvi_locale'] = $locale;
    $file = __DIR__ . '/../lang/' . $locale . '.php';

    if (!file_exists($file)) {
        $file = __DIR__ . '/../lang/en.php';
        $GLOBALS['karvi_locale'] = 'en';
    }

    $GLOBALS['karvi_translations'] = require $file;
}

function resolve_locale(): string
{
    if (isset($_GET['lang']) && in_array($_GET['lang'], KARVI_LOCALES, true)) {
        return $_GET['lang'];
    }

    if (!empty($_COOKIE[KARVI_LANG_COOKIE]) && in_array($_COOKIE[KARVI_LANG_COOKIE], KARVI_LOCALES, true)) {
        return $_COOKIE[KARVI_LANG_COOKIE];
    }

    return detect_browser_locale();
}

function detect_browser_locale(): string
{
    $header = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
    if ($header === '') {
        return 'en';
    }

    foreach (explode(',', $header) as $part) {
        $lang = strtolower(trim(explode(';', $part)[0]));
        if (str_starts_with($lang, 'de')) {
            return 'de';
        }
        if (str_starts_with($lang, 'en')) {
            return 'en';
        }
    }

    return 'en';
}

function current_locale(): string
{
    init_i18n();
    return $GLOBALS['karvi_locale'] ?? 'en';
}

function force_customer_locale_de(): void
{
    set_locale('de');
}

function set_locale(string $locale): void
{
    if (!in_array($locale, KARVI_LOCALES, true)) {
        return;
    }

    setcookie(KARVI_LANG_COOKIE, $locale, [
        'expires' => time() + 365 * 86400,
        'path' => app_base_path() !== '' ? app_base_path() . '/' : '/',
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    $_COOKIE[KARVI_LANG_COOKIE] = $locale;
    $GLOBALS['karvi_locale'] = $locale;
    $GLOBALS['karvi_translations'] = require __DIR__ . '/../lang/' . $locale . '.php';
}

function __(string $key, array $replace = []): string
{
    init_i18n();
    $text = $GLOBALS['karvi_translations'][$key] ?? $key;

    foreach ($replace as $placeholder => $value) {
        $text = str_replace(':' . $placeholder, (string)$value, $text);
    }

    return $text;
}

function t_status(string $status): string
{
    $key = 'status_' . strtolower($status);
    $translated = __($key);
    return $translated !== $key ? $translated : $status;
}

function lang_switch_url(string $locale): string
{
    $return = resolve_lang_return_path();

    return app_path('/lang/' . $locale) . '?return=' . rawurlencode($return);
}

function resolve_lang_return_path(): string
{
    if (!empty($GLOBALS['karvi_lang_return']) && is_string($GLOBALS['karvi_lang_return'])) {
        return $GLOBALS['karvi_lang_return'];
    }

    return current_app_uri();
}

function set_contract_lang_return(string $token): void
{
    $token = trim($token);
    if (is_valid_contract_token($token)) {
        $GLOBALS['karvi_lang_return'] = app_path('/contract/' . $token);
    }
}

function render_lang_switcher(): void
{
    $current = current_locale();
    ?>
<div class="lang-switcher" role="group" aria-label="<?= e(__('lang_switch')) ?>">
    <a href="<?= e(lang_switch_url('en')) ?>" class="lang-option <?= $current === 'en' ? 'active' : '' ?>" title="<?= e(__('lang_en')) ?>">EN</a>
    <span class="lang-divider" aria-hidden="true"></span>
    <a href="<?= e(lang_switch_url('de')) ?>" class="lang-option <?= $current === 'de' ? 'active' : '' ?>" title="<?= e(__('lang_de')) ?>">DE</a>
</div>
    <?php
}

function i18n_js_strings(): array
{
    return [
        'copied' => __('copied'),
        'js_alert_upload' => __('js_alert_upload'),
        'js_alert_draw' => __('js_alert_draw'),
        'js_alert_fail' => __('js_alert_fail'),
        'js_alert_network' => __('js_alert_network'),
        'submit_signed' => __('submit_signed'),
        'submitting' => __('submitting'),
        'reg_next' => __('reg_next'),
        'reg_submit' => __('reg_submit'),
        'reg_registration_document' => __('reg_registration_document'),
        'reg_read_document' => __('reg_read_document'),
        'reg_owner_progress' => __('reg_owner_progress'),
        'reg_doc_required' => __('reg_doc_required'),
        'reg_consent_required' => __('reg_consent_required'),
        'reg_name_required' => __('reg_name_required'),
        'reg_document_email_invalid' => __('reg_document_email_invalid'),
        'reg_rotate_required' => __('reg_rotate_required'),
        'reg_pdf_loading' => __('reg_pdf_loading'),
        'reg_location_loading' => __('reg_location_loading'),
        'reg_location_saving' => __('reg_location_saving'),
        'reg_location_denied' => __('reg_location_denied'),
        'reg_location_timeout' => __('reg_location_timeout'),
        'reg_location_unavailable' => __('reg_location_unavailable'),
        'reg_location_insecure' => __('reg_location_insecure'),
        'reg_location_error' => __('reg_location_error'),
    ];
}

function render_i18n_script(): void
{
    ?>
<script>window.KARVI_I18N = <?= json_encode(i18n_js_strings(), JSON_UNESCAPED_UNICODE) ?>;</script>
    <?php
}
