<?php

namespace App\Controllers;

require_once APPPATH.'Libraries/spout-3.3.0/src/Spout/Autoloader/autoload.php';

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;


use \App\Libraries\Complementos;
use \App\Libraries\Globales;
use \App\Libraries\Scripts;
use \App\Libraries\Error;
use \App\Libraries\Alertas;
use \App\Libraries\Pdf;
use \App\Libraries\PlantillasCorreo;


use App\Models\UsuarioPerfilModelo;
use App\Models\UsuarioRutasModelo;
use App\Models\UsuarioSistemasModelo;
use App\Models\ModulosRutasModel;
use App\Models\ModulosCabeceraModel;
use App\Models\UsuarioLogModel;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 */

class BaseController extends Controller
{
	/**
	 * Instance of the main Request object.
	 *
	 * @var IncomingRequest|CLIRequest
	 */
	protected $request;

	/**
	 * An array of helpers to be loaded automatically upon
	 * class instantiation. These helpers will be available
	 * to all other controllers that extend BaseController.
	 *
	 * @var array
	 */
	protected $helpers = ['form', 'url'];

	/**
	 * Constructor.
	 *
	 * @param RequestInterface  $request
	 * @param ResponseInterface $response
	 * @param LoggerInterface   $logger
	 */
	public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
	{

                
        $fechaActual = date("Y-m-d H:i:s");

		// Do Not Edit This Line
		parent::initController($request, $response, $logger);

		//--------------------------------------------------------------------
		// Preload any models, libraries, etc, here.
		
        $this->complementos = new Complementos();
        $this->globales = new Globales();
        $this->scripts = new Scripts();
        $this->error = new Error();
        $this->alertas = new Alertas();	
        $this->pdf = new Pdf();
        $this->plantillasCorreo = new PlantillasCorreo();
        $this->mensajeError = $this->error->msg();
        $this->session = \Config\Services::session();
		$this->items['baseUrl'] = base_url();

        //Obtener url actual
        $uri = current_url(true);
        //Obtener ruta: 3->ruta localhost 2->hosting
        $ruta = $uri->getSegment(3);
		$this->items['raiz'] = $uri->getSegment(1);

                
        $rutasExcluidas = array('salir');

        if(!in_array($ruta,$rutasExcluidas))
        {
            if(isset($this->session->get('sesionUsuario')['accesoTmpId']))
            {
                
                $this->usuarioPerfil = new UsuarioPerfilModelo();
                $this->usuarioRutas = new UsuarioRutasModelo();
                $this->usuarioSistemas = new UsuarioSistemasModelo();
                $this->modulosRutas = new ModulosRutasModel();
                $this->modulosCabecera = new ModulosCabeceraModel();
		        $this->log = new UsuarioLogModel();

                if($this->session->get('sesionUsuario')['accesoTmpId'] != '4373')
                {
                    $aud = array(
                        'IDUsuario'     => $this->session->get('sesionUsuario')['accesoTmpId'],
                        'FechaIngreso'  => $fechaActual,
                        'Plataforma'    => $uri->getSegment(1),
                        'URL'           => $uri->getSegment(3),
                        'JSON'          => null,
                        'Localhost'     => $this->request->getIPAddress()
                    );
                    
                    $this->log->insert($aud);
                }
                
                /*
                * ----------------------
                * VALIDA PERMISOS DE ACCESO AL SISTEMA
                * ----------------------
                */
                
                $autorizacionSistema = $this->usuarioSistemas->join('sistemas', 'usuario_sistemas.IDSistema = sistemas.IDSistema AND usuario_sistemas.IdUsuario = "'.$this->session->get('sesionUsuario')['accesoTmpId'].'"  AND sistemas.Raiz = "gestion"')->findAll();
                
                if(!empty($autorizacionSistema))
                { 
                    /*
                    * ----------------------
                    * VALIDA PERMISOS DE URL
                    * ----------------------
                    */
    
                    $array = array("ruta" => $ruta, "idusuario" => $this->session->get('sesionUsuario')['accesoTmpId']);
    
                    $vista = $this->usuarioPerfil->obtenerRutaUsuario($array);
                    
                    if(count($vista)>0 && $vista['AUTORIZADO']=='1')
                    { 
                        $this->items['id'] = $this->session->get('sesionUsuario')['accesoTmpId'];
                        $this->items['usuario'] = $this->session->get('sesionUsuario')['accesoTmpUsuario'];
                        $this->items['idPerfil'] = $this->session->get('sesionUsuario')['accesoTmpIDPerfil'];
                        $this->items['perfil'] = $this->session->get('sesionUsuario')['accesoTmpPerfil'];
                        $this->items['dpto'] = $this->session->get('sesionUsuario')['accesoTmpIdDpto'];
                        $this->items['idArea'] = $this->session->get('sesionUsuario')['accesoTmpIdArea'];
                        $this->items['idSubarea'] = $this->session->get('sesionUsuario')['accesoTmpIdSubarea'];
                        $this->items['idDelegacionLog'] = $this->session->get('sesionUsuario')['accesoTmpIdDelegacion'];
                        $this->items['idCargoLog'] = $this->session->get('sesionUsuario')['accesoTmpIdCargo'];
                        
                        $this->items['nombres'] = $this->session->get('sesionUsuario')['accesoTmpNombres'];
                        $this->items['apellidos'] = $this->session->get('sesionUsuario')['accesoTmpApellidos'];
                        $this->items['tipoDocumento'] = $this->session->get('sesionUsuario')['accesoTmpTipoDocumento'];
                        $this->items['numeroDocumento'] = $this->session->get('sesionUsuario')['accesoTmpNumeroDocumento'];
                        $this->items['correoElectronico'] = $this->session->get('sesionUsuario')['accesoTmpCorreoElectronico'];
                        $this->items['cargo'] = $this->session->get('sesionUsuario')['accesoTmpCargo'];
                        $this->items['permisos'] = array_column($this->modulosRutas->listadoPermisosUsuarioRuta($this->session->get('sesionUsuario')['accesoTmpId'], $ruta), 'Codigo');
                        $this->items['navbar'] = $this->usuarioRutas->navBarUsuario($this->session->get('sesionUsuario')['accesoTmpId']);
                        $this->items['cabecera'] = $this->modulosCabecera->where("Estado","A")->orderBy('Orden', 'ASC')->findAll();
                        $this->items['modulo'] = $this->modulosRutas->obtenerModulo(array("ruta"=>$ruta))['Modulo'];
                        $this->items['aleatorio'] = $this->complementos->generar_string_aleatorio(5);
                        $this->items['sistemas'] = $this->usuarioSistemas->join('sistemas', 'usuario_sistemas.IDSistema = sistemas.IDSistema AND usuario_sistemas.IdUsuario = "'.$this->session->get('sesionUsuario')['accesoTmpId'].'"')->findAll();
                        
                    }
                    else
                    {
                        echo $this->alertas->reDireccion($this->items['baseUrl'] . '/' .$vista['URLBase'], 1);
                        EXIT;
                    }
                }
            } else {
                
                $data = array (
                    'titulo' => 'Gestión de Usuarios | Verisure',
                );
                $data = array_merge($data, $this->items);
                return view('dashboard/iniciar-sesion',$data);
            }
        }
		//--------------------------------------------------------------------
		// E.g.: $this->session = \Config\Services::session();
	}
}
