<?php namespace App\Http\Controllers;

use App\Custom\SQLConnection; 
use App\Custom\Misc;
use App\Custom\Mailer;
use Request;
use Session;
use DateTime;
use Illuminate\Support\Facades\Input;
use DB;
use stdClass;

class PadronController extends Controller{
    //----
    public static function BusquedaPadron() {
		$data = [];
		$sin_tabla = Request::input('sin_tabla') ?? null;
		//----
		$search = !empty(Request::input('input_autocomplete')) ? Request::input('input_autocomplete') : NULL;
		if (null != $search) {
			$data = SQLConnection::busquedaPadronAutocomplete($search, true);
		}
		// dd($data);
		//----
		if ($sin_tabla){
			return json_encode($data);
		}
		$vista = \View::make('/led/led_contrapartes_tabla_busqueda')->with(compact(['data']))->render();
        return json_encode( array('view' => $vista) );
	}
    //----
    public static function IdentificadorPais(){
		$cc = Request::input('country_code');
		$tipo_persona = empty(Request::input('tipo_persona')) ? 'T' : Request::input('tipo_persona');
		$ident = Misc::identificadoresPais($cc,$tipo_persona);
		return json_encode($ident);
		// return Response::JSON($ident);
	}
    //-----
    public static function BusquedaPadronExtranjero(){
		//---
		$expReg_cuit = '/^[A-Za-z0-9ñÑ ]+$/';
		$expReg_nombre = '/^[A-Za-zñÑ ]+$/';
		$expReg_nombre2 = '/^[\s]+$/';
		//---
		$sin_tabla = Request::input('sin_tabla') ?? null;
		//---
		$cliente = Session::get('usuario')->cliente['client_id'];
		$pais = Request::input('pais') != '---' ? Request::input('pais') : '';
		$identificacion = empty(Request::input('tipo_identificacion')) ? '' : Request::input('tipo_identificacion');
		$numero = Request::input('identificacion');
		$nombre = Request::input('razon_social');
		$persona = Request::input('tipo_persona') != '---' ? Request::input('tipo_persona') : '';
		$sexo = Request::input('sexo') != '---' ? Request::input('sexo') : '';
		//-----
		//echo(var_dump($pais,$identificacion,$numero,$nombre,$persona,$sexo));die();
		//----- EN CASO DE TENER TODOS LOS DATOS COMPLETOS SE DA DE ALTA EN EL PADRON
		if ( $pais != 'AR' && empty($identificacion) == false  and ($sexo == 'F' or $sexo == 'M') and ($persona == 'F' or $persona == 'J') and preg_match($expReg_cuit,$numero) and preg_match($expReg_nombre,$nombre) ){
			$data[0] = trim($identificacion);
			$data[1] = trim($numero);
			$data[2] = trim($nombre);
			$data[3] = trim($persona);
			$data[4] = trim($sexo);
			$data[5] = 1;
			$data[6] = 1;
			//-----
			$respuesta = SQLConnection::backendStoreProcedure('backend_insertar_padron',$data);
			$data = $respuesta;
		}
		//------ EN CASO DE NO TENER TODOS LOS DATOS COMPLETOS SE BUSCA EN EL PADRON
		elseif ( preg_match($expReg_cuit,$numero) or ( preg_match($expReg_nombre,$nombre) and preg_match($expReg_nombre2,$nombre) == 0 ) ){
			//--- SI EL NUMERO ESTA PASADO , SE DA LA PRIORIDAD EN LA BUSQUEDA POR EL NUMERO
			if (! empty($numero) ){
				$data = SQLConnection::busquedaPadronAutocomplete($numero, true);
			}
			//--- SI EL NUMERO NO ESTA PASADO , SE HACE LA BUSQUEDA POR NOMBRE
			else{
				$data = SQLConnection::busquedaPadronAutocomplete($nombre, true);
			}
			//------
			foreach ( $data as $key => $value){
				//--- SI EL REGISTRO ES DE ARGENTINA LO ELIMINA
				if ( $value->country_code == 'AR'){
					unset($data[$key]);
				}
				//---- SI EL REGISTRO ES EXTRANJERO
				else{
					//----- SI SE HA INTRODUCIDO EL PAIS
					if (! empty($pais) ){
						//---- SI SE HA INTRODUCIDO EL IDENTIFICADOR
						if (! empty($identificacion) ){
							//----
							if ( $value->identificador == $identificacion ){
								continue;
							}
							//---
							else{
								unset($data[$key]);
							}
						}
						//---- SI NO SE HA INTRODUCIDO EL IDENTIFICADOR
						else{
							//---
							if ($value->country_code == $pais){
								continue;
							}
							//---
							else{
								unset($data[$key]);
							}
						}
					}
					//---- SI NO SE HA INTRODUCIDO EL PASI
					else{
						continue;
					}
				}
			}
			//----
		}
		//-- SI LOS DATOS SON INVALIDOS
		else{
			return;
		}
		//---- SE RENDERIZAN LOS DATOS A LA VISTA O SE DEVUELVEN EN FORMATO JSON
		if ($sin_tabla){
			return json_encode($data);
		}
		$vista = \View::make('/iv/iv_tabla_busqueda_padron')->with(compact(['data']))->render();
		return json_encode( array('view'=>$vista));
	}
	
	public static function nuevaBusquedaPadronVista() {
		$data = Request::input('data');

		if (!empty($data)) {
			$data = json_decode($data);
		}
		$vista = \View::make('/led/led_contrapartes_tabla_busqueda_api')->with(compact(['data']))->render();
        return json_encode( array('view' => $vista) );
	}

	/**
	 * Funcion que devuelve los 
	 * identificadores de pais con un
	 * @access public
	 * @return string
	 */
	public static function identificadoresPaisConPasaporteDinamicoOrg(){
		$cc = Request::input('country_code');
		$tipo_persona = empty(Request::input('tipo_persona')) ? 'F' : Request::input('tipo_persona');
		//
		$ident = Misc::identificadoresPais($cc,$tipo_persona);
		// if ( env('APP_ENV') == 'local' ){
		foreach( $ident as $key => $identificador ){
			if ( strstr($identificador->abreviatura,'PAS') !== FALSE ){
				if ( $cc == 'AR' ){
					unset($ident[$key]);
				} else {
					$ident[$key] = (object) ['identificador' => 'PASS','abreviatura' => 'PASS','nombre_identificador' => 'Passport','country_code' => 'XX'];
				}
			}
		}
		//}
		//
		return json_encode($ident);
	}


	/**
	 * Funcion que devuelve los 
	 * identificadores de pais con un
	 * @access public
	 * @return string
	 */
	public static function identificadoresPaisConPasaporteDinamico(){
		$cc = Request::input('country_code');
		$tipo_persona = empty(Request::input('tipo_persona')) ? 'F' : Request::input('tipo_persona');
		//
		$ident = Misc::identificadoresPais($cc,$tipo_persona);
		// if ( env('APP_ENV') == 'local' ){
		foreach( $ident as $key => $identificador ){
			if ( strstr($identificador->abreviatura,'PAS') !== FALSE ){
				if ( $cc != 'CO' ){
					$ident[$key] = (object) ['identificador' => 'PASS','abreviatura' => 'PASS','nombre_identificador' => 'Passport','country_code' => 'XX'];
				}
				/* if ( $cc == 'AR' ){
					unset($ident[$key]);
				} else {
					$ident[$key] = (object) ['identificador' => 'PASS','abreviatura' => 'PASS','nombre_identificador' => 'Passport','country_code' => 'XX'];
				} */
			}
		}
		//}
		//
		return json_encode($ident);
	}

}
