<?php namespace App\Http\Controllers;

use App\Custom\SQLConnection;
use App\Custom\Misc;
use Request;
use Session;
use DB;

class Traducciones extends Controller  {

    public static $blade ='';

	public static function setBlade($vista){
		self::$blade = $vista;
		SQLConnection::obtenerTraducciones(self::$blade);
	}

    public static function get($value){
		//
		/* if ( empty($blade) ) {
			SQLConnection::obtenerTraducciones(Traducciones::$blade);
		} */
		// TRADUCCIONES ESTA VACIO
		$traducciones = Session::get('traduccion_dinamica');
		$clean_string = strtoupper(substr( preg_replace('/[^a-zA-Z0-9]/', '', $value) , 0, 500));
		//
		//dd($traducciones);
		if (isset($traducciones[$clean_string])) {
			return $traducciones[$clean_string];
		}
		else {	
			self::set($value, self::$blade);
			$traducciones[$clean_string] = $value;
			
			Session::put('traduccion_dinamica', $traducciones);
		}
		// 
		return $value;
	}

	public static function set($value,$blade){		
        if ($blade) {
			$app_id = isset(Session::get('webdata')['app_id']) ? Session::get('webdata')['app_id'] : env('APP_ID');
			$trad = SQLConnection::backendStoreProcedure('agregar_traduccion_dinamica', array($value,$blade,$app_id), 'select');
		}
	}

	public static function getStatic($value){
		$traducciones = Session::get('traducciones');
		$blade = '';
		// 
		foreach ($traducciones as $key => $trad) {
			$blade = $key;
		}
		// 
		if (isset($traducciones[$blade][$value])) {
			return $traducciones[$blade][$value];
		}
	}

	public static function traducciones() {
		$trad = self::traduccionesData();
		// 
        return view('/admin-traducciones/panel_traducciones')->with(compact('trad'));
	}

	public static function traduccionesData(){
		if (isset($_POST['plataforma_select'])){
			$app_id = Request::input('plataforma_select');
		} else {
			$app_id = isset(Session::get('webdata')['app_id']) ? Session::get('webdata')['app_id'] : env('APP_ID');
		}
		// dd($app_id);
		$trad = SQLConnection::backendStoreProcedure('traducciones_web', array('LOTEBYAPPID',$app_id), 'select'); // Está hardcodeado las traducciones de backendIV (99). Ese dato debería estar en la sesion, en los datos del webdata
		$aux_0 = [];
		// Corrige string lineas de string para no tener conflictos en el parseo a JSON
		foreach ($trad as $k => $t){
			$t->app_key = htmlspecialchars($t->app_key);
			$t->spa = htmlspecialchars($t->spa);
			$t->por = htmlspecialchars($t->por);
			$t->eng = htmlspecialchars($t->eng);
			//
			$t->app_key = str_replace(array("\n","\t","\r","\\"),'',$t->app_key);
            $t->spa = str_replace(array("\n","\t","\r","\\"),"",$t->spa);
            $t->por = str_replace(array("\n","\t","\r","\\"),"",$t->por);
            $t->eng = str_replace(array("\n","\t","\r","\\"),"",$t->eng);
			// 
            $t->app_key = str_replace(' <span class="text-danger">*</span>',' *',$t->app_key);
            $t->spa = str_replace(' <span class="text-danger">*</span>',' *',$t->spa);
            $t->por = str_replace(' <span class="text-danger">*</span>',' *',$t->por);
            $t->eng = str_replace(' <span class="text-danger">*</span>',' *',$t->eng);
            // Revisa que exista el atribut blade para poder mostrarlo
			if(isset($t->blade)){
				array_push($aux_0, $t);
			}
		}
		//
		return json_encode($aux_0);
	}

