<?php
declare(strict_types=1);

/**
 * Interface language. English and Hebrew, switched per session,
 * with the page direction following the choice.
 */
final class Lang
{
    private static array $strings = [];
    private static string $code = 'en';

    public static function boot(): void
    {
        if (isset($_GET['lang']) && in_array($_GET['lang'], ['en', 'he'], true)) {
            $_SESSION['lang'] = $_GET['lang'];
        }

        self::$code = $_SESSION['lang'] ?? DEFAULT_LANG;
        if (!in_array(self::$code, ['en', 'he'], true)) {
            self::$code = 'en';
        }

        $file = BASE_DIR . '/lang/' . self::$code . '.php';
        self::$strings = is_file($file) ? require $file : [];
    }

    public static function code(): string
    {
        return self::$code;
    }

    public static function dir(): string
    {
        return self::$code === 'he' ? 'rtl' : 'ltr';
    }

    public static function isRtl(): bool
    {
        return self::dir() === 'rtl';
    }

    /** Translate. Missing keys fall back to the key itself, so nothing renders blank. */
    public static function get(string $key, array $replace = []): string
    {
        $text = self::$strings[$key] ?? $key;
        foreach ($replace as $k => $v) {
            $text = str_replace(':' . $k, (string) $v, $text);
        }
        return $text;
    }
}

/** Shorthand used throughout the views. */
function t(string $key, array $replace = []): string
{
    return Lang::get($key, $replace);
}
