<?php

namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use App\Custom\SQLConnection;
use Session;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        /* 
        función traducir, utilizar la key para ver si está seteada en la sesión y sino grabarla en la base de datos y luego agregarlo
        a la sesión.
        falta identificar el idioma para ir a buscar la key.
        */
        /*\Blade::directive('traducir', function ($array) {
            //\Artisan::call('view:clear');
            $vista = app('view')->getEngineResolver()->resolve('blade')->getCompiler()->getPath();
            $vista = (string)substr($vista, strrpos($vista, '/') + 1);
            list($key, $value) = explode(',', $array);
            //esto es lo que finalmente va a mostrar el template.
            $vista = substr($vista, 0, strpos($vista, '.'));
            //print_r($vista);
            $traducciones = [];
            if(! isset(Session::get('traducciones')[$vista]) ) {
                $trad = SQLConnection::backendStoreProcedure('traducciones_web', array('get', env('APP_ID'), $vista, NULL, NULL), 'select');
                $idioma = (isset(Session::get('usuario')->codigo_idioma)) ? Session::get('usuario')->codigo_idioma : 'spa' ;
                //
                foreach ($trad as $n => $expr) {
                    $traducciones[$vista][strtoupper($expr->app_key)] = $expr->{$idioma};
                }
                Session::put('traducciones', $traducciones);
            }
            //
            $key = trim(str_replace("'", '', str_replace('"', '', $key)));
            //
            if(! isset(Session::get('traducciones')[$vista][strtoupper($key)]) )  {
                $value = trim(str_replace("'", '', str_replace('"', '', $value)));
                $temp = SQLConnection::backendStoreProcedure('traducciones_web', array('insert', env('APP_ID'), $vista, $key, $value), 'selectOne');
                $traducciones = [];
                $traducciones[$vista][$key] = $value;
                Session::put('traducciones', $traducciones);
            } else {
                $value = Session::get('traducciones')[$vista][strtoupper($key)];
            }
            //
            return "<?php echo '$value'; ?>";
        });*/
        //
        $app_id = Session::get('webdata')['app_id'] ?? env('APP_ID');
        \Blade::directive('traducir', function ($array) {
            //\Artisan::call('view:clear');
            $vista = app('view')->getEngineResolver()->resolve('blade')->getCompiler()->getPath();
            $vista = (string)substr($vista, strrpos($vista, '/') + 1);
            $lista_parametros = explode(',', $array);
            if ( count($lista_parametros) == 1 ){
                /*return "<?php echo('El array no contiene la cantidad necesaria de parámetros'); echo('vista: " . $vista . "'); echo('texto: " . $lista_parametros[0] . "'); ?>";*/
                return "<?php echo('error @traducir: " . $lista_parametros[0] . "'); ?>";
            }
            list($key, $value) = $lista_parametros;
            //list($key, $value) = explode(',', $array);
            //esto es lo que finalmente va a mostrar el template.
            $vista = substr($vista, 0, strpos($vista, '.'));
            //print_r($vista);
            $traducciones = [];
            if(! isset(Session::get('traducciones')[$vista]) ) {
                $trad = SQLConnection::backendStoreProcedure('traducciones_web', array('get', env('APP_ID'), $vista, NULL, NULL), 'select');
                // $trad = SQLConnection::backendStoreProcedure('traducciones_web', array('get', $app_id, $vista, NULL, NULL), 'select');
                $idioma = ((isset(Session::get('usuario')->codigo_idioma)) ? Session::get('usuario')->codigo_idioma : ((!is_null(Session::get('idioma'))) ? Session::get('idioma') : 'spa')) ;
		// solo para las llamadas de api
                if ( !is_null(Session::get('codigo_idioma_api')) ){
                    $idioma = Session::get('codigo_idioma_api');
                }
                //
                foreach ($trad as $n => $expr) {
                    $traducciones[$vista][strtoupper($expr->app_key)] = (object) ['spa' => trim(str_replace("'", '', str_replace('"', '', $expr->spa)))  ,'por' => trim(str_replace("'", '', str_replace('"', '', $expr->por))),'eng' => trim(str_replace("'", '', str_replace('"', '', $expr->eng)))];
                    
                }
                Session::put('traducciones', $traducciones);
            }
            //
            $key = trim(str_replace("'", '', str_replace('"', '', $key)));
            // dd(Session::get('traducciones')[$vista][strtoupper($key)]);
            //
            if(! isset(Session::get('traducciones')[$vista][strtoupper($key)]) )  {
                // ENTRA ACA CUANDO PARA ALMACENAR LA CLAVE DE LAS TRADUCCIONES
                $value = trim(str_replace("'", '', str_replace('"', '', $value)));
                $temp = SQLConnection::backendStoreProcedure('traducciones_web', array('insert', env('APP_ID'), $vista, $key, $value), 'selectOne');
                // $temp = SQLConnection::backendStoreProcedure('traducciones_web', array('insert', $app_id, $vista, $key, $value), 'selectOne');
                $traducciones = [];
                $traducciones[$vista][$key] = $value;
                Session::put('traducciones', $traducciones);
                $value = (object) ['spa' => $value, 'por' => $value, 'eng' => $value];
            } else {
                // ENTRA ACA CUANDO TIENE ALMACENADA LA TRADUCCION
                $value = Session::get('traducciones')[$vista][strtoupper($key)];
            }
            //
            return "<?php if( ( isset(Session::get('usuario')->codigo_idioma) && Session::get('usuario')->codigo_idioma == 'spa') || ( (!isset(Session::get('usuario')->codigo_idioma)) && Session::get('idioma') == 'spa' ) ): echo('".$value->spa."'); elseif( (isset(Session::get('usuario')->codigo_idioma) && Session::get('usuario')->codigo_idioma == 'por') || ((!isset(Session::get('usuario')->codigo_idioma)) && Session::get('idioma') == 'por' ) ): echo('".$value->por."'); else: echo('".$value->eng."'); endif; ?>";
        });
        //
        /*Blade::directive('traducirVar', function ($keyvalue) {
            $vista = app('view')->getEngineResolver()->resolve('blade')->getCompiler()->getPath();
            $vista = (string)substr($vista, strrpos($vista, '/') + 1);
            $vista = substr($vista, 0, strpos($vista, '.'));
            //
            list($key, $value) = explode(',', $keyvalue);
            $traducciones = [];
            if(! isset(Session::get('traducciones')[$vista]) ) {
                $trad = SQLConnection::backendStoreProcedure('traducciones_web', array('get', env('APP_ID'), $vista, NULL, NULL), 'select');
                $idioma = (isset(Session::get('usuario')->codigo_idioma)) ? Session::get('usuario')->codigo_idioma : 'spa' ;
                //
                foreach ($trad as $n => $expr) {
                    $traducciones[$vista][$expr->app_key] = $expr->{$idioma};
                }         
                Session::put('traducciones', $traducciones);
            }
            //var_dump($key);
            if(! isset(Session::get('traducciones')[$vista][$key]) )  {
                $value = trim(str_replace("'", '', str_replace('"', '', $value)));

                $temp = SQLConnection::backendStoreProcedure('traducciones_web', array('insert', env('APP_ID'), $vista, $key, $value), 'selectOne');
                $traducciones = [];
                $traducciones[$vista][$key] =$value;
                
                Session::put('traducciones', $traducciones);
            }
            //
            return  "<?php echo $value; ?>";
        });*/
        //
        Blade::directive('traducirVar', function ($keyvalue) {
            $vista = app('view')->getEngineResolver()->resolve('blade')->getCompiler()->getPath();
            $vista = (string)substr($vista, strrpos($vista, '/') + 1);
            $vista = substr($vista, 0, strpos($vista, '.'));
            //
            list($key, $value) = explode(',', $keyvalue);
            $traducciones = [];
            if(! isset(Session::get('traducciones')[$vista]) ) {
                $trad = SQLConnection::backendStoreProcedure('traducciones_web', array('get', env('APP_ID'), $vista, NULL, NULL), 'select');
                // $trad = SQLConnection::backendStoreProcedure('traducciones_web', array('get', $app_id, $vista, NULL, NULL), 'select');
                $idioma = (isset(Session::get('usuario')->codigo_idioma)) ? Session::get('usuario')->codigo_idioma : 'spa' ;
                //
                foreach ($trad as $n => $expr) {
                    $traducciones[$vista][strtoupper($expr->app_key)] = (object) ['spa' => trim(str_replace("'", '', str_replace('"', '', $expr->spa)))  ,'por' => trim(str_replace("'", '', str_replace('"', '', $expr->por))),'eng' => trim(str_replace("'", '', str_replace('"', '', $expr->eng)))];
                }         
                Session::put('traducciones', $traducciones);
            }
            //
            if(! isset(Session::get('traducciones')[$vista][$key]) )  {
                $value = trim(str_replace("'", '', str_replace('"', '', $value)));
                $temp = SQLConnection::backendStoreProcedure('traducciones_web', array('insert', env('APP_ID'), $vista, $key, $value), 'selectOne');
                // $temp = SQLConnection::backendStoreProcedure('traducciones_web', array('insert', $app_id, $vista, $key, $value), 'selectOne');
                $traducciones = [];
                $traducciones[$vista][$key] =$value;
                Session::put('traducciones', $traducciones);
                $value = (object) ['spa' => $value, 'por' => $value, 'eng' => $value];
            }
            //
            return "<?php if( isset(Session::get('usuario')->codigo_idioma) && Session::get('usuario')->codigo_idioma == 'eng' ): echo('".$value->eng."'); elseif( isset(Session::get('usuario')->codigo_idioma) && Session::get('usuario')->codigo_idioma == 'por' ): echo('".$value->por."'); else: echo('".$value->spa."'); endif; ?>";
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

   

}
