<?php namespace App\Http\Controllers;

use App\Custom\SQLConnection; 
use App\Custom\Misc;
use App\Custom\Mailer;
use App\Http\Controllers\AFIPController;
use Request;
use Session;
use DateTime;
use Illuminate\Support\Facades\Input;
use DB;
use stdClass;

class ImperiumAcceso extends Controller {
    
    
    public static function controlAcceso() { 
        
        $cli = Session::get('usuario')->cliente['client_id'];
        $usr = Session::get('usuario')->user_id;

        $locac = SQLConnection::backendStoreProcedure('Imperium_Usuario_Locaciones', array($cli, $usr), 'select');

        return view('/acceso/control_acceso')->with(compact(['cli','locac']));   
    }

    public static function buscarEmpleadoAcceso() {

        $cli = Session::get('usuario')->cliente['client_id'];
        $ayn = !empty(Request::input('nombre')) ? Request::input('nombre') : NULL;
        $num = !empty(Request::input('numero')) ? Request::input('numero') : NULL;
        $dominio = !empty(Request::input('dominio')) ? Request::input('dominio') : NULL;

        $loc = Request::input('locacion');

        /*
        var_dump($cli);
        var_dump($ayn);
        var_dump($num);
        var_dump($loc);
        */

        $empleados = SQLConnection::backendStoreProcedure('LN_Impe_buscar_empleado_acceso', array($cli, $ayn, $num, $loc), 'select');
        //var_dump($empleados); die(); 
        return json_encode( $empleados );
    }

    public static function buscarVehiculoAcceso() {

        $cli = Session::get('usuario')->cliente['client_id'];
        $dominio = !empty(Request::input('dominio')) ? Request::input('dominio') : NULL; 
        $loc = Request::input('locacion');

        /*
        var_dump($cli);
        var_dump($ayn);
        var_dump($num);
        var_dump($loc);
        */

        $vehiculoAcceso = SQLConnection::backendStoreProcedure('Imperium_buscar_vehiculos',array('dominio_buscar', NULL, NULL, NULL, NULL, NULL, $dominio), 'select');
//         'dominio_buscar',null,null,null,null,null,'AA133'
        
        return json_encode( $vehiculoAcceso );
    }
    

    // Chequear si una identificacion fiscal está asignada como empleado o contratista sin empleados o se encuentra en forma múltiple bajo el cliente.
    public static function controlAccesoCheck() {
        $cli = Session::get('usuario')->cliente['client_id'];
        $usr = Session::get('usuario')->user_id;

        $id_padron = Request::input('id_padron');
        $num = Request::input('numero');
        $dominio = !empty(Request::input('dominio')) ? Request::input('dominio') : NULL;
        $locacion = Request::input('locacion');
        $tipo_acceso = Request::input('tipo_acceso');
        $tipo_registro = Request::input('tipo_registro');
        $nombre_persona = Request::input('nombre');
        $identificacion = Request::input('numero');
        $identificador = Request::input('identificador');

        /* 28/03/2023: Controla que venga de Lista Blanca (W): Si viene por lista blanca, directamente autoriza el ingreso (sin chequear documentación) */
        if ($tipo_registro == 'W') 
        {

            return view('/acceso/identificacion_lista_blanca')->with(compact(['id_padron', 'locacion', 'tipo_acceso','nombre_persona','identificacion','identificador']));
        }
        
        // Busco el dato de la identificación fiscal dentro de los contratistas y empleados del cliente
        $acceso = SQLConnection::backendStoreProcedure('Imperium_buscar_identificacion_acceso', array($cli, $id_padron, $num), 'select');
        if (!empty($acceso)) {

            if (sizeof($acceso) > 1) {
                // Multiples ocurrencias               
                return view('/acceso/seleccion_recurso')->with(compact(['acceso', 'dominio', 'locacion', 'tipo_acceso']));
            } else{
                return view('/acceso/redirect_doc')->with(compact(['acceso', 'dominio', 'locacion', 'tipo_acceso']));
            }
        }
        else {
            return view('/acceso/identificacion_no_valida');
        }
    }



