<?php
namespace App\Core;

use App\Core\Database;

class I18n
{
    private static array $cache = [];

    public static function supported(): array
    {
        return ['ar', 'en'];
    }

    public static function current(): string
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        $lang = (string)($_SESSION['lang'] ?? $_COOKIE['easychair_lang'] ?? 'ar');

        if (!in_array($lang, self::supported(), true)) {
            $lang = 'ar';
        }

        return $lang;
    }

    public static function set(string $lang): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (!in_array($lang, self::supported(), true)) {
            $lang = 'ar';
        }

        $_SESSION['lang'] = $lang;
        setcookie('easychair_lang', $lang, time() + 60 * 60 * 24 * 365, '/easychair');
    }

    public static function dir(?string $lang = null): string
    {
        $lang = $lang ?: self::current();
        return $lang === 'ar' ? 'rtl' : 'ltr';
    }

    public static function alignStart(?string $lang = null): string
    {
        return self::dir($lang) === 'rtl' ? 'right' : 'left';
    }

    public static function alignEnd(?string $lang = null): string
    {
        return self::dir($lang) === 'rtl' ? 'left' : 'right';
    }

    public static function all(): array
    {
        $lang = self::current();

        if (isset(self::$cache[$lang])) {
            return self::$cache[$lang];
        }

        try {
            $db = Database::getInstance();
            $stmt = $db->query("
                SELECT translation_key, text_en, text_ar
                FROM dictionary_translations
                WHERE is_active=1
            ");

            $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            $map = [];

            foreach ($rows as $r) {
                $key = (string)$r['translation_key'];
                $value = $lang === 'ar'
                    ? (string)($r['text_ar'] ?: $r['text_en'] ?: $key)
                    : (string)($r['text_en'] ?: $r['text_ar'] ?: $key);

                $map[$key] = $value;
            }

            self::$cache[$lang] = $map;
            return $map;
        } catch (\Throwable $e) {
            return [];
        }
    }

    public static function t(string $key, ?string $fallback = null, array $replace = []): string
    {
        $dict = self::all();
        $text = $dict[$key] ?? $fallback ?? $key;

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

        return $text;
    }
}
