<?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\UsuarioPerfilModel;
use App\Models\UsuarioRutasModel;
use App\Models\UsuarioSistemasModel;
use App\Models\ModulosRutasModel;
use App\Models\ModulosCabeceraModel;
use App\Models\UsuarioLogModel;
use App\Models\UsuarioGruposTrabajoModel;
use App\Models\NotificacionesModel;

/**
 * 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.
 */
abstract class BaseController extends Controller
{
    /**
     * Instance of the main Request object.
     *
     * @var CLIRequest|IncomingRequest
     */
    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 list<string>
     */
    protected $helpers = ['form', 'url'];

    /**
     * Be sure to declare properties for any property fetch you initialized.
     * The creation of dynamic property is deprecated in PHP 8.2.
     */
    // protected $session;

    /**
     * @return void
     */
    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);
        // echo APPPATH. 'Config/Routes.php';exit;
        // echo "$fechaActual";exit;

        $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();
		$this->items['aleatorio'] = $this->complementos->generar_string_aleatorio(5);
        // echo $this->items['baseUrl']; exit;
        //Obtener url actual
        // $uri = current_url(true);
        $uri = new \CodeIgniter\HTTP\URI($this->request->getUri());
        //Obtener ruta: 3->ruta localhost 2->hosting
//         echo 'URL Completa: ' . (string) $uri . '<br>';
//         echo 'Segmentos Totales: ' . $uri->getTotalSegments() . '<br>';
// echo 'Segmentos: <br>';
// for ($i = 1; $i <= $uri->getTotalSegments(); $i++) {
//     echo 'Segmento ' . $i . ': ' . $uri->getSegment($i) . '<br>';
// }
// exit;

        $ruta = $uri->getSegment(3);
		$this->items['raiz'] = $uri->getSegment(1);
        $rutasExcluidas = array("entrar", "salir");
        
        if(!in_array($ruta,$rutasExcluidas))
        {
            // echo "No Entró"; exit;
            if(isset($this->session->get('sesionUsuario')['accesoTmpId']))
            {
                $this->usuarioPerfil = new UsuarioPerfilModel();
                $this->usuarioRutas = new UsuarioRutasModel();
                $this->usuarioSistemas = new UsuarioSistemasModel();
                $this->modulosRutas = new ModulosRutasModel();
                $this->modulosCabecera = new ModulosCabeceraModel();
		        $this->log = new UsuarioLogModel();
		        $this->notificaciones = new NotificacionesModel();

                // 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 URL
                * ----------------------
                */

                $array = array("ruta" => $ruta, "idusuario" => $this->session->get('sesionUsuario')['accesoTmpId']);

                $vista = $this->usuarioPerfil->obtenerRutaUsuario($array);
                
                $rutasGlobales = $this->globales->urlLibres();

                if((count($vista)>0 && $vista['AUTORIZADO']=='1') || in_array($ruta,$rutasGlobales))
                {
                
                    /*
                    * ----------------------
                    * OBTENER NOTIFICACIONES NO VISTAS
                    * ----------------------
                    */
    
        		  //  $arrayNoVistos = $this->notificaciones->cantidadNotificacionesSinVer($array);
        		    $arrayNoVistos = array();
                    /*
                    * ----------------------
                    * ARMAR VARIABLES GLOBALES
                    * ----------------------
                    */
    
                    $this->items['idUsuarioSession'] = $this->session->get('sesionUsuario')['accesoTmpId'];
                    $this->items['idPerfilSession'] = $this->session->get('sesionUsuario')['accesoTmpIDPerfil'];
                    $this->items['perfilSession'] = $this->session->get('sesionUsuario')['accesoTmpPerfil'];
                    $this->items['cargoSession'] = $this->session->get('sesionUsuario')['accesoTmpCargo'];
                    
                    $this->items['notificacionesNoVistasInicio'] = isset($arrayNoVistos['TOTALNOVISTO']) ? $arrayNoVistos['TOTALNOVISTO'] : 0;
                    
                    $this->items['nombresSession'] = $this->session->get('sesionUsuario')['accesoTmpNombres'];
                    $this->items['apellidosSession'] = $this->session->get('sesionUsuario')['accesoTmpApellidos'];
                    // $this->items['tipoDocumento'] = $this->session->get('sesionUsuario')['accesoTmpTipoDocumento'];
                    $this->items['nroDocumentoSession'] = $this->session->get('sesionUsuario')['accesoTmpNumeroDocumento'];
                    $this->items['correoElectronicoSession'] = $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['principalURL'] = $vista['URLBase'];
                    //Validar url externas
                    if(in_array($ruta, $rutasGlobales))
                    {
                        $this->items['modulo'] = "Libre";
                    }
                    else
                    {
                        $this->items['modulo'] = $this->modulosRutas->obtenerModulo(array("ruta"=>$ruta))['Modulo'];
                    }
                    
                    
                }
                else
                {
                    echo $this->alertas->reDireccion($this->items['baseUrl'] . '/' .$vista['URLBase'], 1);
                    EXIT;
                    
                    // // echo "No autorizado";exit;
                    // $data = array (
                    //     'titulo' => 'NO AUTORIZADO',
                    // );
                    
                    // // return view('errors/404',$data);
                    // echo view('errors/404',$data);
                    // exit;
                }
            } 
            else 
            {
                $data = array (
                    'titulo' => 'Iniciar sesi贸n | Verisure Peru',
                );
                $data = array_merge($data, $this->items);
                return view('dashboard/iniciar-sesion',$data);
            }
        }
        // Preload any models, libraries, etc, here.

        // E.g.: $this->session = \Config\Services::session();
    }
}