	public static function tablaTraducciones() {
		$app_id = !empty(Request::input('app_id')) ? Request::input('app_id') : null;
		$blade = Request::input('blade');
		$app_key = Request::input('app_key');
		$terminada 	= Request::input('terminada');
		$lang = 'terminada_'.Request::input('lang');
		// 
		$terminada_eng = 0;
		$terminada_por = 0;
		// 
		if($lang ==  'terminada_eng'){
			$terminada_eng = 1;
		}else if ($lang ==  'terminada_por'){
			$terminada_por = 1;
		}
		// 
		$lang = ($terminada == 1 ) ? 1 : 0;
		$trad = SQLConnection::backendStoreProcedure('traducciones_web', array('get',$app_id,null,null,null,null,null,null,$lang,null,$terminada_eng,$terminada_por), 'select');
		// 
		return view('/traducciones/tabla_traducciones')->with(compact(['trad', 'lang']));
	}

	public static function traduccionesTexto() {
		$app_id = Request::input('app_id');
		$blade = Request::input('blade');
		$app_key = Request::input('app_key');
		$lang = Request::input('lang');
		$id_traduccion = Request::input('id_traduccion');
		$iv = Request::input('iv');
		// 
		$texto = SQLConnection::backendStoreProcedure('traducciones_web', array('selectkey', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $id_traduccion), 'selectOne');
		// 
		if ($iv == 1) {
			return json_encode($texto);
		}
		// 
		return view('/traducciones/traducciones_texto')->with(compact(['lang', 'texto']));

	}

	public static function traduccionesTextoUpdate() {

		$app_id = Request::input('app_id');
		$blade = Request::input('blade');
		$app_key = Request::input('app_key');
		$txt_spa = Request::input('txt_spa');
		$txt_eng = Request::input('txt_eng');
		$txt_por = Request::input('txt_por');
		$listo_eng = Request::input('eng_finish');
		$listo_por = Request::input('por_finish');
		$id_traduccion = Request::input('id_trad');

		$spa = 0;
		$por = 0;
		$eng = 0;
		$cambiado = 0;

		// Busca las traducciones similares por el app_key para modificar por lote todos los textos similares, filtra y elimina traducciones que no tengan el mismo texto en español. También filtra si el texto similar ya fue traducido y lo saca del objeto a modificar.
		$trad_like = SQLConnection::backendStoreProcedure('traducciones_web', array('LOTEBYAPPKEY',$app_id,null,$app_key), 'select');
		// 
		foreach ($trad_like as $k => $t) {
			if ($t->spa != $txt_spa || ($t->terminada_eng == 1 && $t->terminada_por == 1) ) {
				unset($trad_like[$k]);
			}
			if ($id_traduccion == $t->id_traduccion){
				if ($t->eng != $txt_eng){
					$eng = 1;
				}
				if ($t->por != $txt_por){
					$por = 1;
				}
				if ($t->spa != $txt_spa){
					$spa = 1;
				}
				$temp = SQLConnection::backendStoreProcedure('traducciones_web', array('update-all', $app_id, $blade, $app_key, $txt_spa, $txt_por, $txt_eng, Session::get('usuario')->user_id,null, null, $listo_eng, $listo_por, $id_traduccion), 'selectOne');
				$cambiado = 1;
				// $trazabilidad = SQLConnection::backendStoreProcedure('insertar_trazabilidad', array($texto, $cliente, 'TRADUCCIONES','BACK', $contraparte,Session::get('usuario')->user_id), 'selectOne');
				unset($trad_like[$k]);
			}
		}
		
		// Recorre las traducciones similares y cambia los textos según las especificaciones del bloque anterior.
		if (!empty($trad_like)) {
			foreach ($trad_like as $k => $t) {
				if ( $eng != 0  && $t->terminada_eng != 1 || $por != 0 && $t->terminada_por != 1){
					$temp = SQLConnection::backendStoreProcedure('traducciones_web', array('update-all', $t->app_id, $t->blade, $t->app_key, $t->spa, ($por != 0 && $t->terminada_por != 1) ? $txt_por : $t->por, ($eng != 0 && $t->terminada_eng != 1) ? $txt_eng : $t->eng, Session::get('usuario')->user_id, NULL, NULL, $t->terminada_eng, $t->terminada_por, $t->id_traduccion), 'selectOne');
					// $trazabilidad = SQLConnection::backendStoreProcedure('insertar_trazabilidad', array($texto, $cliente, 'TRADUCCIONES','BACK', $contraparte,Session::get('usuario')->user_id), 'selectOne');
				}
			}
		}

		if ( $cambiado == 1) {
			return 1;
		} else {
			return 0;
		}
	}

