<?php namespace App\Http\Controllers;

use App\Custom\SQLConnection;
use App\Custom\Misc;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Request;

use App\Models\Proceso;

use Exception;

class ProcesosControllerNuevo extends Controller {

		//--------------------CONSTRUCTOR-----------------------------

	function __construct() {
		// max execution time infinito
		ini_set('max_execution_time', 0);
		Proceso::inicializarRutas();
	} 

	//--------------------ROUTE METHODS-----------------------------

	public function obtenerProcesos(){
		if ( ! Misc::restriccionPermiso('PROCESOS') ){ 
			return redirect('/menu'); 
		}
    	// obtenemos los permisos para el menu, ésta variable debe asignarse al compact de la vista.
    	$menu = Misc::obtenerPermisosNavigatorNoCuit();
    	$fuentes = Proceso::obtenerFuentes();
		return view('procesos/formulario_carga')->with(compact('menu', 'fuentes'));
	}

	public function obtenerTxtCliente(){
	    if ( ! Misc::restriccionPermiso('PROCESOS') ){ 
	    	return redirect('/menu'); 
	    }
	    $menu = Misc::obtenerPermisosNavigatorNoCuit();
	    $inicio_final = 'INICIO';
		return view('procesos/formulario_carga_txt_cliente')->with(compact('menu','inicio_final'));
	}

	public function obtenerTxtCliente2(){
	    if ( ! Misc::restriccionPermiso('PROCESOS') ){ 
	    	return redirect('/menu'); 
	    }
	    $menu = Misc::obtenerPermisosNavigatorNoCuit();
	    $inicio_final = 'FINAL';
		return view('procesos/formulario_carga_txt_cliente')->with(compact('menu','inicio_final'));
	}

	public function pendientesTxtCliente(){
		$cliente = Request::Input('cliente');
		$pendientes = SqlConnection::backendStoreProcedure('procesos_masivos_pendientes', array($cliente), 'selectOne');
		$error   = $pendientes->error ?? 0; 
		$mensaje = $pendientes->mensaje; 
		$cant    = $pendientes->pendientes; 
		
		$href = "/procesos/txt-cliente-2";
		return view("/vista_claudio/notificacion_carga_ai")->with(compact(['mensaje','href','error','cant','cliente']));

	}

 	public function finalTxtCliente(){
		$cliente = Request::Input('cliente');
	 	$pendientes = SqlConnection::backendStoreProcedure('procesos_masivos_fecha_defuncion', array($cliente), 'select');
 		$error   = $pendientes->error ?? 0; 
		if ($error == 0)
		{
			$file= 'CUIL,DNI,Nombre,Fecha,CUIL Validado,Nombre Validado,Fecha Fallecimiento';
			foreach($pendientes as $pend){
	        $file .=  "\n" .
	            		$pend->cuit . ',' .
		        		$pend->dni . ',' .
		        		$pend->nombre . ',' .
		        		$pend->fecha . ',' .
		        		$pend->cuitvalidado . ',' .
		        		$pend->nombrevalidado . ',' .
			    		$pend->fallecimiento;
        					
        	}
    		header('Content-disposition: attachment; filename=Proceso_' . $cliente . '.csv');
			header('Content-type: application/vnd.ms-excel	');
			echo $file;
		}
	}

	public function subirTxtCliente(){
		$cliente = Request::Input('cliente');
		$user_id 		= Session::get("usuario")->user_id;

		$user_name = Session::get('usuario')->username;
		$archivo = $_FILES['archivo']['name'];
		$url_temporal = $_FILES['archivo']['tmp_name'];
		
		$destino = "/var/www/html/compartido/InformesMasivos/" . $cliente . "/";
		if(!is_dir($destino)){
			mkdir($destino, 0777,true);
		}

		//==  ARRAY CON LOS DATOS CORRESPONDIENTES AL NOMBRE COLUMAN  ==//
		$cuit   = array();
		$dni    = array();
		$nombre = array();
		$fecha  = array();
		if(move_uploaded_file($url_temporal, $destino.$archivo)) {
			chmod($destino, 0777);
			$file = fopen($destino.$archivo, 'r');
			while (!feof($file)){
				$linea = fgets($file);
				if(strtoupper(substr($linea, 0, 3)) == "CUI") { continue; }
				if(trim($linea) == "") { continue; }
				$linea = str_replace('|', ',', $linea);
				$linea = str_replace(';', ',', $linea);
				$linea = str_replace('"', '', $linea);
				$linea = explode(',', $linea);
				//echo(count($linea).'</br>');
				foreach($linea as $key => $v) {
					$v = trim($v); 
					switch ($key) {
						case 0:
							$cuit[] = (strlen($v) > 0) ? $v : '';
							break;
						case 1:
							$dni[] = (strlen($v) > 0) ? $v : '';
							break;
						case 2:
							$nombre[] = (strlen($v) > 0) ? $v : '';
							break;
						case 3:
							$fecha[] = (strlen($v) > 0) ? $v : '';
							break;
					}
				}
			}
			
			$href = "/procesos/txt-cliente";
			$cant = 0; 
			foreach($cuit as $key => $v) {
				$cant += 1; 
				try {
					SqlConnection::backendStoreProcedure('procesos_masivos_insertar', array($cliente,$cuit[$key],$dni[$key],$nombre[$key],$fecha[$key],$user_id));
				} catch (Exception $e) {
					$mensaje = $e->getMessage();
					return view("/vista_claudio/notificacion_carga_ai")->with(compact(['mensaje','href','cliente']));
				}
			}
			$mensaje = 'Archivo cargado correctamente. Total de registros a procesar: ' . $cant;
			return view("/vista_claudio/notificacion_carga_ai")->with(compact(['mensaje','href'.'cliente']));
		}
		else 
		{
			$href = "/procesos/txt-cliente";
			$mensaje = "Se produjo un error al subir el archivo.";
			return view("/vista_claudio/notificacion_carga_ai")->with(compact(['mensaje','href','cliente']));
		}
 	}


