<?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;

// use Illuminate\Session\TokenMismatchException;

class IVController extends Controller {

	public static function ivDashboard() {

		return view('/iv/iv_dashboard');
	}


	public static function ivPanelControl() {
		/* si el usuario / cliente tienen producto y cupo para solicitar un nuevo informe */
		$consumo = SQLConnection::backendStoreProcedure('IV_panel_control', array('control_consumo', NULL, Session::get('usuario')->user_id, env('IV_PRODUCTO')), 'selectOne');
		
		$en_proceso = 0;
		if ( $_SERVER['REDIRECT_URL'] == '/iv/iv-panel-control-en-proceso' ){
			$en_proceso++;
		}
		// return view('/iv/iv_panel_control')->with(compact(['consumo']));
        return view('/iv/new/iv_panel_control_nuevo')->with(compact(['consumo','en_proceso']));
	}

	public static function ivPanelControlInfo() {
		$cliente = Session::get('usuario')->cliente['client_id'];
		$user_id = Session::get('usuario')->user_id;
		

		/* 30/09/2020 El sp con la accion columnasr y indicadores_panel_controlr devuelven solo las columnas que el usuario tiene autorizadas */
		$columnas = SQLConnection::backendStoreProcedure('IV_panel_control', array('columnasr', $cliente, $user_id), 'select'); 
		$indicadores = SQLConnection::backendStoreProcedure('IV_panel_control', array('indicadores_panel_controlr', $cliente, $user_id), 'select');

		$personas = SQLConnection::backendStoreProcedure('IV_panel_control', array('panel_control', $cliente), 'select');
		/*---------------------------------------------------------------
		// 25/09/2020
		// en $columnas agregamos el valor de hidden siempre en 0
		// y ponemos hidden = 1 las columnas de indicadores que el usuario tenga restringidas 

		foreach ($columnas as $key => $value) {
			$columnas[$key]->hidden = 0; 
		}
		$usuarios_restricciones = Session::get('usuarios_restricciones');
		$servicio_actual = Session::get('servicio_actual');
		if(!empty($usuarios_restricciones)){
			foreach ($usuarios_restricciones as $key_ur => $value_ur) {
				if($servicio_actual == $key_ur){
					foreach ($value_ur as $key_n2 => $value_n2) {
						foreach ($columnas as $key => $value) {
							if ($value->indicador == $value_n2->indicador)
								{
									//$columnas[$key]->hidden = 1; 
									unset($columnas[$key]); 
								}
						}
					}
				}
			}
		}*/
		
		/*---------------------------------------------------------------*/
		$indic = [];
		foreach ($columnas as $y => $col) {
			// se descartan las columnas fijas
			if ($col->orden_producto > 0) {
				$indic[] = $col->clave_indicador;
			}
		}

		$pais		= [];
		$familias 	= [];
		$data 		= [];
		foreach ($personas as $k => $cand) {
			$cc = strtolower($cand->country_code);

			$pais[$k]['info'] = $cc;
			$pais[$k]['cls'] = 'flag-icon-' . $cc;
			$pais[$k]['val'] = '<span class=flag-icon flag-icon-background flag-icon-' . $cc .'></span>';

			$familias[$k]['value'] = $cand->familia;
			$data[$cand->contraparte] = (array) $cand;
			foreach ($indic as $j => $indica) {
				$data[$cand->contraparte][$indica]  = NULL;
				$data[$cand->contraparte]['icono'][$indica] = NULL;
				$data[$cand->contraparte]['cls'][$indica]   = NULL;
				$data[$cand->contraparte]['color'][$indica] = NULL;
				$data[$cand->contraparte]['title'][$indica] = NULL;
			}
		}

		foreach ($data as $k => $iv) {
			$data[$k]['foto_60'] = '<img src="'. env('RUTA_DOCUMENTOS_IV') . '/' . $data[$k]['foto_60'] . '?r=' . time() .  '" border="0" class="img img-responsive" width="50" height="50" />';
			$data[$k]['country'] = strtolower($data[$k]['country_code']);
		}
		$cv_iv			    = [];
		$valoracion_iv		= [];
		$academico			= [];
		$profesional 		= [];
		$comercial_legal 	= [];
		$compliance 		= [];
		$prensaiv 			= [];
		//-----NUEVO ---------///
		$contrapartes_a_servidor = [];
		$indicador = 0;
		//------
		//------ CREAR LA LISTA QUE VA A SER LLENADA CON LOS CONTRAPARTES DE LOS CASOS QUE ESTAN EN PROCESO QUE VAN A SER MANDADOS A LA BASE DE DATOS
		foreach ($indicadores as $n => $valores){
			//----
			if ($valores->visible == 0 and $valores->clave_indicador == 'IV_CV'){
				array_push($contrapartes_a_servidor,$valores->contraparte);
			}
		}
		//----
		$contrapartres_a_servidor_cadena = implode(',',$contrapartes_a_servidor);
		//----
		//---------- NUEVA LLAMADA AL STORE , QUE DEVUELVE INDICADORES PARA SEPARAR LO QUE ESTA EN PROCESO EN TRES ESTADOS
		$iconos_devueltos = SQLConnection::backendStoreProcedure('iv_estados_en_proceso',array('LISTAR',$contrapartres_a_servidor_cadena));
		//---------- FIN DE LO NUEVO-------//
		foreach ($indicadores as $n => $valores) {
			if ($valores->visible == 0 and $valores->clave_indicador != 'COMERCIAL_LEGAL' and $valores->clave_indicador != 'COMPLIANCE')
			{
				$valores->cls = 'XX';
				$valores->icono = env('ICONO4_EN_PROCESO');
				$valores->color = env('COLOR4_EN_PROCESO');
				$valores->titulo = env('TEXTO4_EN_PROCESO');
			}

			//---------  EN ESTA SECCION SE MODIFICAN LOS CONTENIDOS DE LOS QUE ESTAN EN PROCESO PARA SEPARAR A ALGUNOS EN TRES ESTADOS
			if ($valores->visible == 0 and $valores->clave_indicador == 'IV_CV'){
				foreach($iconos_devueltos as $p => $value){
					if ($valores->contraparte == $value->contraparte){
						//---
						if ($value->ICONO == 'ICONO1'){
							$valores->cls = 'XX1';
							$valores->icono = env('ICONO1_EN_PROCESO');
							$valores->color = env('COLOR1_EN_PROCESO');
							$valores->titulo = env('TEXTO1_EN_PROCESO');
							break;
						}
						//---
						elseif($value->ICONO == 'ICONO2'){
							$valores->cls = 'XX2';
							$valores->icono = env('ICONO2_EN_PROCESO');
							$valores->color = env('COLOR2_EN_PROCESO');
							$valores->titulo = env('TEXTO2_EN_PROCESO');
							break;
						}
						//---
						elseif($value->ICONO == 'ICONO3'){
							$valores->cls = 'XX3';
							$valores->icono = env('ICONO3_EN_PROCESO');
							$valores->color = env('COLOR3_EN_PROCESO');
							$valores->titulo = env('TEXTO3_EN_PROCESO');
							break;
						}
						//---
					}
				}
			}
			//-------
			
			if($valores->clave_indicador == 'IV_CV' and $valores->visible == 1 ){	
				$cv_iv[$n]['info'] = $valores->icono; 
				$cv_iv[$n]['cls']  = $valores->cls;
				$cv_iv[$n]['color'] = $valores->color;
				$cv_iv[$n]['title'] = $valores->titulo;
			}
			if($valores->clave_indicador == 'VALORACION_IV' and $valores->visible == 1 ){
				$valoracion_iv[$n]['info'] = $valores->icono;
				$valoracion_iv[$n]['cls']  = $valores->cls;
				$valoracion_iv[$n]['color'] = $valores->color;
				$valoracion_iv[$n]['title'] = $valores->titulo;
			}
			if($valores->clave_indicador == 'ACADEMICO' and $valores->visible == 1){
				$academico[$n]['info'] = $valores->icono;
				$academico[$n]['cls']  = $valores->cls;
				$academico[$n]['color'] = $valores->color;
				$academico[$n]['title'] = $valores->titulo;
			}
			if($valores->clave_indicador == 'PROFESIONAL' and $valores->visible == 1){
				$profesional[$n]['info'] = $valores->icono;
				$profesional[$n]['cls']  = $valores->cls;
				$profesional[$n]['color'] = $valores->color;
				$profesional[$n]['title'] = $valores->titulo;
			}
			if($valores->clave_indicador == 'COMERCIAL_LEGAL' and $valores->visible == 1){
				$comercial_legal[$n]['info'] = $valores->icono;
				$comercial_legal[$n]['cls']  = $valores->cls;
				$comercial_legal[$n]['color'] = $valores->color;
				$comercial_legal[$n]['title'] = $valores->titulo;
			}
			if($valores->clave_indicador == 'COMPLIANCE' and $valores->visible == 1){
				$compliance[$n]['info'] = $valores->icono;
				$compliance[$n]['cls']  = $valores->cls;
				$compliance[$n]['color'] = $valores->color;
				$compliance[$n]['title'] = $valores->titulo;
			}
			if($valores->clave_indicador == 'PRENSAIV' and $valores->visible == 1){
				$prensaiv[$n]['info'] = $valores->icono;
				$prensaiv[$n]['cls']  = $valores->cls;
				$prensaiv[$n]['color'] = $valores->color;
				$prensaiv[$n]['title'] = $valores->titulo;
			}
			$data[$valores->contraparte][$valores->clave_indicador] = $valores->titulo; 
			$data[$valores->contraparte][$valores->clave_indicador.'_icono']  = $valores->icono;
			$data[$valores->contraparte][$valores->clave_indicador.'_cls']    = $valores->cls;
			$data[$valores->contraparte][$valores->clave_indicador.'_color'] = $valores->color;
			$data[$valores->contraparte][$valores->clave_indicador.'_titulo']  = $valores->titulo;
		}


		$pais	   		= array_map("unserialize", array_unique(array_map("serialize", $pais)));
		$familias		= array_map("unserialize", array_unique(array_map("serialize", $familias)));
		$cv_iv	   		= array_map("unserialize", array_unique(array_map("serialize", $cv_iv)));
		$valoracion_iv	= array_map("unserialize", array_unique(array_map("serialize", $valoracion_iv)));
		$academico		= array_map("unserialize", array_unique(array_map("serialize", $academico)));
		$profesional	= array_map("unserialize", array_unique(array_map("serialize", $profesional)));
		$comercial_legal= array_map("unserialize", array_unique(array_map("serialize", $comercial_legal)));
		$compliance		= array_map("unserialize", array_unique(array_map("serialize", $compliance)));
		$prensaiv		= array_map("unserialize", array_unique(array_map("serialize", $prensaiv)));
		$inquiro = [];
		$inquiro_en_proceso = [];
		//-----------
		if (empty($data)){
			return json_encode(
				array(
					'error'=>'Sin datos'
				)
			);
		}
		//----------- 
		foreach ($data as $contraparte => $nd) {
			$pp = [];
			foreach ($columnas as $x => $col) {
				$g = (array) $col;
                
				$pp[$g['clave_indicador']] = $nd[ $g['clave_indicador'] ] ?? null;
				$pp[$g['clave_indicador'].'_icono'] = $nd[ $g['clave_indicador'].'_icono'] ?? null;
				$pp[$g['clave_indicador'].'_cls'] = $nd[ $g['clave_indicador'].'_cls'] ?? null;
				$pp[$g['clave_indicador'].'_color'] = $nd[ $g['clave_indicador'].'_color'] ?? null;
				$pp[$g['clave_indicador'].'_titulo'] = $nd[ $g['clave_indicador'].'_titulo'] ?? null;
			}

			$pp['contraparte'] = $nd['contraparte'] ?? null;
			$pp['iv_busqueda'] = $nd['iv_busqueda'] ?? null;
			$pp['country_code'] = $nd['country_code'] ?? null;
			//------- SECCION DE TRADUCCIONES
			Traducciones::$blade = 'iv_panel_control';
			$trad = SQLConnection::obtenerTraduccionesPHP(Traducciones::$blade);
			//----
			$etiqueta_solicitud = env('TEXTO1_EN_PROCESO');
			$etiqueta_referencia = env('TEXTO2_EN_PROCESO');
			$etiqueta_redaccion = env('TEXTO3_EN_PROCESO');
			$etiqueta_control_calidad = env('TEXTO4_EN_PROCESO');
			//------
			if ( array_key_exists($etiqueta_solicitud,$trad) ){
				foreach ($trad as $key => $value) {
					if ($etiqueta_solicitud == $key){
						$etiqueta_solicitud = $value;
					}
				}
			}
			else{
				Traducciones::set($etiqueta_solicitud,Traducciones::$blade);
			}
			//-----
			if ( array_key_exists($etiqueta_referencia,$trad) ){
				foreach ($trad as $key => $value) {
					if ($etiqueta_referencia == $key){
						$etiqueta_referencia = $value;
					}
				}
			}
			else{
				Traducciones::set($etiqueta_referencia,Traducciones::$blade);
			}
			//-----
			if ( array_key_exists($etiqueta_redaccion,$trad) ){
				foreach ($trad as $key => $value) {
					if ($etiqueta_redaccion == $key){
						$etiqueta_redaccion = $value;
					}
				}
			}
			else{
				Traducciones::set($etiqueta_redaccion,Traducciones::$blade);
			}
			//----------	
			if ( array_key_exists($etiqueta_control_calidad,$trad) ){
				foreach ($trad as $key => $value) {
					if ($etiqueta_control_calidad == $key){
						$etiqueta_control_calidad = $value;
					}
				}
			}
			else{
				Traducciones::set($etiqueta_control_calidad,Traducciones::$blade);
			}
			//---- FIN DE LA SECCION DE TRADUCCIONES
			//------------- NUEVO
			if ($pp['IV_CV'] == env('TEXTO4_EN_PROCESO') or $pp['ACADEMICO'] == env('TEXTO4_EN_PROCESO') or $pp['COMERCIAL_LEGAL'] == env('TEXTO4_EN_PROCESO') or $pp['COMPLIANCE'] == env('TEXTO4_EN_PROCESO') or $pp['PRENSAIV'] == env('TEXTO4_EN_PROCESO') or $pp['PROFESIONAL'] == env('TEXTO4_EN_PROCESO') or $pp['VALORACION_IV'] == env('TEXTO4_EN_PROCESO')){
				//------------ SI TIENE ALGUN ESTADO EN PROCESO, LE QUITA LOS VALORES A LOS SIGUIENTES OBJETOS
				$pp['IV_CV'] = null;
				$pp['IV_CV_cls'] = null;
				$pp['IV_CV_color'] = null;
				$pp['IV_CV_icono'] = null;
				$pp['IV_CV_titulo'] = null;
				$pp['VALORACION_IV'] = null;
				$pp['VALORACION_IV_cls'] = null;
				$pp['VALORACION_IV_color'] = null;
				$pp['VALORACION_IV_icono'] = null;
				$pp['VALORACION_IV_titulo'] = null;
				$pp['ACADEMICO'] = null;
				$pp['ACADEMICO_cls'] = null;
				$pp['ACADEMICO_color'] = null;
				$pp['ACADEMICO_icono'] = null;
				$pp['ACADEMICO_titulo'] = null;
				//-------- Y LE AGREGA EL ESTADO DE EN PROCESO A LA COLUMNA PROFESIONAL 
				$pp['PROFESIONAL'] = $etiqueta_control_calidad;
				$pp['PROFESIONAL_cls'] = 'XX';
				$pp['PROFESIONAL_color'] = env('COLOR4_EN_PROCESO');
				$pp['PROFESIONAL_icono'] = env('ICONO4_EN_PROCESO');
				$pp['PROFESIONAL_titulo'] = $etiqueta_control_calidad;
				$inquiro_en_proceso[] = $pp;
			}
			elseif ($pp['IV_CV'] == env('TEXTO1_EN_PROCESO') or $pp['ACADEMICO'] == env('TEXTO1_EN_PROCESO') or $pp['COMERCIAL_LEGAL'] == env('TEXTO1_EN_PROCESO') or $pp['COMPLIANCE'] == env('TEXTO1_EN_PROCESO') or $pp['PRENSAIV'] == env('TEXTO1_EN_PROCESO') or $pp['PROFESIONAL'] == env('TEXTO1_EN_PROCESO') or $pp['VALORACION_IV'] == env('TEXTO1_EN_PROCESO')){
				//-------- SI TIENE ALGUN ESTADO COMPLETANDO DOCUMENTO, LE QUITA LOS VALORES A LOS SIGUIENTES OBJETOS
				$pp['VALORACION_IV'] = null;
				$pp['VALORACION_IV_cls'] = null;
				$pp['VALORACION_IV_color'] = null;
				$pp['VALORACION_IV_icono'] = null;
				$pp['VALORACION_IV_titulo'] = null;
				$pp['ACADEMICO'] = null;
				$pp['ACADEMICO_cls'] = null;
				$pp['ACADEMICO_color'] = null;
				$pp['ACADEMICO_icono'] = null;
				$pp['ACADEMICO_titulo'] = null;
				$pp['PROFESIONAL'] == null;
				$pp['PROFESIONAL_cls'] = null;
				$pp['PROFESIONAL_color'] = null;
				$pp['PROFESIONAL_icono'] = null;
				$pp['PROFESIONAL_titulo'] = null;
				//-------- Y LE AGREGA EL ESTADO COMPLETANDO DOCUMENTO A LA COLUMNA IV_CV
				$pp['IV_CV'] = $etiqueta_solicitud;
				$pp['IV_CV_cls'] = 'XX1';
				$pp['IV_CV_color'] = env('COLOR1_EN_PROCESO');
				$pp['IV_CV_icono'] = env('ICONO1_EN_PROCESO');
				$pp['IV_CV_titulo'] = $etiqueta_solicitud;
				$inquiro_en_proceso[] = $pp;
			}
			elseif ($pp['IV_CV'] == env('TEXTO2_EN_PROCESO') or $pp['ACADEMICO'] == env('TEXTO2_EN_PROCESO') or $pp['COMERCIAL_LEGAL'] == env('TEXTO2_EN_PROCESO') or $pp['COMPLIANCE'] == env('TEXTO2_EN_PROCESO') or $pp['PRENSAIV'] == env('TEXTO2_EN_PROCESO') or $pp['PROFESIONAL'] == env('TEXTO2_EN_PROCESO') or $pp['VALORACION_IV'] == env('TEXTO2_EN_PROCESO')){
				//-------- SI TIENE ALGUN ESTADO EN AGUARDANDO REFERENCIA, LE QUITA LOS VALORES A LOS SIGUIENTES OBJETOS
				$pp['ACADEMICO'] = null;
				$pp['ACADEMICO_cls'] = null;
				$pp['ACADEMICO_color'] = null;
				$pp['ACADEMICO_icono'] = null;
				$pp['ACADEMICO_titulo'] = null;
				$pp['PROFESIONAL'] == null;
				$pp['PROFESIONAL_cls'] = null;
				$pp['PROFESIONAL_color'] = null;
				$pp['PROFESIONAL_icono'] = null;
				$pp['PROFESIONAL_titulo'] = null;
				$pp['IV_CV'] = null;
				$pp['IV_CV_cls'] = null;
				$pp['IV_CV_color'] = null;
				$pp['IV_CV_icono'] = null;
				$pp['IV_CV_titulo'] = null;
				//-------- Y LE AGREGA EL ESTADO AGUARDANDO REFERENCIA A LA COLUMNA VALORACION_IV
				$pp['VALORACION_IV'] = $etiqueta_referencia;
				$pp['VALORACION_IV_cls'] = 'XX2';
				$pp['VALORACION_IV_color'] = env('COLOR2_EN_PROCESO');
				$pp['VALORACION_IV_icono'] = env('ICONO2_EN_PROCESO');
				$pp['VALORACION_IV_titulo'] = $etiqueta_referencia;
				$inquiro_en_proceso[] = $pp;
			}
			elseif ($pp['IV_CV'] == env('TEXTO3_EN_PROCESO') or $pp['ACADEMICO'] == env('TEXTO3_EN_PROCESO') or $pp['COMERCIAL_LEGAL'] == env('TEXTO3_EN_PROCESO') or $pp['COMPLIANCE'] == env('TEXTO3_EN_PROCESO') or $pp['PRENSAIV'] == env('TEXTO3_EN_PROCESO') or $pp['PROFESIONAL'] == env('TEXTO3_EN_PROCESO') or $pp['VALORACION_IV'] == env('TEXTO3_EN_PROCESO')){
				//-------- SI TIENE ALGUN ESTADO EN REDACTANDO INFORME, LE QUITA LOS VALORES A LOS SIGUIENTES OBJETOS
				$pp['PROFESIONAL'] == null;
				$pp['PROFESIONAL_cls'] = null;
				$pp['PROFESIONAL_color'] = null;
				$pp['PROFESIONAL_icono'] = null;
				$pp['PROFESIONAL_titulo'] = null;
				$pp['IV_CV'] = null;
				$pp['IV_CV_cls'] = null;
				$pp['IV_CV_color'] = null;
				$pp['IV_CV_icono'] = null;
				$pp['IV_CV_titulo'] = null;
				$pp['VALORACION_IV'] = null;
				$pp['VALORACION_IV_cls'] = null;
				$pp['VALORACION_IV_color'] = null;
				$pp['VALORACION_IV_icono'] = null;
				$pp['VALORACION_IV_titulo'] = null;
				//-------- Y LE AGREGA EL ESTADO REDACTANDO INFORME A LA COLUMNA ACADEMICO
				$pp['ACADEMICO'] = $etiqueta_redaccion;
				$pp['ACADEMICO_cls'] = 'XX3';
				$pp['ACADEMICO_color'] = env('COLOR3_EN_PROCESO');
				$pp['ACADEMICO_icono'] = env('ICONO3_EN_PROCESO');
				$pp['ACADEMICO_titulo'] = $etiqueta_redaccion;
				$inquiro_en_proceso[] = $pp;
			}
			//------------------ MODIFICACION 18/10/2021
			elseif($pp['IV_CV'] == null and $pp['ACADEMICO'] == null and $pp['PRENSAIV'] == null and $pp['VALORACION_IV'] == null){
				$inquiro_en_proceso[] = $pp;
			}
			//-------- FIN
			else{
				$inquiro[] = $pp;	
			}
			//---------
		}
		//--------------------- SECCION DONDE SE DETERMINA SI UNA DE LAS DOS SECCIONES SON VACIAS O NO
		//-------- VARIABLE QUE DETERMINA SI HAY ALGUNA SECCION VACIA
		$grid_tiene_valores = 0;
		//-------- SI NO HAY CONTRAPARTES QUE ESTEN EN PROCESO
		if ( empty($inquiro_en_proceso) ){
			$grid_tiene_valores += 1;
		}
		//-------- SI NO HAY CONTRAPARTES QUE ESTEN FINALIZADAS
		elseif ( empty($inquiro) ){
			$grid_tiene_valores += 2;
		}
		//-------- SI AMBAS SECCIONES TIENE CONTENIDO
		else {
			$grid_tiene_valores += 3;
		}
		//----------
		//--------------------- SECCION DONDE SE ORDENAN LOS VALORES EN PROCESO DE FORMA DIAGONAL, PRIMERO SE VERIFICA QUE EL ARRAY DE EN PROCESO NO ESTE VACIO
		if ($grid_tiene_valores != 1){
			//--------
			$inquiro_sorteado = [];
			$inquiro_xx = [];
			$inquiro_xx1 = [];
			$inquiro_xx2 = [];
			$inquiro_xx3 = [];
			$inquiro_sin_estado = [];
			//----- SE CORRE UN LOOP PARA SEPARAR EL CONTENIDO DE MANERA ORDENADA
			foreach ($inquiro_en_proceso as $key => $value) {
				if ( $value['IV_CV_cls'] == 'XX1' ){
					array_push($inquiro_xx1,$value);
				}
				elseif ( $value['VALORACION_IV_cls'] == 'XX2' ){
					array_push($inquiro_xx2,$value);
				}
				elseif ( $value['ACADEMICO_cls'] == 'XX3' ){
					array_push($inquiro_xx3,$value);
				}
				elseif ( $value['PROFESIONAL_cls'] == 'XX' ){
					array_push($inquiro_xx,$value);
				}
				else{
					array_push($inquiro_sin_estado,$value);
				}
			}
			//---------------- SE UNEN LOS ARRAYS DESPUES DEL LOOP EN EL ARRAY inquiro_sorteado PARA FORMAR LA ESTRUCTURA DIAGONAL
			$inquiro_sorteado = array_merge($inquiro_xx1,$inquiro_xx2,$inquiro_xx3,$inquiro_xx,$inquiro_sin_estado);
		}
		//------------ EN ESTA SECCION SE MODIFICAN LAS ULTIMAS CUATRO COLUMNAS DE LA SECCION EN PROCESO
		$columnas_en_proceso = [];
		//-------- SE CREA UN NUEVO ARRAY DE COLUMNAS Y SE LES SACA ALGUNOS CONTENIDOS DE LAS ULTIMAS CUATRO COLUMNAS
		foreach ($columnas as $key => $value) {
			if ($key < 8){
				$objeto = clone $columnas[$key];
				array_push($columnas_en_proceso,$objeto);
			}
			//----------
			elseif ($key >= 8 and $key <= 13){
				$objeto = clone $columnas[$key];
				//----- LE MODIFICA LA ETIQUETA Y EL ICONO A LAS COLUMNAS INDICADAS
				if ($objeto->clave_indicador == 'IV_CV'){
					$objeto->class_icon = 'fas '.env('ICONO1_EN_PROCESO');
					$objeto->etiqueta_indicador = $etiqueta_solicitud;
					$objeto->searchable = '0';
					array_push($columnas_en_proceso,$objeto);
				}
				//----
				elseif($objeto->clave_indicador == 'VALORACION_IV'){
					$objeto->class_icon = 'fas '.env('ICONO2_EN_PROCESO');
					$objeto->etiqueta_indicador = $etiqueta_referencia;
					$objeto->searchable = '0';
					array_push($columnas_en_proceso,$objeto);
				}
				//---
				elseif($objeto->clave_indicador == 'ACADEMICO'){
					$objeto->class_icon = 'fas '.env('ICONO3_EN_PROCESO');
					$objeto->etiqueta_indicador = $etiqueta_redaccion;
					$objeto->searchable = '0';
					array_push($columnas_en_proceso,$objeto);
				}
				//----
				elseif($objeto->clave_indicador == 'PROFESIONAL'){
					$objeto->class_icon = 'fas '.env('ICONO4_EN_PROCESO');
					$objeto->etiqueta_indicador = $etiqueta_control_calidad;
					$objeto->searchable = '0';
					array_push($columnas_en_proceso,$objeto);
				}
				//----
				else{
					$objeto->searchable = '0';
					array_push($columnas_en_proceso,$objeto);
				}
			}
		}
		//----------- EN ESTA SECCION SE DEVUELVEN LOS VALORES A LA VISTA SEGUN EL ESTADO QUE TIENEN
	if ( $grid_tiene_valores == 3){
		
		//-----------NUEVO
		//--------SI ENTRA EN ESTA CONDICION DEVUELVE LOS VALORES FINALIZADOS
		if ($_POST['mostrar_en_proceso'] == '0') {
			return json_encode( array(
				'columnas' => $columnas,
				'data' => $inquiro,
				'pais' => $pais ,
				'familias' => $familias,
				//'cv' => $cv,
				'cv_iv' => $cv_iv,
				'valoracion_iv' => $valoracion_iv,
				'academico' => $academico,
				'profesional' => $profesional,
				'comercial_legal' => $comercial_legal,
				'compliance' => $compliance,
				'prensa' => $prensaiv,
				'indicador_boton' => '0',
				'indicador_estado_grid' => '0',
				'error'=>'0'
			));
		}
		//--------SI ENTRA EN ESTA CONDICION DEVUELVE LOS VALORES EN PROCESO
		elseif ($_POST['mostrar_en_proceso'] == '1'){
			return json_encode( array(
					//---NUEVO
				'columnas' => $columnas_en_proceso,
				'data' => $inquiro_sorteado,
				'pais' => $pais ,
				'familias' => $familias,
				//'cv' => $cv,
				'cv_iv' => $cv_iv,
				'valoracion_iv' => $valoracion_iv,
				'academico' => $academico,
				'profesional' => $profesional,
				'comercial_legal' => $comercial_legal,
				'compliance' => $compliance,
				'prensa' => $prensaiv,
				'indicador_boton' => '1',
				'indicador_estado_grid' => '0',
				'error'=>'0'
			));
		}
	}
	//-------------- SI ENTRA EN ESTA CONDICION VA A DEVOLVER UNICAMENTE LOS QUE ESTAN EN PROCESO PORQUE NO HAY NINGUNO FINALIZADO
	elseif ( $grid_tiene_valores == 2 ){
		// nahu
		return json_encode( array(
			//---NUEVO
			'columnas' => $columnas_en_proceso,
			'data' => $inquiro_sorteado,
			'pais' => $pais ,
			'familias' => $familias,
			//'cv' => $cv,
			'cv_iv' => $cv_iv,
			'valoracion_iv' => $valoracion_iv,
			'academico' => $academico,
			'profesional' => $profesional,
			'comercial_legal' => $comercial_legal,
			'compliance' => $compliance,
			'prensa' => $prensaiv,
			'indicador_boton' => '1',
			'indicador_estado_grid' => '1',
			'error'=>'0'
		));
	}
	//------------- SI ENTRA EN ESTA CONDICION VA A DEVOLVER LOS QUE ESTAN FINALIZADAS PORQUE NO HAY NINGUNO EN PROCESO
	elseif ( $grid_tiene_valores == 1){
		
		return json_encode( array(
			'columnas' => $columnas,
			'data' => $inquiro,
			'pais' => $pais ,
			'familias' => $familias,
			//'cv' => $cv,
			'cv_iv' => $cv_iv,
			'valoracion_iv' => $valoracion_iv,
			'academico' => $academico,
			'profesional' => $profesional,
			'comercial_legal' => $comercial_legal,
			'compliance' => $compliance,
			'prensa' => $prensaiv,
			'indicador_boton' => '0',
			'indicador_estado_grid' => '2',
			'error'=>'0'
		));
	}

	}

