<?php

 class util_languages {

    private static $languages_model;
    private static $language ;
    private static $cache = [];

    public static function setModel($model) {
        self::$languages_model = $model;
        self::buildCache();
    }    

    public static function setLanguage($language) {
        self::$language = $language;
    }    

    private static function buildCache() {

        if (!self::$languages_model) {
            throw new Exception("languages_model no asignado");
        }

        // Traer todos los tokens de una sola vez
        $rows = self::$languages_model->selectAll([], false, false);

        self::$cache = [];
        foreach ($rows as $row) {
            $token = trim(strtolower($row['token']));
            // Usamos el valor de "token" como clave
            self::$cache[ $token ] = [
                'es' => $row['es'],
                'en' => $row['en']
            ];
        }
    }


    public static function translate($token) {

        $token = trim(strtolower($token));

        if (empty(self::$cache)) {
            // Por si acaso aún no se construyó la caché
        //                    echo "build Cache";

            self::buildCache();
        }

        if (!isset(self::$cache[$token])) {
            return $token; // Si no existe la traducción, devolvemos el token
        }

        if (self::$language === 'es') {
            return self::$cache[$token]['es'];
        } else if (self::$language === 'en') {
            return self::$cache[$token]['en'];
        }

        return "error";
    }

    public static function translate_bd($token)
    {
        if (!self::$languages_model) {
            throw new Exception("languages_model no asignado");
        }

        $result = self::$languages_model->get_token($token);
//        print_r($result);

        if ( empty($result))  {
           return $token;
        }

        if (self::$language == 'es') { 
            return $result['es'];
        }
        else if (self::$language == 'en') { 
            return $result['en'];
        }

        return "error";
    }

}

?>