    public static function controlAccesoCheckDoc() {
        $cli = Session::get('usuario')->cliente['client_id'];

        $recurso = Request::input('recurso');
        $dominio = !empty(Request::input('dominio')) ? Request::input('dominio') : NULL;

        $locacion = Request::input('locacion');

        $reporte = !empty(Request::input('reporte')) ? Request::input('reporte') : "NO";

        $loc = SQLConnection::backendStoreProcedure('Imperium_buscar_locaciones', array(NULL, NULL, $locacion), 'selectOne');

        $tipo_acceso = Request::input('tipo_acceso');

        $data = explode('|', $recurso);

        // C o E
        $seccion = $data[0];

        // ID de contratista o ID de empleado
        $id = $data[1];

        $data_acceso = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso', array($cli, $locacion, $seccion, ($seccion == 'C' ? $id : NULL), ($seccion == 'E' ? $id : NULL)), 'selectOne');
        
        $docs = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Documentacion', array($seccion, $id), 'select');
        
        $pendientes = 0;
        foreach($docs as $d) { $d->estado_doc != 'V' ? $pendientes++ : $pendientes; }

        
        // Datos y acceso del vehículo en caso de haberse ingresado un dominio
        $data_vehiculo = NULL;
        $acceso_vehiculo = NULL;
        $docs_veh = NULL;
        $pendientes_veh = 0;
        if (!empty($dominio)) {
            $data_vehiculo = SQLConnection::backendStoreProcedure('Imperium_buscar_vehiculos', array('search', NULL, NULL, NULL, NULL, NULL, $dominio), 'selectOne');

            if(!empty($data_vehiculo)) {
                $acceso_vehiculo = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso', array($cli, $locacion, 'V', NULL, NULL, $data_vehiculo->vehiculo), 'selectOne');
                $docs_veh = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Documentacion', array('V', $data_vehiculo->vehiculo), 'select');
                foreach($docs_veh as $dv) { $dv->estado_doc != 'V' ? $pendientes_veh++ : $pendientes_veh; }
            }
        }
/*
        var_dump($id);
        var_dump("<br>");
        var_dump($loc);
        var_dump("<br>");
        var_dump($tipo_acceso);
        var_dump($seccion);
        var_dump("<br>");
        var_dump($data_acceso);
        var_dump("<br>");
        var_dump($docs);
        var_dump("<br>");
        var_dump($pendientes);
        var_dump("<br>");
        var_dump($dominio);
        var_dump("<br>");
        var_dump($data_vehiculo);
        var_dump("<br>");
        var_dump($acceso_vehiculo);
        var_dump("<br>");
        var_dump($docs_veh);
        var_dump("<br>");
        var_dump($pendientes_veh);
        var_dump("<br>");
        var_dump($reporte);
        var_dump("<br>");
        
        
        
        die();
*/


        return view('/acceso/confirmar_acceso')->with(compact(['loc', 'tipo_acceso', 'seccion', 'data_acceso', 'docs', 'pendientes', 'dominio', 'data_vehiculo', 'acceso_vehiculo', 'docs_veh', 'pendientes_veh', 'reporte']));

    }
    
    public static function controlAccesoConfirm() {
        $cli = Session::get('usuario')->cliente['client_id'];
        $usuario = Session::get('usuario')->user_id;
        $lista = ''; 
        return view('/acceso/control_acceso_confirm')->with(compact(['cli','usuario','lista']));
    }

    /* 28/03/2023: Viene de lista blanca (envia lista = 'W', para poder saber que form tomar al momento de confirmar el ingreso) */
    public static function controlAccesoConfirmWL() {
        $cli = Session::get('usuario')->cliente['client_id'];
        $usuario = Session::get('usuario')->user_id;
        $lista = 'W'; 
        return view('/acceso/control_acceso_confirm')->with(compact(['cli','usuario','lista']));
    }