	public static function ivExportarExcel() {
		$cliente = Session::get('usuario')->cliente['client_id'];
		$contrapartes = Request::input('contrapartes');

		$acontr = explode(',', $contrapartes); 

		$candidatos = SQLConnection::backendStoreProcedure('IV_panel_control', array('panel_control_excel', $cliente), 'select');

		/* 30/09/2020 El sp con la accion indicadores_panel_controlr devuelve solo las columnas que el usuario tiene autorizadas */
		$user_id = Session::get('usuario')->user_id;
		$columnas = SQLConnection::backendStoreProcedure('IV_panel_control', array('columnasr', $cliente, $user_id), 'select'); 
		$indicadores = SQLConnection::backendStoreProcedure('IV_panel_control', array('indicadores_panel_controlr', $cliente, $user_id), 'select');

		foreach($candidatos as $cand) {
			if (in_array($cand->contraparte, $acontr)) {
				$data[$cand->contraparte]['pais'] = $cand->country_name;
				$data[$cand->contraparte]['familia'] = $cand->familia;
				$data[$cand->contraparte]['nombre'] = $cand->nombre_persona;
				$data[$cand->contraparte]['fecha'] = $cand->creado;
				$data[$cand->contraparte]['referencia'] = $cand->ref . ' - ' . $cand->ref_nombre;
				$data[$cand->contraparte]['sector'] = $cand->ref_seccion;
				$data[$cand->contraparte]['cargo'] = $cand->ref_cargo;
				$data[$cand->contraparte]['tipo'] = $cand->abreviatura;
				$data[$cand->contraparte]['documento'] = $cand->identificacion;
				$data[$cand->contraparte]['email'] = $cand->email_candidato;
				$data[$cand->contraparte]['telefono'] = $cand->telefono_candidato;
				//$data[$cand->contraparte]['cv'] = $cand->cv_existe > 0 ? 'SI' : 'NO';
			}
		}

		// Acá hago corte de control por ID de contraparte para no buscar en array por cada registro de indicadores
		$last = 0;
		foreach($indicadores as $indica) {
			if ($indica->contraparte != $last) {
				$cand = $indica->contraparte;
				$incluye = in_array($cand, $acontr);
				var_dump(in_array($cand, $acontr));
			}

			if ($incluye) {
				if($indica->clave_indicador == 'IV_CV')
				{
					if ($indica->valor_numerico == '1') 
						 {	$data[$cand][$indica->clave_indicador] = 'SI'; }
					else {	$data[$cand][$indica->clave_indicador] = 'NO'; }
				} 
				else
				{
				$data[$cand][$indica->clave_indicador] = $indica->valor_texto != NULL ? ( ($indica->valor_texto == 'P') ? 'Positivo' : (($indica->valor_texto == 'O') ? 'Observado' : 'Alerta') ) : NULL;
				}
			}

			$last = $cand;
		}
		
		$file = '<table border="1">';
		$file .= '<tr><th>País</th><th>Familia</th><th>Apellido y Nombres</th><th>Fecha</th><th>Referencia</th><th>Sector</th><th>Cargo</th>';
		$file .= '<th>Tipo</th><th>Documento</th><th>E-mail</th><th>Teléfono</th>';
		//$file .= '<th>CV</th><th>Valoración</th><th>Académico</th><th>Profesional</th><th>Comercial/Legal</th><th>Compliance</th><th>Prensa</th></tr>'; 
		/* 30/09/2020 No son mas columnas fijas, son las que devuelve el SP, que el usuario tiene habilitadas */ 
		foreach($columnas as $j => $col) {
			if ($col->orden_producto <= 0) { continue; }
			$file .= '<th>' . $col->etiqueta_indicador . '</th>';
		}
		$file .= '</tr>';
		
		foreach($data as $x => $candidato) {
			$file .= '<tr>';
			$file .= '<td style="text-align:center;">' . $candidato['pais'] . '</td>';
			$file .= '<td>' . $candidato['familia'] . '</td>';
			$file .= '<td>' . $candidato['nombre'] . '</td>';
			$file .= '<td style="text-align:center;">' . $candidato['fecha'] . '</td>';
			$file .= '<td>' . $candidato['referencia'] . '</td>';
			$file .= '<td>' . $candidato['sector'] . '</td>';
			$file .= '<td>' . $candidato['cargo'] . '</td>';
			$file .= '<td>' . $candidato['tipo'] . '</td>';
			$file .= '<td style="mso-number-format:\'@\';">' . $candidato['documento'] . '</td>';
			$file .= '<td>' . $candidato['email'] . '</td>';
			$file .= '<td style="mso-number-format:\'@\';">' . $candidato['telefono'] . '</td>';
			//$file .= '<td style="text-align:center;">' . $candidato['cv'] . '</td>';
			foreach($columnas as $j => $col) {
				if ($col->orden_producto <= 0) { continue; }
				$file .= '<td style="text-align:center;">' .(isset($candidato[$col->clave_indicador]) ? $candidato[$col->clave_indicador] : '') . '</td>';
				/*
				if ($col->clave_indicador == 'IV_CV') { 
					$file .= '<td style="text-align:center;">' .(isset($candidato['IV_CV']) ? $candidato['IV_CV'] : '') . '</td>';
				}
				if ($col->clave_indicador == 'VALORACION_IV') { 
					$file .= '<td style="text-align:center;">' . (isset($candidato['VALORACION_IV']) ? $candidato['VALORACION_IV'] : '') . '</td>';
				}
				if ($col->clave_indicador == 'ACADEMICO') { 
					$file .= '<td style="text-align:center;">' . (isset($candidato['ACADEMICO']) ? $candidato['ACADEMICO'] : '') . '</td>';
				}
				if ($col->clave_indicador == 'PROFESIONAL') { 
					$file .= '<td style="text-align:center;">' . (isset($candidato['PROFESIONAL']) ? $candidato['PROFESIONAL'] : '') . '</td>';
				}
				if ($col->clave_indicador == 'COMERCIAL_LEGAL') { 
					$file .= '<td style="text-align:center;">' .(isset($candidato['COMERCIAL_LEGAL']) ? $candidato['COMERCIAL_LEGAL'] : '') . '</td>';
				}
				if ($col->clave_indicador == 'COMPLIANCE') { 
					$file .= '<td style="text-align:center;">' .(isset($candidato['COMPLIANCE']) ? $candidato['COMPLIANCE'] : '') . '</td>';
				}
				if ($col->clave_indicador == 'PRENSAIV') { 
					$file .= '<td style="text-align:center;">' .(isset($candidato['PRENSAIV']) ? $candidato['PRENSAIV'] : '') . '</td>';
				}
				*/
			}
			$file .= '</tr>';
		}
		$file .= '</table>';

		$fecha = date("Y-m-d");
		header('Content-disposition: attachment; filename=Reporte_InquiroVitae_' . $fecha . '.xls');
		header('Content-type: application/vnd.ms-excel; charset=utf-8');

		$file = utf8_decode($file); 
		$response =  array(
			'op' => 'ok',
			'archivo' => 'Reporte_InquiroVitae_' . $fecha . '.xls', 
			'file' => "data:application/vnd.ms-excel;base64,".base64_encode($file)
		);
		die(json_encode($response));
	}