	/*==  CODIGO ORIGINAL, MODIFICADO ES EL SIGUIENTE ==
	public function obtenerEjecutar(){

		// valido si el usuario tiene el permiso correspondiente para acceder a la sección solicitada.
    if ( !Misc::restriccionPermiso('PROCESOS') ){ 
    	return redirect('/menu'); 
    }
		$fuente_key = Request::input("fuente");
		if ( !$fuente_key ) {
			$res = "Fuente no identificada.";
			return view('procesos/nuevo')->with(compact('res'));
		}
		
		// GAFIP se procesa de forma distinta por eso tiene un método propio a diferencia de todas las demás fuentes
		if (strtolower($fuente_key) == "gafip"){
			Proceso::procesarGafip();
		}else{
			Proceso::asignarDatosInicialesDeFuente($fuente_key);
			Proceso::procesarArchivos();
		}
	}
	*/

	function modificador($n) {
		$n = explode(' ', $n);
		$cantidad = 0;
		$nuevo = '';
		foreach($n as $key) {
			if(strlen($key) >= 2 and $cantidad < 2) {
				$nuevo = $nuevo.$key[0];
				$cantidad += 1;
			}
		}
		return $nuevo;
	}
	/*  --  VERSION ORIGINAL  --  
	function cargos($c) {
		$c = trim($c);
		if(strlen($c) > 1 and $c != 'RELACIONADO') {
			$c = self::modificador($c);

			$cargos = array('S' => 'S', 'G' => 'SG', 'P' => 'P', 'V' => 'VP', 'DT' => 'DT', 'DS' => 'DS', 'VS' => 'VS', 'VT' => 'VT', 'D' => 'D');
			
			foreach ($cargos as $key => $value) {
				if($c == $key) {
					return $value;
				}
			}
			return 'ZZZ';
		} else if($c == 'RELACIONADO') {
			return 'RLL';
		} else {
			return 'ZZZ';
		}
		
		
	}
	*/

	function unificador_de_cargos($c) {
		$nuevo = '';

		if(count($c) == 4) {
			$nuevo = $c[0][0].$c[1][0].$c[2][0].$c[3][0];
		} else if(count($c) == 3) {
			$nuevo = $c[0][0].$c[1][0].$c[2][0];
		} else if(count($c) == 2) {
			$nuevo = $c[0][0].$c[1][0];
		} else {
			$nuevo = $c[0][0];
		}
		//echo(var_dump($nuevo)); die();
		return $nuevo;
	}

	function cargos($c) {
		$c = trim($c);

		if(strlen($c) > 1 and $c != 'RELACIONADO') {
			$c = explode(' ', $c);
			$c = self::unificador_de_cargos($c);
			
			switch ($c) {
				// #1
				case 'DS':
				case 'SD':
					return 'DS';
					break;
				// #2
				case 'DT':
				case 'TD':
					return 'DT';
					break;
				// #3
				case 'DTYP':
				case 'DTP':
				case 'PYDT':
				case 'PDT':
				case 'P':
					return 'P';
					break;

				// #4
				case 'DTYV':
				case 'DTV':
				case 'VYDT':
				case 'VDT':
				case 'V':
					return 'VP';
					break;
				// #5
				case 'G':
					return 'GTE';
					break;
				// #6
				case 'GS':
				case 'SG':
					return 'SUP';
					break;
				// #7
				case 'GT':
				case 'TG':
					return 'GTT';
					break;
				// #8
				case 'ST':
				case 'TS':
					return 'ST';
					break;
				// #9
				case 'S':
					return 'SU';
					break;
				default:
					return 'ZZZ';
					break;
			}

		} else if($c == 'RELACIONADO') {
			return 'RLL';
		} else {
			return 'ZZZ';
		}
		 
		
	}