    public static function registrarControlAcceso() {
        
        $rslt = 0;
        $cli = Session::get('usuario')->cliente['client_id'];
        $usuario = Session::get('usuario')->user_id;
        $locacion = Request::input('locacion');
        $tipo_acceso = Request::input('tipo_acceso');
        $contratista_1 = Request::input('contratista_1') ?? NULL;
        $contratista = Request::input('contratista') ?? NULL ;
        $empleado = Request::input('empleado') ?? NULL ;
        $vehiculo = Request::input('vehiculo') ?? NULL ;
        $detalle = '- Acceso controlado por: ' . Session::get('usuario')->first_name . ' ' . Session::get('usuario')->last_name . '. Fecha y hora: ' . date('d/m/Y H:i');
        
        /* 28/03/2023: Si tiene id_padron viene de Lista Blanca, se guarda con el id_padron */
        $id_padron = Request::input('id_padron') ?? NULL ;
        
        if ($id_padron !== NULL) 
            { $detalle .= ' (Autorizado por estar en Lista Blanca)'; }
        /* */

        $acceso = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Insert', array($cli, $locacion, $tipo_acceso, $usuario, $contratista, $empleado, $vehiculo, NULL, $detalle, 0, NULL, NULL, NULL, $id_padron), 'selectOne');
        
        return json_encode( array('result'=>$rslt, 'message'=>'Ok') );
    }

    public static function registrarControlAccesoAnterior() {
        $rslt = 0;

        $cli = Session::get('usuario')->cliente['client_id'];
        $usuario = Session::get('usuario')->user_id;
        $locacion = Request::input('locacion');
        $tipo_acceso = Request::input('tipo_acceso');
        $contratista_1 = Request::input('contratista_1');
        $contratista = Request::input('contratista');
        $empleado = !empty(Request::input('empleado')) ? Request::input('empleado') : NULL ;
        $vehiculo = !empty(Request::input('vehiculo')) ? Request::input('vehiculo') : NULL ;
        $detalle = 'Acceso controlado por: ' . Session::get('usuario')->first_name . ' ' . Session::get('usuario')->last_name . '. Fecha y hora: ' . date('d/m/Y H:i');
        $acceso = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Insert', array($cli, $locacion, $tipo_acceso, $usuario, $contratista, $empleado, $vehiculo, NULL, $detalle, 0), 'selectOne');
        
        return json_encode( array('result'=>$rslt, 'message'=>'Ok') );
    }
    
    public static function ingresoExcepcion() {
        $cli = Session::get('usuario')->cliente['client_id'];
        $usuario = Session::get('usuario')->user_id;
        $locacion = Request::input('locacion');
        $tipo_acceso = Request::input('tipo_acceso');
        $contratista_1 = Request::input('contratista_1');
        $contratista = Request::input('contratista');
        $empleado = !empty(Request::input('empleado')) ? Request::input('empleado') : NULL ;
        $vehiculo = !empty(Request::input('vehiculo')) ? Request::input('vehiculo') : NULL ;
        $dominio = Request::input('dominio');

        $loc = SQLConnection::backendStoreProcedure('Imperium_buscar_locaciones', array(NULL, NULL, $locacion), 'selectOne');
        $seccion = !empty($empleado) ? 'E' : 'C';
        $id = ($empleado ?? $contratista);

        $data_acceso = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso', array($cli, $locacion, $seccion, ($seccion == 'C' ? $id : NULL), ($seccion == 'E' ? $id : NULL)), 'selectOne');
        $docs = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Documentacion', array($seccion, $id), 'select');

        $data_vehiculo = NULL;
        $acceso_vehiculo = NULL;
        $docs_veh = NULL;
        if (!empty($vehiculo)) {
            $data_vehiculo = SQLConnection::backendStoreProcedure('Imperium_buscar_vehiculos', array('search', $vehiculo), 'selectOne');
            $acceso_vehiculo = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso', array($cli, $locacion, 'V', NULL, NULL, $vehiculo), 'selectOne');
            $docs_veh = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Documentacion', array('V', $vehiculo), 'select');
        }
/*
        $personal = DB::select("select led_cliente_personal.* 
                                from led_cliente_personal
                                where cliente = " . $cli .
                                " and locacion = " . $locacion .
                                " and activo = 'A' and autoriza_ingreso = 1" .
                                " order by nombre_completo");
*/
        $personal = DB::select("select led_cliente_personal.* from led_cliente_personal where persona = 50");

        return view('/acceso/ingresar_excepcion')->with(compact(['cli','usuario','loc','tipo_acceso','seccion','id','data_acceso','docs','data_vehiculo','acceso_vehiculo','docs_veh', 'personal']));
    }