	public static function ivNuevaBusqueda() 
	{
		$cliente = Session::get('usuario')->cliente['client_id'];
		//$prod = SQLConnection::backendStoreProcedure('IV_panel_control', array('productos', $cliente), 'select');

		$id_tipo_informe = !empty(Request::input('id_tipo_informe')) ? Request::input('id_tipo_informe') : NULL;
		$id_padron = !empty(Request::input('id_padron')) ? Request::input('id_padron') : NULL;

		$familia = !empty(Request::input('familia')) ? Request::input('familia') : NULL;
		$referencia = !empty(Request::input('referencia')) ? Request::input('referencia') : NULL;
		$ref = !empty(Request::input('ref')) ? Request::input('ref') : NULL;
		$ref_nombre = !empty(Request::input('ref_nombre')) ? Request::input('ref_nombre') : NULL;
		$ref_seccion = !empty(Request::input('ref_seccion')) ? Request::input('ref_seccion') : NULL;
		$ref_cargo = !empty(Request::input('ref_cargo')) ? Request::input('ref_cargo') : NULL;
		$email_candidato  = !empty(Request::input('email_candidato')) ? Request::input('email_candidato') : NULL;
		$telefono_candidato  = !empty(Request::input('telefono_candidato')) ? Request::input('telefono_candidato') : NULL;
		$notas_candidato  = !empty(Request::input('notas_candidato')) ? Request::input('notas_candidato') : NULL;


		$familias = SQLConnection::backendStoreProcedure('LN_familias_', array('inquirovitae', null, null, $cliente, null, 1, null), 'select');
		$prod = SQLConnection::backendStoreProcedure('IV_panel_control', array('productos_backend', NULL, Session::get('usuario')->user_id, env('IV_PRODUCTO')), 'select');
/*
		var_dump('IV_panel_control');
		var_dump('<br>');

		var_dump('productos_backend');
		var_dump('<br>');

		
		var_dump('NULL');
		var_dump('<br>');

		var_dump(Session::get('usuario')->user_id);
		var_dump('<br>');

		var_dump(env('IV_PRODUCTO'));
		var_dump('<br>');

		
		
		
		var_dump($prod);
		
		
		die();
*/

		return view('/iv/iv_nueva_busqueda')->with(compact(['prod', 'familias', 'id_tipo_informe', 'id_padron', 'familia', 'referencia', 'ref', 'ref_nombre', 'ref_seccion', 'ref_cargo', 'email_candidato', 'telefono_candidato', 'notas_candidato']));
	}

