<?php
namespace EasyChat\Library;

class I18n {
    private const SUPPORTED = ['ru', 'en', 'kk', 'uz', 'uk', 'es'];

    private static $cache = [];

    public static function supportedLocales() {
        return self::SUPPORTED;
    }

    public static function normalizeLocale($locale) {
        $locale = strtolower(str_replace('_', '-', trim((string)$locale)));
        if ($locale === '') {
            return 'ru';
        }
        $short = explode('-', $locale)[0];
        return in_array($short, self::SUPPORTED, true) ? $short : 'ru';
    }

    public static function resolveFromAcceptLanguage($header) {
        foreach (explode(',', (string)$header) as $part) {
            $locale = trim(explode(';', $part)[0]);
            $normalized = self::normalizeLocale($locale);
            if ($normalized !== 'ru' || stripos($locale, 'ru') === 0) {
                return $normalized;
            }
        }
        return 'ru';
    }

    public static function translate($key, array $params = [], $locale = 'ru') {
        $locale = self::normalizeLocale($locale);
        $value = self::load($locale)[$key] ?? self::load('ru')[$key] ?? $key;

        foreach ($params as $name => $param) {
            $value = str_replace('{' . $name . '}', (string)$param, $value);
        }

        return $value;
    }

    public static function dictionary($locale, array $keys = []) {
        $locale = self::normalizeLocale($locale);
        $ru = self::load('ru');
        $selected = [];
        foreach ($keys ?: array_keys($ru) as $key) {
            $selected[$key] = self::translate($key, [], $locale);
        }
        return $selected;
    }

    private static function load($locale) {
        $locale = self::normalizeLocale($locale);
        if (isset(self::$cache[$locale])) {
            return self::$cache[$locale];
        }

        $data = self::includeDictionary($locale);
        self::$cache[$locale] = is_array($data) ? $data : [];
        return self::$cache[$locale];
    }

    private static function includeDictionary($locale) {
        switch (self::normalizeLocale($locale)) {
            case 'en':
                return include (defined('SITE_PATH') ? SITE_PATH : dirname(__DIR__)) . DS . 'lang' . DS . 'en.php';
            case 'kk':
                return include (defined('SITE_PATH') ? SITE_PATH : dirname(__DIR__)) . DS . 'lang' . DS . 'kk.php';
            case 'uk':
                return include (defined('SITE_PATH') ? SITE_PATH : dirname(__DIR__)) . DS . 'lang' . DS . 'uk.php';
            case 'uz':
                return include (defined('SITE_PATH') ? SITE_PATH : dirname(__DIR__)) . DS . 'lang' . DS . 'uz.php';
            case 'es':
                return include (defined('SITE_PATH') ? SITE_PATH : dirname(__DIR__)) . DS . 'lang' . DS . 'es.php';
            case 'ru':
            default:
                return include (defined('SITE_PATH') ? SITE_PATH : dirname(__DIR__)) . DS . 'lang' . DS . 'ru.php';
        }
    }
}