	public static function traduccionesTextos() {

		$app_id = Request::input('app_id');

		$blade = Request::input('blade');

		$app_key = Request::input('app_key');

		$id_traduccion = Request::input('id_traduccion');



		//$textos = SQLConnection::backendStoreProcedure('traducciones_web', array('get', $app_id, $blade, $app_key), 'selectOne');

		$textos = SQLConnection::backendStoreProcedure('traducciones_web', array('selectkey', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $id_traduccion), 'selectOne');

		return view('/traducciones/traducciones_textos')->with(compact(['textos']));

	}

	public static function traduccionesTextosUpdate() {

		$app_id = Request::input('app_id');

		$blade = Request::input('blade');

		$app_key = Request::input('app_key');

		$id_traduccion = Request::input('id_traduccion');

		$spa = Request::input('spa');

		$por = Request::input('por');

		$eng = Request::input('eng');

		$terminada_eng = !empty(Request::input('terminada_eng') ) ? 1 : 0;

		$terminada_por = !empty(Request::input('terminada_por') ) ? 1 : 0;



		$temp = SQLConnection::backendStoreProcedure('traducciones_web', array('update-all', $app_id, $blade, $app_key,$spa, $por, $eng, Session::get('usuario')->user_id,null,null,$terminada_eng,$terminada_por,$id_traduccion), 'selectOne');



		return '';

	}

	public static function traduccionesGet($app_id=null, $blade=null, $app_key=null) {

		return ( SQLConnection::backendStoreProcedure('traducciones_web', array('get', $app_id, $blade, $app_key), 'selectOne') );

	}

	public static function traduccionesVarBlade($valor,$vista){
		// $vista = app('view')->getEngineResolver()->resolve('blade')->getCompiler()->getPath();
		// dd(app('view')->getEngineResolver()->resolve('blade')->getCompiler());
		// $vista = (string)substr($vista, strrpos($vista, '/') + 1);
		$app_id = isset(Session::get('webdata')['app_id']) ?? env('APP_ID');
		list($key, $value) = [$valor,$valor];
		

		//esto es lo que finalmente va a mostrar el template.
		// $vista = array_keys(Session::get('traducciones'))[0];
		$traducciones = [];
		$existe = 0;
		foreach(Session::get('traducciones')[$vista] as $key => $ingresada){
			if($key == $valor || Session::get('traducciones')[$vista][$key]->spa == $valor){
				$existe = 1;
				break;
			}
		}
        // dd($existe);
		// if(! isset(Session::get('traducciones')[$vista]) ) {
		if(! $existe ) {
            // dd('entre');
			$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)] = (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)));
		//
		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');
			$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)];
            // dd($value,$vista);
		}
		//
		
		// dd(SQLConnection::backendStoreProcedure('traducciones_web', array('get', env('IV_APP_ID'), $vista, NULL, NULL), 'select'));
		if ( !is_object($value) ){
			return $value;
		} else {
			if ( isset(Session::get('usuario')->codigo_idioma) && Session::get('usuario')->codigo_idioma == 'eng' ) {
				return $value->eng; 
			} elseif ( isset(Session::get('usuario')->codigo_idioma) && Session::get('usuario')->codigo_idioma == 'por' ) {
				return $value->por; 
			} else{
				return $value->spa;
			}

		}
	}

}