     /*--------------- FUNCION PARA ENVIAR EMAIL DESDE EL BOTON SOLICITUD DE EXCEPCION --------- */
     public static function solicitudExcepcion(){
        $cli = Session::get('usuario')->cliente['client_id'];
        $usuario = Session::get('usuario')->user_id;
        $locacion = Request::input('locacion');
        $tipo_acceso = Request::input('tipo_acceso');
        $contratista_1 = Request::input('contratista_1');
        $contratista = Request::input('contratista');
        $empleado = !empty(Request::input('empleado')) ? Request::input('empleado') : NULL ;
        $vehiculo = !empty(Request::input('vehiculo')) ? Request::input('vehiculo') : NULL ;
        $persona = Request::input('persona');
        $detalle = Request::Input('detalle_control') ?? '';
        $vigencia = Misc::unaHoraMas();
        
        //GENERAMOS EL INGRESO CON LOS DATOS DEL FORM
        $acceso = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Insert', array($cli, $locacion, $tipo_acceso, $usuario, $contratista, $empleado, $vehiculo, $persona, $detalle, 1, 'P', $vigencia), 'selectOne');
        
        //RECUPERAMOS LOS DATOS INGRESADO A LA BASE DE DATOS
        $ttmail = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Excepciones', array('LISTAR',$acceso->control_id,'P',$detalle,NULL),'selectOne');
       
        if(!is_null($ttmail)){

            if( (!empty($ttmail->vigencia_excepcion) and !is_null($ttmail->vigencia_excepcion))
             and (!empty($ttmail->usuario) and !is_null($ttmail->usuario)) 
             and (!empty($ttmail->nombre_locacion) and !is_null($ttmail->nombre_locacion)) 
             and (!empty($ttmail->tipo_acceso) and !is_null($ttmail->tipo_acceso)) 
             and (!empty($ttmail->horario) and !is_null($ttmail->horario)) 
             and (!empty($ttmail->detalle_control) and !is_null($ttmail->detalle_control)) 
             and (!empty($ttmail->nombre_subcontratista) and !is_null($ttmail->nombre_subcontratista)) 
             and (!empty($ttmail->nombre_contratista) and !is_null($ttmail->nombre_contratista)) 
             and (!empty($ttmail->nombre_empleado) and !is_null($ttmail->nombre_empleado)) ){
            
                /* ----------- EXPLODE PARA LA VIGENCIA ----------- */
                $vigencia = $ttmail->vigencia_excepcion;
                $fechalink = explode(' ', $vigencia);
                $horalink = $fechalink[1];
                $horalink = explode(':', $horalink);
                $horalink = $horalink[0].$horalink[1];
                $fechalink = explode('-',$fechalink[0]);
                $fechalink = $fechalink[0].$fechalink[1].$fechalink[2];
                
                $parte_link = $acceso->control_id."& '|' & ".$persona." & '|' & ".$fechalink." & ".$horalink;
                $parte_link = base64_encode($parte_link);
        
                $linkRedirec = env('URL_BASEWEB')."/imperium/verificar-excepcion?q=".$parte_link;
        
                $content = new \stdClass;
                $content->usuario_session = $ttmail->usuario;
                $content->locacion = $ttmail->nombre_locacion;
                $content->tipo_acceso = $ttmail->tipo_acceso;
                $content->fecha_hora = $ttmail->horario;
                $content->detalle_control = $ttmail->detalle_control;
                $content->subcontratista = $ttmail->nombre_subcontratista;
                $content->contratista = $ttmail->nombre_contratista;
                $content->nombre_persona = $ttmail->nombre_empleado;
                $content->vigencia_excepcion = $vigencia;
                $content->click_aqui = $linkRedirec;
                $content->detalle_control = $detalle;

                $to = $ttmail->email;

                /* ----------- ENVIANDO EMAIL ------------ */
                if( Misc::enviarMail("imperiumexcepciones",$to,$content,"Control de Ingreso - Solicitud de acceso por excepción") ) {
                    return 'ok';
                } else{
                    return false;
                }
            } else{
                return "campos vacios";
            }
        } else{
            return "listar vacio";
        }
    }

    public static function ingresoExcepcionConfirm() {
        $cli = Session::get('usuario')->cliente['client_id'];
        $usuario = Session::get('usuario')->user_id;

        return view('/acceso/ingreso_excepcion_confirm')->with(compact(['cli','usuario']));
    }

