<?php
/**
 * Language Helper
 * Localization handler (Default: Thai)
 */

class Language {
    private static ?string $currentLocale = null;
    private static array $translations = [];

    private const SUPPORTED_LOCALES = ['th', 'en'];
    private const DEFAULT_LOCALE = 'th';

    public static function init(): void {
        if (self::$currentLocale !== null) {
            return;
        }

        $config = [];
        if (file_exists(__DIR__ . '/../../config/app.php')) {
            $config = require __DIR__ . '/../../config/app.php';
        }
        $supported = $config['supported_locales'] ?? self::SUPPORTED_LOCALES;
        $default = $config['default_locale'] ?? self::DEFAULT_LOCALE;

        // Check query param (e.g. ?lang=en)
        if (isset($_GET['lang']) && is_string($_GET['lang']) && in_array($_GET['lang'], $supported, true)) {
            $_SESSION['locale'] = $_GET['lang'];
            if (!headers_sent()) {
                setcookie('cargoo_lang', $_GET['lang'], [
                    'expires'  => time() + (86400 * 365),
                    'path'     => '/',
                    'httponly' => true,
                    'samesite' => 'Lax'
                ]);
            }
        }

        // Check session or cookie
        if (isset($_SESSION['locale']) && is_string($_SESSION['locale']) && in_array($_SESSION['locale'], $supported, true)) {
            self::$currentLocale = $_SESSION['locale'];
        } elseif (isset($_COOKIE['cargoo_lang']) && is_string($_COOKIE['cargoo_lang']) && in_array($_COOKIE['cargoo_lang'], $supported, true)) {
            self::$currentLocale = $_COOKIE['cargoo_lang'];
        } else {
            self::$currentLocale = $default;
        }

        self::loadTranslations(self::$currentLocale);
    }

    public static function getLocale(): string {
        self::init();
        return self::$currentLocale ?? self::DEFAULT_LOCALE;
    }

    public static function setLocale(string $locale): void {
        $config = [];
        if (file_exists(__DIR__ . '/../../config/app.php')) {
            $config = require __DIR__ . '/../../config/app.php';
        }
        $supported = $config['supported_locales'] ?? self::SUPPORTED_LOCALES;
        $default = $config['default_locale'] ?? self::DEFAULT_LOCALE;

        if (!in_array($locale, $supported, true)) {
            $locale = $default;
        }

        self::$currentLocale = $locale;
        $_SESSION['locale'] = $locale;
        if (!headers_sent()) {
            setcookie('cargoo_lang', $locale, [
                'expires'  => time() + (86400 * 365),
                'path'     => '/',
                'httponly' => true,
                'samesite' => 'Lax'
            ]);
        }

        self::loadTranslations($locale);
    }

    /**
     * Load translation file safely using static whitelist mapping (Prevent LFI & Path Traversal)
     */
    private static function loadTranslations(string $locale): void {
        $localeFiles = [
            'th' => __DIR__ . '/../../lang/th.php',
            'en' => __DIR__ . '/../../lang/en.php',
        ];

        $filePath = $localeFiles[$locale] ?? $localeFiles[self::DEFAULT_LOCALE] ?? null;
        if ($filePath !== null && file_exists($filePath)) {
            self::$translations = require $filePath;
        } else {
            self::$translations = [];
        }
    }

    public static function trans(string $key, array $params = []): string {
        self::init();
        $text = self::$translations[$key] ?? $key;
        foreach ($params as $k => $v) {
            $text = str_replace(':' . $k, (string)$v, $text);
        }
        return $text;
    }

    /**
     * Generate safe URL for switching language with current URI preservation
     */
    public static function switchUrl(string $locale): string {
        $targetLocale = in_array($locale, self::SUPPORTED_LOCALES, true) ? $locale : self::DEFAULT_LOCALE;
        
        $currentUri = $_SERVER['REQUEST_URI'] ?? '';
        if ($currentUri !== '') {
            $parsed = parse_url($currentUri);
            $path = $parsed['path'] ?? '';
            // If current URI is a language switch action itself, reset return URI
            if (preg_match('#/(language|set-language|lang)(/|$)#i', $path)) {
                $currentUri = '';
            }
        }

        $switchUrl = url('/language/' . urlencode($targetLocale));
        if ($currentUri !== '') {
            $switchUrl .= '?return=' . urlencode($currentUri);
        }

        return $switchUrl;
    }
}

/**
 * Global translation shortcut
 */
function __(string $key, array $params = []): string {
    return Language::trans($key, $params);
}
