<?php
namespace a_modules\common\repository;

use Illuminate\Database\Capsule\Manager as Capsule;

class TT
{
    public $locale;
    public $lngCache;
    public $lngModule;
    public $lngFile;
    
    /**
     * TT constructor.
     */
    public function __construct()
    {
        global $locale, $lngCache, $lngModule, $lngFile;

    }

    public static function locales($string, $code = null, $module = null, $file = null) {
        global $locale, $lngCache, $lngModule, $lngFile;
        $locale_code = $locale;

        if($code != null && $code != "") {
            $locale_code = $code;
        }

        /*$lngModule = $module != null ? $module : static::$lngModule;
        $lngFile = $file != null ? $file : ($module != null ? $module : $lngFile);*/

        $lng_module_file = $lngModule . $lngFile;

        $translation = $string;
        $string = trim(stripslashes($string));

        $cache_index = md5($string . $lng_module_file);
        //$lngCache[$cache_index]['lang_code'] = $locale_code;
        //print_r($lngCache[$cache_index]);
        if(isset($lngCache[$cache_index])) {
            if(isset($lngCache[$cache_index][$locale_code])) {
                $translation = $lngCache[$cache_index][$locale_code];
                return $translation;
            }
            else {
                $translation = $lngCache[$cache_index]['en'];
                return $translation;
            }
        }

        // Following code is reached if we did not get the string from cache

        $r = Capsule::table('locales')
            ->where('tags', $string)
            ->where('lng_module', $lngModule)
            ->where('lng_file', $lngFile)
            ->where('active', 1)
            ->first();

        if($r) {
            $row = collect($r)->toArray();
            $trans = unserialize(base64_decode($row['locale']));
            if(!isset($locale) || $locale == "") $locale = "en";

            if($locale_code != "en") {
                if(isset($trans[$locale_code])) {
                    $translation = $trans[$locale_code];
                }
                else {
                    if(isset($trans['en'])) {
                        $translation = $trans['en'];
                    }
                    else {
                        $tarr = array('en' => $string);
                        $translation = $string;
                    }
                }
            }
            else {
                if(isset($trans['en'])) {
                    $translation = $trans['en'];
                }
                else {
                    $tarr = array('en' => $string);
                    $translation = $string;
                }
            }
        }
        else {
            $tarr = array('en' => $string);
            $translation = $string;
        }

        if(isset($tarr)) {
            $r = Capsule::table('locales')
                ->where('tags', $string)
                ->where('active', 1)
                ->where(function($query){
                    return $query->where('lng_module', '=', '')
                        ->orWhere('lng_module', 'INDEX_PAGE');
                })
                ->first();

            if($r) {
                $row = collect($r)->toArray();

                $tr_id = $row['id'];
                $trans = unserialize(base64_decode($row['locale']));

                $have_langs = "#en#";
                if(count($trans) > 1) {
                    $have_langs = "";
                    $trans_keys = array_keys($trans);
                    foreach ($trans_keys as $i=>$tr_code) {
                        $have_langs .= "#$tr_code#";
                    }
                }
                if(isset($trans[$locale_code])) {
                    $translation = $trans[$locale_code];
                }

                $updated = Capsule::table('locales')
                    ->where('id', $tr_id)
                    ->update([
                        'have_langs' => $have_langs,
                        'lng_module' => $lngModule,
                        'lng_file' => $lngFile
                    ]);
            }
            else {
                $t_add = base64_encode(serialize($tarr));

                try {
                    $inserted = Capsule::table('locales')
                        ->insert([
                            'tags' => $string,
                            'locale' => $t_add,
                            'have_langs' => '#en#',
                            'active' => 1,
                            'lng_module' => $lngModule,
                            'lng_file' => $lngFile
                        ]);
                }
                catch (\Exception $e) {
                    dd($lngModule, $lngFile, $e->getMessage(), $e->getTraceAsString());
                }
            }

        }

        return stripslashes($translation);

    }

    public static function t($string, $args = 0) {
        $string = static::locales($string);
        if (!$args) {
            return $string;
        }
        else {
            // Transform arguments before inserting them
            if($args && count($args)) {
                foreach ($args as $key=>$val) {
                    $args[$key] = '"'.htmlentities($val). '"';
                }
                $params = implode(",", $args);
                @eval("\$ret_parsed = sprintf(\"".$string."\", ".$params.");");
                if(isset($ret_parsed)) 	return html_entity_decode($ret_parsed);
            }
        }

        return $string;
    }

    public static function t_($string, $code = null, $args=0) {

        $string = static::locales($string, $code);
        if (!$args) {
            return $string;
        }
        else {
            // Transform arguments before inserting them
            if($args && count($args)) {
                foreach ($args as $key=>$val) {
                    $args[$key] = '"'.htmlentities($val). '"';
                }
                $params = implode(",", $args);
                @eval("\$ret_parsed = sprintf(\"".$string."\", ".$params.");");
                if(isset($ret_parsed)) 	return html_entity_decode($ret_parsed);
            }
        }

        return $string;
    }

    public static function tt($string, $module, $file=null) {
        global $locale;
        if($file == null) $file = $module;
        if (function_exists('locales')) {
            $string = static::locales($string, null, $module, $file);
        }
        return $string;
    }

    public static function t_a($string, $args = null) {
        $string = static::locales($string, 'en');
        if ($args == null) {
            return $string;
        }
        else {
            // Transform arguments before inserting them
            if(!is_array($args)) {
                $params = implode(",", $args);
                @eval("\$ret_parsed = sprintf(\"".$string."\", ".$params.");");
                if(isset($ret_parsed)) 	return html_entity_decode($ret_parsed);

            }
            elseif(is_array($args) && count($args) > 0) {
                $names = array();
                foreach ($args as $key=>$val) {
                    $args[$key] = htmlentities($val);
                    $names [] = '{{' . $key . '}}';
                }

                return str_ireplace($names, $args, $string);
            }
        }

        return $string;
    }
}