    public function verificarExcepcion(){
        if (isset($_GET['q'])){
            $varAux = base64_decode(Request::get('q'));
            $varAux = explode(' ',$varAux);
                
            if ( $varAux[0] != '' && $varAux[7] != '' && $varAux[9]!= '' ) {
                $currentDate = time();
                $acceso = $varAux[0];
                $acceso = str_replace('&','',$acceso);
                $fecha_vigencia = $varAux[7];
                $vigencia = strtotime($varAux[7].$varAux[9]);                
                $detalle = '';
                if( $currentDate < $vigencia ){
                    $verificacion = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Excepciones', array('LISTAR',$acceso,'P',$detalle,NULL),'selectOne');
                    if (!is_null($verificacion)){
                        return view('/acceso/verificar_excepcion')->with(compact('verificacion','fecha_vigencia'));
                    } else{
                        return view('/acceso/link-expirado');
                    }
                } else{
                    return view('/acceso/link-expirado');
                }
            } else{
                return view('/acceso/link-expirado');
            }
        }
    }

    public static function updateExcepcion(){
        if(isset($_POST['acceso'])){
            $acceso = $_POST['acceso'];
            $detalle = $_POST['detalle_control'];
            $estado = $_POST['estado'];
            $dias = $_POST['dias'];
       
            if ($acceso != '' && $detalle != '' &&  $estado != ''){
                $respuesta = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Excepciones', array('UPDEXCEPCION',$acceso,$estado,$detalle,$dias),'selectOne');
               
                return 'ok';
            }
            return 'error';
        }
    }

    public static function ingresarExcepcionAcceso() {
        $rslt = 0;

        $cli = Session::get('usuario')->cliente['client_id'];
        $usuario = Session::get('usuario')->user_id;
        $locacion = Request::input('locacion');
        $tipo_acceso = Request::input('tipo_acceso');
        $contratista_1 = Request::input('contratista_1');
        $contratista = Request::input('contratista');
        $empleado = !empty(Request::input('empleado')) ? Request::input('empleado') : NULL ;
        $vehiculo = !empty(Request::input('vehiculo')) ? Request::input('vehiculo') : NULL ;
        $persona = Request::input('persona');
        $detalle = Request::input('detalle_control');

        // Hasta el final del día actual
        $vigencia = date_create_from_format('!Y-m-d', date('Y-m-d'));
        $vigencia = date_add(date_add($vigencia, date_interval_create_from_date_string('1 day')), date_interval_create_from_date_string("-1 second"));

        $acceso = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso_Insert', array($cli, $locacion, $tipo_acceso, $usuario, $contratista, $empleado, $vehiculo, $persona, $detalle, 1, 'A', $vigencia), 'selectOne');
        
        return json_encode( array('result'=>$rslt, 'message'=>'Ok') );
    }

    public static function controlAccesoNominas() {
        $cliente = Request::input('cliente');
        $locacion = Request::input('locacion');
        $seccion = Request::input('seccion');
        return view('/acceso/control_acceso_nominas')->with(compact(['cliente','locacion','seccion']));
    }