	public static function ivBusquedaCandidato() {
		$id_tipo_informe = !empty(Request::input('id_tipo_informe')) ? Request::input('id_tipo_informe') : NULL;
 		$id_padron = !empty(Request::input('id_padron')) ? Request::input('id_padron') : NULL;

		$familia = !empty(Request::input('familia')) ? Request::input('familia') : NULL;
		$referencia = !empty(Request::input('referencia')) ? Request::input('referencia') : NULL;
		$ref = !empty(Request::input('ref')) ? Request::input('ref') : NULL;
		$ref_nombre = !empty(Request::input('ref_nombre')) ? Request::input('ref_nombre') : NULL;
		$ref_seccion = !empty(Request::input('ref_seccion')) ? Request::input('ref_seccion') : NULL;
		$ref_cargo = !empty(Request::input('ref_cargo')) ? Request::input('ref_cargo') : NULL;
		$email_candidato  = !empty(Request::input('email_candidato')) ? Request::input('email_candidato') : NULL;
		$telefono_candidato  = !empty(Request::input('telefono_candidato')) ? Request::input('telefono_candidato') : NULL;
		$notas_candidato  = !empty(Request::input('notas_candidato')) ? Request::input('notas_candidato') : NULL;

		
		$persona = null;
		if ($id_padron != null) {
			$persona = SQLConnection::backendStoreProcedure('backend_obtener_id_padron', array($id_padron), 'selectOne');
		}
		//----- 5/10/2021
		$paises = SQLConnection::backendStoreProcedure('backend_obtener_paises',array(),'select');
		//-----
		return view('/iv/iv_busqueda_candidato')->with(compact(['id_tipo_informe', 'id_padron', 'persona', 'familia', 'referencia', 'ref', 'ref_nombre', 'ref_seccion', 'ref_cargo', 'email_candidato', 'telefono_candidato', 'notas_candidato','paises']));;	
	}

