<?php
declare(strict_types=1);

function display_mode_options(): array
{
    return array(
        'app' => 'แอป',
        'web' => 'เว็บ',
    );
}

function normalize_display_mode(string $displayMode): string
{
    return array_key_exists($displayMode, display_mode_options()) ? $displayMode : 'web';
}

function current_display_mode(): string
{
    $displayMode = (string) ($_SESSION['display_mode'] ?? $_COOKIE['ccw_display_mode'] ?? 'web');

    return normalize_display_mode($displayMode);
}

function remember_display_mode(string $displayMode): string
{
    $displayMode = normalize_display_mode($displayMode);
    $_SESSION['display_mode'] = $displayMode;

    setcookie('ccw_display_mode', $displayMode, array(
        'expires' => time() + 31536000,
        'path' => '/',
        'samesite' => 'Lax',
    ));

    return $displayMode;
}

function language_options(): array
{
    return array(
        'th' => 'TH',
        'en' => 'EN',
    );
}

function normalize_language(string $language): string
{
    return array_key_exists($language, language_options()) ? $language : 'th';
}

function current_language(): string
{
    $language = (string) ($_SESSION['language'] ?? $_COOKIE['ccw_language'] ?? 'th');

    return normalize_language($language);
}

function current_language_html_code(): string
{
    return current_language() === 'en' ? 'en' : 'th';
}

function localized_text_value(string $th, string $en, ?string $language = null): string
{
    $language = $language !== null ? normalize_language($language) : current_language();

    return $language === 'en' ? $en : $th;
}

function localized_flash_message(string $th, string $en, array $replacements = array()): array
{
    return array(
        'th' => $th,
        'en' => $en,
        'replacements' => $replacements,
    );
}

function resolve_localized_flash_message(string|array $message, ?string $language = null): string
{
    if (!is_array($message) || !isset($message['th'], $message['en'])) {
        return (string) $message;
    }

    $template = localized_text_value((string) $message['th'], (string) $message['en'], $language);
    $replacePairs = array();

    foreach ((array) ($message['replacements'] ?? array()) as $key => $value) {
        if (is_array($value)) {
            continue;
        }

        $replacePairs['{' . (string) $key . '}'] = (string) $value;
    }

    return $replacePairs !== array() ? strtr($template, $replacePairs) : $template;
}

function remember_language(string $language): string
{
    $language = normalize_language($language);
    $_SESSION['language'] = $language;

    setcookie('ccw_language', $language, array(
        'expires' => time() + 31536000,
        'path' => '/',
        'samesite' => 'Lax',
    ));

    return $language;
}