    public static function controlAccesoNominasData() {
        $cliente = Request::input('cliente');
        $locacion = Request::input('locacion');
        $seccion = Request::input('seccion');
        $reporte = Request::input('reporte') ?? 'NO';
        $nomina = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso', array($cliente, $locacion, $seccion), 'select');

        $acceso = [];
        $paises = [];
        foreach($nomina as $contrat) {
            if(!in_array($contrat->country_code, $paises)) {
                $paises[] = $contrat->country_code;
            }
        }
        array_multisort($paises);
 
        if($seccion == 'C') {

            $tipos = [];
            foreach($nomina as $contrat) {
                if(!in_array($contrat->nombre_tipo_contratista, $tipos)) {
                    $tipos[] = $contrat->nombre_tipo_contratista;
                }
                if(!in_array($contrat->acceso, $acceso)) {
                    $acceso[] = $contrat->acceso;
                }
            }
            array_multisort($tipos);

            $columns[0] = array('type'=>'string', 'title'=>'País', 'index'=>'country_code', 'width'=>90, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            $columns[1] = array('type'=>'string', 'title'=>'Contratista', 'index'=>'nombre_persona', 'cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>1,'locked'=>true);
            $columns[2] = array('type'=>'string', 'title'=>'Identificación', 'index'=>'identificacion', 'width'=>160, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            $columns[3] = array('type'=>'string', 'title'=>'Tipo', 'index'=>'nombre_tipo_contratista', 'cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>1,'locked'=>true);
            $columns[4] = array('type'=>'string', 'title'=>'Subcontratista de', 'index'=>'nombre_contratista_1', 'cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>1,'locked'=>true);
            $columns[5] = array('type'=>'string', 'title'=>'Identificación', 'index'=>'identificacion_1', 'width'=>160, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            $columns[6] = array('type'=>'string', 'title'=>'Acceso', 'index'=>'acceso', 'width'=>80, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
           
            $columns[7] = array('type'=>'select','width'=>70, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'hidden'=>true,'locked'=>false); 
            

        }
        elseif ($seccion == 'E') {

            $tipos = [];
            foreach($nomina as $empl) {
                if(!in_array($empl->nombre_tipo_empleado, $tipos)) {
                    $tipos[] = $empl->nombre_tipo_empleado;
                }
                if(!in_array($empl->acceso, $acceso)) {
                    $acceso[] = $empl->acceso;
                }
            }
            array_multisort($tipos);

            $columns[0] = array('type'=>'string', 'title'=>'País', 'index'=>'country_code', 'width'=>90, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            $columns[1] = array('type'=>'string', 'title'=>'Empleado', 'index'=>'nombre_persona','cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>1,'locked'=>true);
            $columns[2] = array('type'=>'string', 'title'=>'Identificación', 'index'=>'identificacion', 'width'=>160, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            $columns[3] = array('type'=>'string', 'title'=>'Tipo', 'index'=>'nombre_tipo_empleado','cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>1,'locked'=>true);
            $columns[4] = array('type'=>'string', 'title'=>'Contratista', 'index'=>'nombre_contratista_1', 'cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>1,'locked'=>true);
            $columns[5] = array('type'=>'string', 'title'=>'Subcontratista', 'index'=>'nombre_contratista', 'width'=>250, 'cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>'1','locked'=>true);
            $columns[6] = array('type'=>'string', 'title'=>'Acceso', 'index'=>'acceso', 'width'=>80, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            $columns[7] = array('type'=>'select','width'=>70, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'hidden'=>true,'locked'=>false); 
           



        }
        else {
            $tipos = [];
            foreach($nomina as $veh) {
                if(!in_array($veh->nombre_tipo_vehiculo, $tipos)) {
                    $tipos[] = $veh->nombre_tipo_vehiculo;
                }
                if(!in_array($veh->acceso, $acceso)) {
                    $acceso[] = $veh->acceso;
                }
            }
            array_multisort($tipos);

            $columns[0] = array('type'=>'string', 'title'=>'País', 'index'=>'country_code', 'width'=>90, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            $columns[1] = array('type'=>'string', 'title'=>'Vehículo', 'index'=>'nombre_vehiculo','cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>1,'locked'=>true);
            $columns[2] = array('type'=>'string', 'title'=>'Dominio', 'index'=>'dominio', 'width'=>160, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            $columns[3] = array('type'=>'string', 'title'=>'Tipo', 'index'=>'nombre_tipo_vehiculo', 'width'=>300, 'cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            $columns[4] = array('type'=>'string', 'title'=>'Contratista', 'index'=>'nombre_contratista_1','cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>1,'locked'=>true);
            $columns[5] = array('type'=>'string', 'title'=>'Subcontratista', 'index'=>'nombre_contratista', 'cellAlign'=>'left', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}', 'flex'=>1,'locked'=>true);
            $columns[6] = array('type'=>'string', 'title'=>'Acceso', 'index'=>'acceso', 'width'=>80, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'filter'=>'{header:true}','locked'=>true);
            
            $columns[7] = array('type'=>'select','width'=>70, 'cellAlign'=>'center', 'sortable'=>true, 'resizable'=>true, 'align'=>'center', 'hidden'=>true,'locked'=>false); 
            
        }


        return json_encode( array('columns' => $columns, 'data' => $nomina, 'paises' => $paises, 'tipos' => $tipos, 'acceso' => $acceso ) );
    }

    // Funcion que arma el excel para poder exportarlo en control de acceso.
	public static function controlAccesoNominasDataFancy(){
        $cliente = Request::input('cliente');
        $locacion = Request::input('locacion');
        $seccion = Request::input('seccion');
        $nomina = SQLConnection::backendStoreProcedure('Imperium_Control_Acceso', array($cliente, $locacion, $seccion), 'select');
		
        // SECCION DE PERSONAS
		if($seccion == 'E'){
            $file = '<table border="1"><tr>';
		    $file .= '<td>PAÍS' . "</td><td>" . 'EMPLEADO' . "</td><td>" . 'IDENTIFICACIÓN' . "</td><td>TIPO</td>" . "<td>CONTRATISTA" . "</td>". "<td>SUBCONTRATISTA" . "</td>". "<td>ACCESO" . "</td>"; 
		
            foreach ($nomina as $key => $value) {
                $file .= '<tr valign="top">';
                $file .= "<td>" . $value->country_code . "</td>" . "<td>".$value->nombre_persona . "</td>" . "<td>" . $value->identificacion . "</td>" . "<td>" . $value->nombre_tipo_empleado . "</td>" . "<td>" . $value->nombre_contratista_1 . "</td>"."<td>" . $value->nombre_contratista . "</td>"."<td>" . $value->acceso . "</td>"; 
            }
        }

        // SECCION DE CONTRATISTAS
        if($seccion == 'C'){
            $file = '<table border="1"><tr>';
		    $file .= '<td>PAÍS' . "</td><td>" . 'CONTRATISTA' . "</td><td>" . 'IDENTIFICACIÓN' . "</td><td>TIPO</td>" . "<td>SUBCONTRATISTA DE" . "</td>". "<td>IDENTIFICACÍON" . "</td>". "<td>ACCESO" . "</td>"; 
		
            foreach ($nomina as $key => $value) {
                $ident_completa = $value->identificador.' '.$value->identificacion;
                $ident_completa_1 = $value->abreviatura_1.' '.$value->identificacion_1;
                $file .= '<tr valign="top">';
                $file .= "<td>" . $value->country_code . "</td>" . "<td>".$value->nombre_persona . "</td>" . "<td>" . $ident_completa . "</td>" . "<td>" . $value->nombre_tipo_contratista . "</td>" . "<td>" . $value->nombre_contratista_1 . "</td>"."<td>" . $ident_completa_1 . "</td>"."<td>" . $value->acceso . "</td>"; 
            }
        } 

        // SECCION DE VEHICULOS
        if($seccion == 'V'){
            $file = '<table border="1"><tr>';
		    $file .= '<td>PAÍS' . "</td><td>" . 'VEHÍCULO' . "</td><td>" . 'DOMINIO' . "</td><td>TIPO</td>" . "<td>CONTRATISTA" . "</td>". "<td>SUBCONTRATISTA" . "</td>". "<td>ACCESO" . "</td>"; 
		
            foreach ($nomina as $key => $value) {
                $file .= '<tr valign="top">';
                $file .= "<td>" . $value->country_code . "</td>" . "<td>".$value->nombre_vehiculo . "</td>" . "<td>" . $value->dominio . "</td>" . "<td>" . $value->nombre_tipo_vehiculo . "</td>" . "<td>" . $value->nombre_contratista_1 . "</td>"."<td>" . $value->nombre_contratista . "</td>"."<td>" . $value->acceso . "</td>"; 
            }
        }
    
        $file .= '</tr>'; 
		$file .= '</table>'; 

		$fecha = date("Y-m-d");
		header('Content-disposition: attachment; filename=Control_acceso_nominas_' . $fecha . '.xls');
		header('Content-type: application/vnd.ms-excel; charset=utf-8');
		$file = utf8_decode($file); 
		$response =  array(
			'op' => 'ok',
			'archivo' => 'Control_acceso_nominas_' . $fecha . '.xls', 
			'file' => "data:application/vnd.ms-excel;base64,".base64_encode($file)
		);
		return json_encode($response);
	}
	// ----------


    public static function reportesControlAcceso() {
        $cliente = Session::get('usuario')->cliente['client_id'];
        $usr = Session::get('usuario')->user_id;
        $seccion = Request::input('seccion') ?? 'C';
        //
        $locac = SQLConnection::backendStoreProcedure('Imperium_Usuario_Locaciones', array($cliente, $usr), 'select');
        $locacion = $locac[0]->locacion ?? ''; 
        return view('imperium/reportes_control_acceso')->with(compact(['cliente','locacion','seccion']));
    }
    
}