	public static function ivBusquedaPadron() {
		$data = [];
		$search = !empty(Request::input('input_search')) ? Request::input('input_search') : NULL;
		if (null != $search) {
			$data = SQLConnection::busquedaPadronAutocomplete($search, true);
		}
		return view('/iv/iv_tabla_busqueda_padron')->with(compact(['data']));
	}

	public static function ivDatosBusqueda() {
		$familia = !empty(Request::input('familia')) ? Request::input('familia') : NULL;
		$id_tipo_informe = !empty(Request::input('id_tipo_informe')) ? Request::input('id_tipo_informe') : NULL;
		$id_padron = !empty(Request::input('id_padron')) ? Request::input('id_padron') : NULL;

		$cliente = Session::get('usuario')->cliente['client_id'];
		$familias = SQLConnection::backendStoreProcedure('LN_familias_', array('inquirovitae', null, null, $cliente, null, 1, null), 'select');

		$referencia = !empty(Request::input('referencia')) ? Request::input('referencia') : NULL;
		$ref = !empty(Request::input('ref')) ? Request::input('ref') : NULL;
		$ref_nombre = !empty(Request::input('ref_nombre')) ? Request::input('ref_nombre') : NULL;
		$ref_seccion = !empty(Request::input('ref_seccion')) ? Request::input('ref_seccion') : NULL;
		$ref_cargo = !empty(Request::input('ref_cargo')) ? Request::input('ref_cargo') : NULL;
		$email_candidato  = !empty(Request::input('email_candidato')) ? Request::input('email_candidato') : NULL;
		$telefono_candidato  = !empty(Request::input('telefono_candidato')) ? Request::input('telefono_candidato') : NULL;
		$notas_candidato  = !empty(Request::input('notas_candidato')) ? Request::input('notas_candidato') : NULL;
		//-------- VARIABLE IMPORTANTE PARA DETERMINAR SI EL USUARIO YA FUE AVISADO QUE EXISTE LA CONTRAPARTE EN EL PANEL Y LO QUIERE DAR DE ALTA DE VUELTA
		$candidato_repetir = !empty(Request::input('nueva_repeticion')) ? Request::input('nueva_repeticion') : NULL;
		//--------
		if ($id_tipo_informe != null) {
			$tipoinforme = SQLConnection::backendStoreProcedure('LN_informes', array('tipo_informe', NULL, NULL, NULL, NULL, NULL, $id_tipo_informe), 'selectOne');
		}
		if ($id_padron != null) {
			$persona = SQLConnection::backendStoreProcedure('backend_obtener_id_padron', array($id_padron), 'selectOne');
		}
		$referencias = SQLConnection::backendStoreProcedure('IV_panel_control', array('referencias', Session::get('usuario')->cliente['client_id']), 'select');
		$file_name = null;
		$file_url = null;
		$dircliente = env('PATH_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id;
		if (is_dir($dircliente)) {
			$dirhandle = opendir($dircliente);
			if ($dirhandle) {
				while (($archivo = readdir($dirhandle)) !== false) {
					if (is_file( env('PATH_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id. '/' . $archivo )) {
						$file_name = $archivo;
						$file_url = env('RUTA_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id. '/' . $archivo;
						break;
					}
				}
			}
		}

/* 25/01/2021 esto estaba en produccion, pero no en desarrollo .... */
		$n = SQLConnection::backendStoreProcedure('LN_informes', array('tipos_informe_cliente', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Session::get('usuario')->cliente['client_id']));
		$resultado = SQLConnection::backendStoreProcedure('backend_contratos_consumos', array(Session::get('usuario')->cliente['client_id'], self::depurador_contador_consumo($n, $id_tipo_informe)));
		
		foreach ($resultado as $key) {
			$consumido = ($key->consumido != null) ? $key->consumido : '0';
			$disponible = ($key->disponible != null) ? $key->disponible : '0';
		}
/* */ 		
/* 25/01/2021 se cambio el return .... */
		/*return view('/iv/iv_datos_busqueda')->with(compact(['familia', 'tipoinforme', 'persona', 'familias', 'familia', 'referencias', 'referencia', 'ref', 'ref_nombre', 'ref_seccion', 'ref_cargo', 'email_candidato', 'telefono_candidato', 'notas_candidato','file_name', 'file_url']));*/
		//---- MODIFICACION 18/10/2021
		if (!isset($candidato_repetir)){
			$user_id = Session::get('usuario')->user_id;
			$servicio = Session::get('servicio_actual');
			//----
			$indicadores = SQLConnection::backendStoreProcedure('IV_panel_control', array('indicadores_panel_controlr', $cliente, $user_id), 'select');
			$datoscontrap = SQLConnection::backendStoreProcedure('LN_contrapartes_sc',array('search',null,$id_padron,$cliente,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$servicio));
			//----- PROCESO DE CONOCER SI EL CANDIDATO YA EXISTE
			$registros_finalizados = [];
			$registros_en_proceso = [];
			//-----
			if (sizeof($datoscontrap) == 0){
				return view('/iv/iv_datos_busqueda')->with(compact(['familia', 'tipoinforme', 'persona', 'familias', 'familia', 'referencias', 'referencia', 'ref', 'ref_nombre', 'ref_seccion', 'ref_cargo', 'email_candidato', 'telefono_candidato', 'notas_candidato','file_name', 'file_url', 'consumido', 'disponible']));	
			}
			//-----
			else{
				foreach ($datoscontrap as $key => $value){
					foreach ( $indicadores as $clave => $valor ){
						//--- SI LA CONTRAPARTE ESTA EN PROCESO
						if ( $value->contraparte == $valor->contraparte and $valor->visible == 0 ){
							if ( !in_array($value,$registros_en_proceso) ){
								$value->created = date_format(date_create_from_format('Y-m-d H:i:s', $value->created),'d-m-Y');
								$value->created = str_replace('-','/',$value->created);
								array_push($registros_en_proceso,$value);
							}
						}
						//--- SI LA CONTRAPARTE ESTA FINALIZADA
						elseif ( $value->contraparte == $valor->contraparte and $valor->visible == 1 ){
							if ( !in_array($value,$registros_finalizados) ){
								$value->created = date_format(date_create_from_format('Y-m-d H:i:s', $value->created),'d-m-Y');
								$value->created = str_replace('-','/',$value->created);
								array_push($registros_finalizados,$value);
							}
						}
						//----
					}
				}
				//-------
				return view('/iv/iv_datos_busqueda_existente')->with(compact(['persona','registros_finalizados','registros_en_proceso','familia', 'id_tipo_informe', 'id_padron', 'referencias', 'referencia', 'ref', 'ref_nombre', 'ref_seccion', 'ref_cargo', 'email_candidato', 'telefono_candidato', 'notas_candidato','file_name', 'file_url', 'consumido', 'disponible']));
			}

		}
		else{
			return view('/iv/iv_datos_busqueda')->with(compact(['familia', 'tipoinforme', 'persona', 'familias', 'familia', 'referencias', 'referencia', 'ref', 'ref_nombre', 'ref_seccion', 'ref_cargo', 'email_candidato', 'telefono_candidato', 'notas_candidato','file_name', 'file_url', 'consumido', 'disponible']));	
		}
		//return view('/iv/iv_datos_busqueda')->with(compact(['familia', 'tipoinforme', 'persona', 'familias', 'familia', 'referencias', 'referencia', 'ref', 'ref_nombre', 'ref_seccion', 'ref_cargo', 'email_candidato', 'telefono_candidato', 'notas_candidato','file_name', 'file_url', 'consumido', 'disponible']));
	}

/* 25/01/2021 esto estaba en produccion, pero no en desarrollo .... */
//--  METODO DEPURADOR PARA OBTENER CONSUMOS, USADO POR EL METODO 'ivDatosBusqueda'  --//
	static function depurador_contador_consumo($resuktado_store, $id_tipo_informe) {
		$nuevo = array();

		foreach($resuktado_store as $key) {
			$nuevo[$key->id_tipo_informe] = $key->item_contrato;
		}

		foreach($nuevo as $key => $value) {
			if($key == $id_tipo_informe) {
				return $value;
			}
		}
		return 0;
	}
/* */ 

	public static function ivSubirCv() {
		$cliente = Session::get('usuario')->cliente['client_id'];

		$id_tipo_informe = !empty(Request::input('id_tipo_informe')) ? Request::input('id_tipo_informe') : NULL;
		$id_padron = !empty(Request::input('id_padron')) ? Request::input('id_padron') : NULL;

		$familia = !empty(Request::input('familia')) ? Request::input('familia') : NULL;
		$referencia = !empty(Request::input('referencia')) ? Request::input('referencia') : NULL;
		$ref = !empty(Request::input('ref')) ? Request::input('ref') : NULL;
		$ref_nombre = !empty(Request::input('ref_nombre')) ? Request::input('ref_nombre') : NULL;
		$ref_seccion = !empty(Request::input('ref_seccion')) ? Request::input('ref_seccion') : NULL;
		$ref_cargo = !empty(Request::input('ref_cargo')) ? Request::input('ref_cargo') : NULL;
		$email_candidato  = !empty(Request::input('email_candidato')) ? Request::input('email_candidato') : NULL;
		$telefono_candidato  = !empty(Request::input('telefono_candidato')) ? Request::input('telefono_candidato') : NULL;
		$notas_candidato  = !empty(Request::input('notas_candidato')) ? Request::input('notas_candidato') : NULL;


		if ($id_tipo_informe != null) {
			$tipoinforme = SQLConnection::backendStoreProcedure('LN_informes', array('tipo_informe', NULL, NULL, NULL, NULL, NULL, $id_tipo_informe), 'selectOne');
		}
		if ($id_padron != null) {
			$persona = SQLConnection::backendStoreProcedure('backend_obtener_id_padron', array($id_padron), 'selectOne');
		}

		$file_name = null;
		$file_url = null;
		$dircliente = env('PATH_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id;
		if (is_dir($dircliente)) {
			$dirhandle = opendir($dircliente);
			if ($dirhandle) {
				while (($archivo = readdir($dirhandle)) !== false) {
					if (is_file( env('PATH_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id. '/' . $archivo )) {
						$file_name = $archivo;
						$file_url = env('RUTA_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id. '/' . $archivo;
						break;
					}
				}
			}
		}
		return view('/iv/iv_subir_cv')->with(compact(['tipoinforme', 'persona', 'familia', 'referencia', 'ref', 'ref_nombre', 'ref_seccion', 'ref_cargo', 'email_candidato', 'telefono_candidato', 'notas_candidato', 'file_name', 'file_url']));
	}


	public static function ivUploadFile() {

		$cliente = Session::get('usuario')->cliente['client_id'];

		if(!empty($_FILES['archivo']) && $_FILES['archivo']['name'] !== '') {

			$userfile_name = $_FILES['archivo']['name'];
			$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);
			$file_url = env('RUTA_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id. '/' . $userfile_name;

			$ftype = strtolower($userfile_extn); 

			if($ftype !== 'pdf' and $ftype !== 'doc' and $ftype !== 'docx') {
				$rslt = 5;
				$msg = 'El tipo de archivo especificado no está permitido. - Por favor ingrese un archivo del tipo PDF o Word.';
				return json_encode(array( 'error' => $rslt , 'mensaje' => $msg , 'archivo' => $file_url, 'nombre' => $userfile_name));
			}

			if( basename($userfile_name) != '' ) {

				/* Creacion de la carpeta del cliente para el storage de IV */
				$path_cli = env('PATH_DOCUMENTOS_IV') . '/' . $cliente;
				if (!is_dir( $path_cli )) {
			    	$carpeta_cliente = mkdir( $path_cli );
				}
				else {
					$carpeta_cliente = true;	
				}

				/* Creacion de la carpeta temporaria del cliente / usuario para el storage de IV */
				$path_temp = env('PATH_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id;
				if (!is_dir( $path_temp )) {
			    	$carpeta_cliente_temp = mkdir( $path_temp , 0777, true );
				}
				else {
					$carpeta_cliente_temp = true;	
				}


				if($carpeta_cliente AND $carpeta_cliente_temp) {

					// Como todavía no creé la carpeta de la contraparte, va a la carpeta temporal 

					// Vacío la carpeta temporal del cliente
					$dirhandle = opendir($path_temp);
					if ($dirhandle) {
						while (($archivo_preexistente = readdir($dirhandle)) !== false) {
							if (is_file( $path_temp . '/' . $archivo_preexistente )) {
								unlink( $path_temp . '/' . $archivo_preexistente );
							}
						}
					}

					$path = env('PATH_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id. '/' . $userfile_name;


					if(move_uploaded_file($_FILES['archivo']['tmp_name'], $path)) {
						$rslt = 0;
						$msg = 'Archivo subido exitosamente';

						$file_name = $userfile_name;
						$form = \View::make('/iv/iv_buscar_cv_temp')->with(compact(['file_name', 'file_url']))->render();

						return \Response::json(array( 'error' => $rslt ,
																	'mensaje' => $msg , 
																	'archivo' => $file_url, 
																	'nombre' => $userfile_name, 
																	'formulario' => $form),
															200,
															[],
															JSON_NUMERIC_CHECK);
					}
					else {
						$rslt = 4;
						$msg = 'No se pudo guardar el archivo seleccionado.';
						return json_encode(array( 'error' => $rslt , 'mensaje' => $msg , 'archivo' => $file_url, 'nombre' => $userfile_name));										
					}

				}
				else {
					$rslt = 3;
					$msg = 'No se pudo crear la carpeta correspondiente para almacenar el archivo.';
					return json_encode(array( 'error' => $rslt , 'mensaje' => $msg , 'archivo' => $file_url, 'nombre' => $userfile_name));
				}
			}
			else {
				$rslt = 2;
				$msg = 'El nombre del archivo especificado es inválido.';
				return json_encode(array( 'error' => $rslt , 'mensaje' => $msg , 'archivo' => $file_url, 'nombre' => $userfile_name));
			}
		}
		else {
			$rslt = 1;
			$msg = 'No se ha especificado el archivo a subir.';
			return json_encode(array( 'error' => $rslt , 'mensaje' => $msg , 'archivo' => NULL, 'nombre' => NULL));
		}

	}


	public static function ivBuscarCvTemp() {
		$cliente = Session::get('usuario')->cliente['client_id'];
		$dircliente = env('PATH_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id;

		$file_name = null;
		$file_url = null;
		if (is_dir($dircliente)) {
			$dirhandle = opendir($dircliente);
			if ($dirhandle) {
				while (($archivo = readdir($dirhandle)) !== false) {
					if (is_file( $dircliente . '/' . $archivo )) {
						$file_name = $archivo;
						$file_url = env('RUTA_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id. '/' . $archivo;
						break;
					}
				}
			}
		}

		return view('/iv/iv_buscar_cv_temp')->with(compact(['file_name', 'file_url']));
	}


	public static function ivDeleteFile() {
		$cliente = Session::get('usuario')->cliente['client_id'];
		$dircliente = env('PATH_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id;

		$rslt = 0;
		$msg = '';

		if (is_dir($dircliente)) {

			$dirhandle = opendir($dircliente);

			if ($dirhandle) {
				while (($archivo = readdir($dirhandle)) !== false) {
					if (is_file( $dircliente . '/' . $archivo )) {
						unlink( $dircliente . '/' . $archivo );
						$rslt = 0;
						$msg = "Archivo eliminado.";
						break;
					}
				}
			}
		}

		return \Response::json(array( 'error' => $rslt ,
													'mensaje' => $msg , 
													'formulario' => NULL),
											200,
											[],
											JSON_NUMERIC_CHECK);

	}


	public static function ivIngresarBusqueda() {
		$cliente = Session::get('usuario')->cliente['client_id'];

		$id_tipo_informe = !empty(Request::input('id_tipo_informe')) ? Request::input('id_tipo_informe') : NULL;
		$id_padron = !empty(Request::input('id_padron')) ? Request::input('id_padron') : NULL;

		$familia = !empty(Request::input('familia')) ? Request::input('familia') : NULL;
		$referencia = !empty(Request::input('referencia')) ? Request::input('referencia') : NULL;
		$ref = !empty(Request::input('ref')) ? Request::input('ref') : NULL;
		$ref_nombre = !empty(Request::input('ref_nombre')) ? Request::input('ref_nombre') : NULL;
		$ref_seccion = !empty(Request::input('ref_seccion')) ? Request::input('ref_seccion') : NULL;
		$ref_cargo = !empty(Request::input('ref_cargo')) ? Request::input('ref_cargo') : NULL;
		$email_candidato  = !empty(Request::input('email_candidato')) ? Request::input('email_candidato') : NULL;
		$telefono_candidato  = !empty(Request::input('telefono_candidato')) ? Request::input('telefono_candidato') : NULL;
		$notas_candidato  = !empty(Request::input('notas_candidato')) ? Request::input('notas_candidato') : NULL;
		//------- SECCION PRUEBA
		//------- FIN DE SECCION PRUEBA
		if ($cliente != null AND $id_tipo_informe != null AND $id_padron != null AND $familia != null) {

			$params = array('ingresar_busqueda', 
										$cliente,
										Session::get('usuario')->user_id,
										env('IV_PRODUCTO'),
										$id_tipo_informe,
										$id_padron,
										$familia,
										$referencia,
										$ref,
										$ref_nombre,
										$ref_seccion,
										$ref_cargo,
										$email_candidato,
										$telefono_candidato,
										$notas_candidato,
										env('FILIAL_DEFAULT'),
										env('IDIOMA_DEFAULT'),
										env('DATAMANAGER_DEFAULT'),
										env('ASIGNADO_DEFAULT'),
										env('ESTADO_INFORME_INICIAL'));

			$nueva_busqueda = SQLConnection::backendStoreProcedure('IV_panel_control', $params, 'selectOne');
			/* Ese SP lo manda al queue */

			if (!empty($nueva_busqueda)) {

				$rootcliente = env('PATH_DOCUMENTOS_IV') . '/' . $cliente;
				$dir_temp = env('PATH_DOCUMENTOS_IV_TEMP') . '/' . $cliente . '/' . Session::get('usuario')->user_id;

				$path_legajo = $rootcliente . '/' . $nueva_busqueda->contraparte . '/' . $nueva_busqueda->gestion;
		    	$legajo = mkdir( $path_legajo , 0777, true );

		    	if ($legajo) {

		    		/* Copiar el CV en la carpeta temporal al legajo del candidato */
					if (is_dir($dir_temp)) {
						$dirhandle = opendir($dir_temp);
						if ($dirhandle) {
							while (($archivo = readdir($dirhandle)) !== false) {
								if (is_file( $dir_temp . '/' . $archivo )) {

									$target_name = str_pad($nueva_busqueda->iv_busqueda, 8, '0', STR_PAD_LEFT) . '_' . str_replace(' ', '_', $archivo);
									if (copy( $dir_temp . '/' . $archivo , $path_legajo . '/' . $target_name )) {

										unlink( $dir_temp . '/' . $archivo );

										$temp = SQLConnection::backendStoreProcedure('IV_busquedas_', array('subir_cv', $nueva_busqueda->iv_busqueda), 'selectOne');
									}

								}
							}
						}
					}

					$err = 0;
					$msg = "La búsqueda se ingresó correctamente.";
		    	}
		    	else {
					$err = 3;
					$msg = "No se ha podido generar la carpeta de documentos para el candidato.";
		    	}
			}
			else {
				$err = 2;
				$msg = "No se ha podido generar la búsqueda. Por favor reintente.";
			}
		}
		else {
			$err = 1;
			$msg = "Parámetros incorrectos.";
		}

		//------ MODIFICACION 12/10/2021
		$padron  = DB::selectOne('EXEC dbo.backend_obtener_id_padron '.$id_padron);
		$servicio = Session::get('servicio_actual');
		$datoscontrap = SQLConnection::backendStoreProcedure('LN_contrapartes_sc',array('search',null,$id_padron,$cliente,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$servicio));
		$contraparte = end($datoscontrap)->contraparte;
		$nombre_completo = $datoscontrap[0]->nombre_persona;
		//----
		if ($padron->country_code == 'AR'){
			$indicador_comercial_legal = Misc::CURLCall(env('API_SCORE_INFORME_COMERCIAL'),'cuit='.$padron->numero.'&cliente='.$cliente);
			$indicador_comercial_legal = json_decode($indicador_comercial_legal);
			$indicador_compilance = Misc::CURLCall(env('API_SCORE_FIDECHECK_COMPLIANCE'),'apikey=1F44A3FAA0C15C42PEP2&country_code='.$padron->country_code.'&tax_id='.$padron->numero.'&full_name='.$nombre_completo);
			$indicador_compilance = json_decode($indicador_compilance);
			$indicador_compilance = $indicador_compilance->response[0];
			//----- ESCALA DE SECCION COMERCIAL/LEGAL
			if ($indicador_comercial_legal->score >= 0 and $indicador_comercial_legal->score <= 44){
				$score_comercial_legal = 'N';	
			}
			elseif ($indicador_comercial_legal->score >= 45 and $indicador_comercial_legal->score <= 69){
				$score_comercial_legal = 'O';	
			}
			elseif ($indicador_comercial_legal->score >= 70 and $indicador_comercial_legal->score <= 100){
				$score_comercial_legal = 'P';	
			}
			//---------
			$comercial_legal = SQLConnection::backendStoreProcedure('IV_panel_control', array('actualizar_indicador',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,$contraparte,'COMERCIAL_LEGAL',$score_comercial_legal), 'selectOne');
			//------- ESCALA DE SECCION COMPLIANCE
			if ( is_object($indicador_compilance) ){
				if ($indicador_compilance->fidecheck == 'NEGATIVO' or $indicador_compilance->fidecheck == 'SUJETO OBLIGADO'){
					$score_compliance = 'P';
				}
				elseif($indicador_compilance->fidecheck == 'PEP' or $indicador_compilance->fidecheck == 'SANCIONADO' or $indicador_compilance->fidecheck == 'TERRORISTA'){
					$score_compliance = 'N';
				}
				else{
					$score_compliance = 'O';
				}
				//-------
				$compliance = SQLConnection::backendStoreProcedure('IV_panel_control', array('actualizar_indicador',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,$contraparte,'COMPLIANCE',$score_compliance), 'selectOne');
			}
			
		}
		//------ FIN DE MODIFICACION
		return \Response::json(array('error'=>$err, 'mensaje'=>$msg));

	}


	public static function ivDatosCandidato() {
		$iv_busqueda = Request::input('iv_busqueda');
		$contraparte = Request::input('contraparte');
		// este es el nombre del index (valor texto) de la columna clickeada en la fancy.
		$column = Request::input('column');
		$contrap = SQLConnection::backendStoreProcedure('LN_contrapartes_', array('select', $contraparte, null, null, null, null, null, null, null, null, null, null, null, null, Session::get('usuario')->user_id), 'selectOne');
		$familia = SQLConnection::backendStoreProcedure('LN_contraparte_familias_', array('search', $contraparte, null, null, null, null, null), 'selectOne');
		$busqueda = SQLConnection::backendStoreProcedure('IV_busquedas_', array('search', $iv_busqueda), 'selectOne');

		$files = self::getIVFiles($iv_busqueda);
		$cv_exists = $files['cv_exists'];
		$cv_full_url = $files['cv_full_url'];
		$foto_exists = $files['foto_exists'];
		$foto_full_url = $files['foto_full_url'];

		$iv_exists = FALSE;
		$iv_full_url = NULL;
        if ( $busqueda != null) {
            if (file_exists( env('PATH_DOSSIER_IV') . '/' . $busqueda->cliente . '/' . $busqueda->contraparte . '/' . $busqueda->contraparte . '_' . $busqueda->gestion . '.pdf' )) {
                $iv_exists = TRUE;
                $iv_full_url = env('RUTA_DOSSIER_IV') . '/' . $busqueda->cliente . '/' . $busqueda->contraparte . '/' . $busqueda->contraparte . '_' . $busqueda->gestion . '.pdf?rnd=' . time();
            }
        }
		

		$indicadores = SQLConnection::backendStoreProcedure('IV_panel_control', array('obtener_indicadores',null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,$contraparte), 'select');

		/*---------------------------------------------------------------*/
		// 25/09/2020
		// sacamos los indicadores que el usuario tiene restringidos para que no se vean 
	
		$usuarios_restricciones = Session::get('usuarios_restricciones');
		$servicio_actual = Session::get('servicio_actual');
		if(!empty($usuarios_restricciones)){
			foreach ($usuarios_restricciones as $key_ur => $value_ur) {
				if($servicio_actual == $key_ur){
					foreach ($value_ur as $key_n2 => $value_n2) {
						foreach ($indicadores as $key => $value) {
							if ($value->indicador == $value_n2->indicador)
								{
									unset ($indicadores[$key]);
								}
						}
					}
				}
			}
		}
//var_dump($indicadores); die(); 
		$vista = \View::make('/iv/iv_datos_candidato')->with(compact(['contrap', 'familia', 'busqueda', 'column', 'cv_exists', 'cv_full_url', 'foto_exists', 'foto_full_url', 'iv_exists', 'iv_full_url', 'indicadores']))->render();

		return json_encode(array('nombre_persona' => $contrap->nombre_persona,
												'abreviatura' => $contrap->abreviatura,
												'identificacion' => $contrap->identificacion,
												'country' =>  '<span class="flag-icon flag-icon-background flag-icon-' . strtolower($contrap->country_code) . '"></span>',
												'vista' => $vista));

	}


	public static function getIVFiles($iv_busqueda = null) {

		$cv_exists = FALSE;
		$cv_full_url = NULL;
		$foto_exists = FALSE;
		$foto_full_url = NULL;
		
		if (!empty($iv_busqueda)) {
			$pattern = str_pad($iv_busqueda, 8, '0', STR_PAD_LEFT) . '_*.*';
			$busqueda = SQLConnection::backendStoreProcedure('IV_busquedas_', array('search', $iv_busqueda), 'selectOne');
            if ( $busqueda != null) {
                // Buscar el archivo de CV -- puede ser PDF o Word  y la foto de perfil
                $rootpath = env('PATH_DOCUMENTOS_IV') . '/' . $busqueda->cliente . '/' . $busqueda->contraparte . '/' . $busqueda->gestion;
                            
                $foto_file = str_pad($iv_busqueda, 8, '0', STR_PAD_LEFT) . '_foto_120.jpg';
                $foto_full_url = env('RUTA_DOCUMENTOS_IV') . '/' . $busqueda->cliente . '/' . $busqueda->contraparte . '/' . $busqueda->gestion . '/' . $foto_file . '?r=' . time();

                if (is_dir($rootpath)) {
                    
                    $files = glob( $rootpath . '/' . $pattern );
                    foreach ($files as $f => $file) {
                        $extn = strtolower(substr($file, strrpos($file, '.') + 1));
                        
                        if ($cv_full_url == NULL) {
                            if ($extn == 'pdf' /*OR $extn == 'doc' OR $extn == 'docx'*/) {
                                $cv_file = basename($file);
                                
                                $cv_full_url = env('RUTA_DOCUMENTOS_IV') . '/' . $busqueda->cliente . '/' . $busqueda->contraparte . '/' . $busqueda->gestion . '/' . $cv_file . '?r=' . time();
                                $cv_exists = TRUE;
                            }
                        }
                        
                    }
                }
            }
		}

		return array('cv_exists' => $cv_exists, 'cv_full_url' => $cv_full_url, 'foto_exists' => $foto_exists, 'foto_full_url' => $foto_full_url);
	}


	public static function ivDatosCV() {
		$iv_busqueda = Request::input('iv_busqueda');

		$files = self::getIVFiles($iv_busqueda);
		$cv_exists = $files['cv_exists'];
		$cv_full_url = $files['cv_full_url'];
		$foto_exists = $files['foto_exists'];
		$foto_full_url = $files['foto_full_url'];

		return view('/iv/iv_datos_cv')->with(compact(['files']));
	}

	public static function ivDatosAnexos() {
		$iv_busqueda = Request::input('iv_busqueda');
		$contraparte = Request::input('contraparte');
		$busqueda = SQLConnection::backendStoreProcedure('IV_busquedas_', array('search', $iv_busqueda), 'selectOne');

		$docs = DB::select('EXEC dbo.LN_contrapartes_ ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?', array('DOCUMENTOS_GESTION_ACTIVA', $contraparte, null, null, null, null, null, null, null, null, null, null, null, null, null));

		$cumpldoc = SQLConnection::backendStoreProcedure('LN_dashboard_cliente', array('indicadores_contraparte',null,null,null,$contraparte,'CUMPL_DOC'), 'selectOne');


		$files = [];
		$n = -1;
		foreach ($docs as $k => $doc) {
			if ($doc->estado_doc == 'N' || $doc->estado_doc == 'I' || $doc->estado_doc == 'R' || $doc->estado_doc == 'V') {
				$n++;
				$file_path = env('PATH_DOCUMENTOS') . '/' . $doc->cliente . '/' . $doc->contraparte . '/' . $doc->gestion . '/' . $doc->doc_id . '.pdf';
				$file_url = env('RUTA_DOCUMENTOS') . '/' . $doc->cliente . '/' . $doc->contraparte . '/' . $doc->gestion . '/' . $doc->doc_id . '.pdf' . '?rnd=' . time();

				$file_exists = file_exists($file_path);

				$files[$n]['path'] = $file_path;
				$files[$n]['url'] = $file_url;
				$files[$n]['exists'] = $file_exists;
			}
		}

		/* Traducciones de los nombres de documento */
		Traducciones::$blade = 'iv_datos_anexos';
		SQLConnection::obtenerTraducciones(Traducciones::$blade); 

		return view('/iv/iv_datos_anexos')->with(compact(['busqueda', 'docs', 'files', 'cumpldoc']));
	}


	public static function ivDatosInforme() {
		$iv_busqueda = Request::input('iv_busqueda');
		$contraparte = Request::input('contraparte');
		$busqueda = SQLConnection::backendStoreProcedure('IV_busquedas_', array('search', $iv_busqueda), 'selectOne');
		$informe = SQLConnection::backendStoreProcedure('IV_busquedas_', array('informe', $iv_busqueda), 'selectOne');

		$iv_exists = FALSE;
		$iv_full_url = NULL;

		if (file_exists( env('PATH_DOSSIER_IV') . '/' . $busqueda->cliente . '/' . $busqueda->contraparte . '/' . $busqueda->contraparte . '_' . $busqueda->gestion . '.pdf' )) {
			$iv_exists = TRUE;
			$iv_full_url = env('RUTA_DOSSIER_IV') . '/' . $busqueda->cliente . '/' . $busqueda->contraparte . '/' . $busqueda->contraparte . '_' . $busqueda->gestion . '.pdf' . '?rnd=' . time();
		}

		$valoracion = SQLConnection::backendStoreProcedure('LN_dashboard_cliente', array('indicadores_contraparte', $busqueda->cliente, null, null, $contraparte, 'VALORACION_IV'), 'selectOne'); 

		return view('/iv/iv_datos_informe')->with(compact(['busqueda', 'informe', 'valoracion', 'iv_exists', 'iv_full_url']));
	}

	public static function ivInformeComercial() {

		$id = Request::input('contraparte');
		$qcontrap = DB::selectOne('EXEC dbo.LN_contrapartes_ ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?', array('select', $id, null, null, null, null, null, null, null, null, null, null, null, null, null));
		//$prod = Request::input('producto');
		//$qproducto = SQLConnection::backendStoreProcedure('LN_productos_', array('select', $prod, null, null, null, null, null, null, null, null, null, null, null, null, null), 'selectOne');
		
		$apikey = env('API_KEY');

		return view('/iv/iv_informe_comercial')->with(compact('qcontrap', 'apikey'));
	}

	//--------------------------------------------------------------------------------------------------------//

	public static function ivDocsDetail() {
		$plain = null != Request::input('plain') ? Request::input('plain') : false;
		$carga = null != Request::input('carga') ? Request::input('carga') : false;
		$verifica = null != Request::input('verifica') ? Request::input('verifica') : false;

		// para que el botón de ver archivo apunte a abrir en un custom modal -- por ahora sólo usado desde panel de control Inquiro
		$custommodal = null != Request::input('custommodal') ? Request::input('custommodal') : false;

		$docid = Request::input('doc_id');

		$temp = SQLConnection::backendStoreProcedure('LN_doc_campos_', array('GENERATE', $docid, null, null, null, null, null, null, null, null), 'select');
		$doc = SQLConnection::backendStoreProcedure('LN_docs_', array('select', $docid, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null), 'selectOne');
		$flds = SQLConnection::backendStoreProcedure('LN_doc_campos_', array('search', $docid, null, null, null, null, null, null, null, null), 'select');

		//** Documento foto de Inquiro vitae
		$foto_perfil_url = NULL;
		if ($doc->es_foto_perfil > 0) {
			$busqueda = SQLConnection::backendStoreProcedure('IV_busquedas_', array('search', NULL, $doc->contraparte), 'selectOne');
			if (!empty($busqueda)) {
				$foto_perfil_url = env('RUTA_DOCUMENTOS_IV') . '/' . $busqueda->foto;
			}
		}


		$hay_campos = false;
		$hay_archivo = false;
		foreach ($flds as $fld) {
			$hay_campos = !$hay_campos ? ($fld->tipo_campo != 'F' ? true : $hay_campos) : $hay_campos;
			$hay_archivo = !$hay_archivo ? ($fld->tipo_campo == 'F' ? true : $hay_archivo) : $hay_archivo;
		}

		$secciones = [];

		$data = [];
		foreach ($flds as $k => $fld) {
			if ($fld->tipo_campo=='G') {

				/* encabezados de la tabla */
				$c1 = SQLConnection::backendStoreProcedure('LN_campos_col_', array('search', $fld->campo, null, null, null, null, null, null), 'select');
				$cols=[];
				foreach ($c1 as $clm) {
					$cols[] = $clm->etiqueta;
				}

				/* configuración de los campos y valores de la tabla */
				$c2 = SQLConnection::backendStoreProcedure('LN_doc_campos_col_', array($fld->doc_id, $fld->seccion, $fld->campo), 'select');
				$valores = [];
				foreach ($c2 as $k1 => $valor) {
					$valores[$valor->fila][$valor->col]['valor_texto'] = $valor->valor_texto;
					$valores[$valor->fila][$valor->col]['valor_fecha'] = $valor->valor_fecha;
					$valores[$valor->fila][$valor->col]['valor_fecha_str'] = $valor->valor_fecha_str;
					$valores[$valor->fila][$valor->col]['valor_numerico'] = $valor->valor_numerico;
					$valores[$valor->fila][$valor->col]['tipo_campo'] = $valor->tipo_campo;
					$valores[$valor->fila][$valor->col]['longitud'] = $valor->longitud;
					$valores[$valor->fila][$valor->col]['decimales'] = $valor->decimales;

					//$valores[$valor->fila][$valor->col]['opciones'] = $valor->opciones;

					if ($valor->tipo_campo == 'S' or $valor->tipo_campo == 'R' or $valor->tipo_campo == 'C') {
						if (strlen($valor->opciones) > 0) {
							$r = explode("^", $valor->opciones);
							$txt = [];
							$val = [];
							if (sizeof($r) >= 2) {
								$txt = explode("|", $r[0]);
								$val = explode("|", $r[1]);
							}
							$valores[$valor->fila][$valor->col]['opciones']['txt'] = $txt;
							$valores[$valor->fila][$valor->col]['opciones']['val'] = $val;
						}
					}
				}

				$fld->headers = $cols;
				$fld->values = $valores;
			} else {

				/* campo no tabla */

				if ($fld->tipo_campo == 'S' or $fld->tipo_campo == 'R' or $fld->tipo_campo == 'C') {
					$valores = [];

					if (strlen($fld->opciones) > 0) {
						$r = explode("^", $fld->opciones);
						$txt = [];
						$val = [];
						if (sizeof($r) >= 2) {
							$txt = explode("|", $r[0]);
							$val = explode("|", $r[1]);
						}
						$valores[] = $txt;
						$valores[] = $val;
					}

					$fld->opciones = $valores;
				}
			}

			$data[$fld->titulo_seccion][] = $fld;

			if ($fld->titulo_seccion != '') {
				$secciones[$fld->titulo_seccion]['texto_bajada'] = $fld->texto_bajada;
				$secciones[$fld->titulo_seccion]['texto_pie'] = $fld->texto_pie;
			}
		}

		if ($doc->es_balance > 0) {
			/*$file_path = env('PATH_BALANCES') . '/' . $doc->numero . '/' . $doc->id_externo . '.pdf';
			$file_url = env('RUTA_BALANCES') . '/' . $doc->numero . '/' . $doc->id_externo . '.pdf';	  */

			$file_path = env('PATH_COMPARTIDO') . '/' . $doc->ruta_archivo;
			$file_url = env('RUTA_COMPARTIDO') . '/' . $doc->ruta_archivo;
		} else {
			$file_path = env('PATH_DOCUMENTOS') . '/' . $doc->cliente . '/' . $doc->contraparte . '/' . $doc->gestion . '/' . $doc->doc_id . '.pdf';
			$file_url = env('RUTA_DOCUMENTOS') . '/' . $doc->cliente . '/' . $doc->contraparte . '/' . $doc->gestion . '/' . $doc->doc_id . '.pdf';
		}

		$file_exists = file_exists($file_path);

		$search_array = array( '%inicio_vigencia_fecha%' , '%fin_vigencia_fecha%' , '%inicio_vigencia_periodo%' , '%fin_vigencia_periodo%' );
		$replace_array = array( $doc->inicio_vigencia , $doc->fecha_vigencia , (null !== $doc->inicio_vigencia) ? substr($doc->inicio_vigencia, 3, 7) : null , (null !== $doc->fecha_vigencia) ? substr($doc->fecha_vigencia, 3, 7) : null );

		/* Traducciones de los nombres de documento */
		Traducciones::$blade = 'detalle documento';
		SQLConnection::obtenerTraducciones(Traducciones::$blade); 

		if ($carga === false and $verifica === false) { 
			return view('/led/led_doc_detail')->with(compact(['docid', 'doc', 'data', 'secciones', 'plain', 'file_path', 'file_url', 'file_exists', 'hay_campos', 'hay_archivo', 'search_array', 'replace_array', 'foto_perfil_url', 'custommodal']));
		}
		else {
			$mode = ($verifica !== false) ? 'readonly' : 'edit';
			return view('/led/led_carga_documentos_detalle')->with(compact(['docid', 'doc', 'data', 'secciones', 'plain', 'file_path', 'file_url', 'file_exists', 'hay_campos', 'hay_archivo', 'search_array', 'replace_array', 'foto_perfil_url', 'custommodal', 'mode']));
		}
  
	}


	//---- MODIFICACION 05/10/2021
	//------ FUNCION ENCARGADA DE AGARRAR EL CODIGO DEL PAIS Y DEVOLVER UNA LISTA DE TAX ID DEL PAIS
	public static function ivIdentificadorPais(){
		$cc = Request::input('country_code');
		$ident = Misc::identificadoresPais($cc);
		return json_encode($ident);
	}
	//------ FUNCION ENCARGADA DE CONSULTAR EL PADRON SOBRE UNA PERSONA CON TAX ID DEL EXTRANJERO Y DEVOLVERLO , SI TODOS LOS DATOS ESTAN INTRODUCIDOS LO DA DE ALTA
	public static function ivBusquedaPadronExtranjero(){
		//---
		$expReg_cuit = '/^[A-Za-z0-9ñÑ ]+$/';
		$expReg_nombre = '/^[A-Za-zñÑ ]+$/';
		$expReg_nombre2 = '/^[\s]+$/';
		//---
		$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 ( 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
		$vista = \View::make('/iv/iv_tabla_busqueda_padron')->with(compact(['data']))->render();
		return json_encode( array('view'=>$vista));
	}

}