	public function obtenerEjecutar(){

		// valido si el usuario tiene el permiso correspondiente para acceder a la sección solicitada.
    if ( !Misc::restriccionPermiso('PROCESOS') ){ 
    	return redirect('/menu'); 
    }
		$fuente_key = Request::input("fuente");
		if ( !$fuente_key ) {
			$res = "Fuente no identificada.";
			return view('procesos/nuevo')->with(compact('res'));
		}
		
		// GAFIP se procesa de forma distinta por eso tiene un método propio a diferencia de todas las demás fuentes
		if (strtolower($fuente_key) == "gafip"){
			Proceso::procesarGafip();
		} else if($fuente_key == 'sociedades_bt') {
			$ul_dir = (isset($_POST['ult_dir']) && $_POST['ult_dir'] == '1') ? 'S' : 'N';
			$user_id = Session::get('usuario')->user_id;
			//return view("/vista_claudio/notificacion_carga_ai")->with(compact(['mensaje'])); die();
			$mensaje = '';
			$user_name = Session::get('usuario')->username;
			$archivo = $_FILES['archivo']['name'];
			$url_temporal = $_FILES['archivo']['tmp_name'];
			$destino = "/var/www/html/compartido/Edicto_Procesado/";

			//==  ARRAY CON LOS DATOS CORRESPONDIENTES AL NOMBRE COLUMAN  ==//
			$titulo = array();
			$razonSocial = array();
			$documento_soc = array();
			$nombre_integrante = array();
			$nrdoc_int = array();
			$cuit_int = array();
			$cuit_integrante = array();
			$domicilio_integrante = array();
			$localidad_integrante = array();
			$capital_social = array();
			$cargo = array();
			$cargo_real = array();
			$domicilio_sociedad = array();
			$localidad_sociedad = array();
			$fecha_publicacion = array();
			$referencia_edicto = array();
			$contenido_archivo = array();
			$fuente = array();
			$provincia_sociedad = array();
			$created = array();
			$visible = array();

			if(move_uploaded_file($url_temporal, $destino.$archivo)) {
				$file = fopen($destino.$archivo, 'r');
				//echo(var_dump($file)); fclose($file); die();
				while (!feof($file)){
					$linea = fgets($file);
					
					$linea = explode('|', str_replace('"', '', $linea));
					//echo(count($linea).'</br>');
					foreach($linea as $key => $v) {
						switch ($key) {
							case 0:
								$titulo[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 1:
								$razonSocial[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 2:
								$documento_soc[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 3:
								$nombre_integrante[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 4:
								$nrdoc_int[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 5:
								$cuit_int[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 6:
								$cuit_integrante[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 7:
								$domicilio_integrante[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 8:
								$localidad_integrante[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 9:
								$capital_social[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 10:
								//--  ASIGNAR ARRAY STORE  --//
								//$cargo[] = (strlen($v) > 0) ? $v : ' ';
								$cargo_temporal = (strlen($v) > 0) ? $v : ' ';
								$cargo[] = self::cargos($cargo_temporal);
								$cargo_real[] = $cargo_temporal;
								break;
							case 11:
								$domicilio_sociedad[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 12:
								$localidad_sociedad[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 13:
								$fecha_publicacion[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 14:
								$referencia_edicto[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 15:
								$contenido_archivo[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 16:
								$fuente[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 17:
								$provincia_sociedad[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 18:
								$created[] = (strlen($v) > 0) ? $v : ' ';
								break;
							case 19:
								$visible[] = (strlen($v) > 0) ? $v : ' ';
								break;
							/*default:
								# code...
								break;*/
						}
					}
				}
				
				foreach($nombre_integrante as $key => $v) {
					try {
						SqlConnection::backendStoreProcedure('sociedades_edictos_insertar', array(0,$documento_soc[$key],$razonSocial[$key],$domicilio_sociedad[$key],$localidad_sociedad[$key],$provincia_sociedad[$key],$fecha_publicacion[$key],$titulo[$key],'',$capital_social[$key],'',$cargo[$key],$nombre_integrante[$key],$cuit_int[$key],$domicilio_integrante[$key],$localidad_integrante[$key],'',$fuente[$key],'',$contenido_archivo[$key],$created[$key],$ul_dir,$user_id, $cargo_real[$key]));
						/*echo(var_dump(0,$documento_soc[$key],$razonSocial[$key],$domicilio_sociedad[$key],$localidad_sociedad[$key],$provincia_sociedad[$key],$fecha_publicacion[$key],$titulo[$key],'',$capital_social[$key],'',$cargo[$key],$nombre_integrante[$key],$cuit_int[$key],$domicilio_integrante[$key],$localidad_integrante[$key],'',$fuente[$key],'',$contenido_archivo[$key],$created[$key],$ul_dir,$user_id, $cargo_real[$key]));
						die();*/
					} catch (Exception $e) {
						$mensaje = $e->getMessage();
						$href = '/procesos/nuevo';
						return view("/vista_claudio/notificacion_carga_ai")->with(compact(['mensaje','href']));
					}
				}
				$href = '/procesos/nuevo';
				$mensaje = 'Documento procesado correctamente.';
				return view("/vista_claudio/notificacion_carga_ai")->with(compact(['mensaje','href']));
				
			}else {
				$href = '/procesos/nuevo';
				$mensaje = "Se produjo un error al subir el archivo.";
				return view("/vista_claudio/notificacion_carga_ai")->with(compact(['mensaje','href']));
			}

			
		} else{
			Proceso::asignarDatosInicialesDeFuente($fuente_key);
			Proceso::procesarArchivos();
		}
	}

	public function obtenerMcyq(){
		$menu = Misc::obtenerPermisosNavigatorNoCuit();
		return view('procesos/mant_cyq')->with(compact('menu'));
	}

	public function generarMcyq(){
		$tipo = Request::Input('tipo');
		$fecha_desde = Request::Input('fecha_desde');
		$fecha_hasta = Request::Input('fecha_hasta');
		$fec = substr($fecha_hasta,-2) . substr($fecha_hasta, -5,2) . substr($fecha_hasta,2,2);

		if ($tipo == 'W') 
		{
			$mant = SQLConnection::backendStoreProcedure('Mantenimiento_Concursos_y_Quiebras_word',array($fecha_desde,$fecha_hasta),"select");
			$file = '';
			foreach($mant as $line){
        $file .= $line->registro."\n\n";
	  	}
    	header('Content-disposition: attachment; filename=mant_qyc_' . $fec . '.doc');
			header('Content-type: application/msword');
			echo $file;
		}
		if ($tipo == 'E') 
		{
			$mant = SQLConnection::backendStoreProcedure('Mantenimiento_Concursos_y_Quiebras_excel',array($fecha_desde,$fecha_hasta),"select");
			$file= 'Cuit'."\t".'Demandado'."\t".'Juzgado'."\t".'Fecha'."\t".'Tipo de Novedad'."\t".'Sindico'."\t".'Verificacion hasta'."\t".'Audiencia Informativa'."\t".'Observaciones'."\t".'Fuente'."\t".'Fecha Fuente';
			foreach($mant as $line){
        $file .=  "\n" .
                  $line->Cuit. "\t" .
        					$line->Demandado . "\t" .
        					$line->Juzgado . "\t" .
        					$line->Fecha . "\t" .
        					$line->TipodeNovedad . "\t" .
        					$line->Sindico . "\t" .
        					$line->VerificacionHasta . "\t" .
        					$line->AudienciaInformativa . "\t" .
        					$line->Observaciones . "\t" .
        					$line->Fuente . "\t" .
        					$line->FechaFuente;
        					
        }
    	header('Content-disposition: attachment; filename=mant_qyc_' . $fec . '.xls');
			header('Content-type: application/vnd.ms-excel	');
			echo $file;
		}
		if ($tipo == 'C') 
		{
			$mant = SQLConnection::backendStoreProcedure('Mantenimiento_Concursos_y_Quiebras_csv',array($fecha_desde,$fecha_hasta),"select");
			$file= 'Grupo'."|". 'Cuit'."|".'Demandado'."|".'Domicilio Demandado'."|".'Juzgado'."|".'Secretaria'."|".'Expediente'."|".'Fecha'."|".'Novedad'."|".'Sindico'."|".'Domicilio Sindico'."|".'Verificacion hasta'."|".'Audiencia Informativa';
			foreach($mant as $line){
        $file .=  "\n" .
                  $line->grupo. "|" .
                  $line->Cuit. "|" .
        					$line->Demandado . "|" .
        					$line->DomicilioDemandado . "|" .
        					$line->Juzgado . "|" .
        					$line->secretaria . "|" .
        					$line->expediente . "|" .
        					$line->Fecha . "|" .
        					$line->TipodeNovedad . "|" .
        					$line->Sindico . "|" .
        					$line->DomicilioSindico . "|" .
        					$line->VerificacionHasta . "|" .
        					$line->AudienciaInformativa;
        					
        }
			header('Content-disposition: attachment; filename=mant_qyc_' . $fec . '.txt');
			header('Content-type: application/text');
			echo $file;
		}

	}

}