<?php
class NotificacionesControlador extends Controladores {
    
    function mostrarTodasDelColaborador(){
        //$Notificaciones = Notificaciones::delCliente();
        Vistas::mostrar( 'usuarios', 'notificaciones/lst-notificaciones');
    }
    function tablaListado(){
        $Notificaciones = Notificaciones::delCliente();
        Vistas::mostrar( 'usuarios', 'notificaciones/tbl-notificaciones', 
            array('Notificaciones' => $Notificaciones) 
        );
    }
    
    
    function mostrarEnviadasPorColaborador(){
        //$Notificaciones = Notificaciones::delCliente();
        Vistas::mostrar( 'usuarios', 'notificaciones/lst-notificaciones-enviadas');
    }
    function tablaListadoEnviadas(){
        $Notificaciones = Notificaciones::enviadasPorElCliente();
        Vistas::mostrar( 'usuarios', 'notificaciones/tbl-notificaciones-enviadas', 
            array('Notificaciones' => $Notificaciones) 
        );
    }
    
    
    /**
     * Responde con el formulario de notificacion vacio, solo datos necesarios.
     * LLama a la función que devuleve el formulario pero 
     * sin enviarle los datos de notificacion.  
     * Esta función se crea para poder gestionar el permiso de NUEVO notificacion
     * @return HTML Formulario solo con datos inciales o necesarios.
     */
    function mostrarFormularioNuevo() {
        $this->mostrarFormulario();
    }
    /**
     * Muestra el Formulario procesado para ser mostrado al usuario.
     * Se le envian unos datos inciales para la carga de la vista, y
     * se envia los datos del notificacion cuando se esta editando.
     * @return HTML Vista del Formulario de notificacion
     */
    private function mostrarFormulario($notificacion = null) {
        Vistas::mostrar('usuarios', 'notificaciones/form-notificacion', array(
          'Colaboradores' => Colaboradores::activos(),
          'Operaciones'     => Operaciones::todos()
        ));
    }
    
     /**
     * Guardar Datos Recibidos, bien sea como un registro nuevo, o como una actualización.
     * Despues imprime las Respuesta del Sistema a la ejecución de la operacion
     */
    function guardarDatos() {
        if (empty($this->notificacionID)) {
            echo $this->guardarNuevo();
        } else {
            echo $this->guardarCambios();
        }
    }

    /**
     * Función que toma los datos enviados y crea un nuevo registro
     * @return RespuestasSistema 
     */
    private function guardarNuevo() {
        $creadoID = Notificaciones::paraColaborador(
                $this->notificacionCOLABORADOR, 
                $this->notificacionTIPO, 
                $this->notificacionTITULO, 
                $this->notificacionDESCRIPCION, 
                $this->notificacionOPERACION
        );
        if ($creadoID) {
            $Notificacion = Notificaciones::datosCompletos($creadoID);
            return Respuestassistema::exito("Nuevo Registro CREADO con EXITO", $Notificacion);
        } else {
            return Respuestassistema::fallo("No se pudo REGISTRAR LA NOTIFICACIÓN. Si vuelve a suceder, contacte con el Centro TICS.");
        }
    }
    
    
     /**
     * Cambiar el estado de uan notificación a Leido.
     * Esta operacion actualiza el campo de la FECHA de LECTURA.     
     * @return RespuestasSistema Resultado de la Operacion
     */
    function marcarComoLeida() {
        $NotificacionesSeleccionadas = $this->check_notificaciones;
        if (count($NotificacionesSeleccionadas)) {
            $n = 0;
            foreach ($NotificacionesSeleccionadas as $NotificacionesID):
                $Notificacion = Notificaciones::datosCompletos($NotificacionesID);
                if( is_null( $Notificacion->notificacionFCHLECTURA) ){
                    if (Notificaciones::registrarLectura($NotificacionesID)) {
                        $n++;
                    }
                }
            endforeach;
            if ($n == 0) {
                echo RespuestasSistema::error('No fue posible realizar la OPERACION [MARCAR COMO LEIDA]. Verifica los datos o Contacte al centro TICS.');
            } else if ($n == count($NotificacionesSeleccionadas)) {
                echo RespuestasSistema::exito('Se MARCÓ COMO LEIDA la(s) notificación(es) exitosamente!');
            } else {
                echo RespuestasSistema::alerta('No se realizó la operación [MARCAR COMO LEIDA] en la(s) notificación(es) seleccionadas. Verifica los datos o contacta al centro TICS.');
            }
        } else {
            echo RespuestasSistema::error('No llegarón los datos para ejecutar la operación de [MARCAR COMO LEIDA]. Contacta al centro TICS');
        }
    }

    
    
    
    function listaPendientes() {
        $Notificaciones = Notificaciones::delClientePendientes();
        Vistas::mostrar( 'usuarios', 'notificaciones/lista-notificaciones', 
            array('Notificaciones' => $Notificaciones) 
        );
    }
    
    function menuNotificaciones() {
        $Notificaciones = Notificaciones::delClientePendientes();
        Vistas::mostrar( 'usuarios', 'notificaciones/menu-notificaciones', 
            array( 'TIEMPO_NOTIFICACIONES' => Parametros::valor('TIEMPO_CONSULTA_NOTIFICACIONES') , 'Notificaciones' => $Notificaciones) 
        );
    } 
    function pendientes() {
        $Notificaciones = Notificaciones::delClientePendientes();
        echo RespuestasSistema::exito(
            $Notificaciones
        );
    } 
    function pendientesLectura() {
        $Notificaciones = Notificaciones::delClientePendientesLectura();
        echo RespuestasSistema::exito(
            $Notificaciones
        );
    } 
    function pendientesOperacion() {
        $Notificaciones = Notificaciones::delClientePendientesOperacion();
        echo RespuestasSistema::exito(
            $Notificaciones
        );
    } 
    
    function consultarPendientes() {
        $Notificaciones = Notificaciones::delClientePendientes();
        echo RespuestasSistema::exito(
            (count($Notificaciones)>0 ? "Tiene ".count($Notificaciones)." PENDIENTES por revisar." : "") 
        );
    } 
    
    function totalPendientes() {
        $Notificaciones = Notificaciones::delClientePendientes();
        echo RespuestasSistema::exito(
            array(count($Notificaciones) )
        );
    } 
    
    function registrarLecturaNotificacion(){
        Notificaciones::registrarLectura($this->notificacionID);
        echo RespuestasSistema::exito(/*"Se ha registrado la lectura de la notificacion."*/);
    }
    
    
    function ejecutarOperacionAsociada() {
        $NotificacionesSeleccionadas = $this->check_notificaciones;
        if (count($NotificacionesSeleccionadas)) {
            foreach ($NotificacionesSeleccionadas as $NotificacionID):
                $Notificacion = Notificaciones::datosCompletos($NotificacionID);
                if( !is_null($Notificacion->notificacionOPERACION) ){
                    if( is_null($Notificacion->notificacionFCHOPERACION) ){
                        echo RespuestasSistema::exito("Iniciaremos la ejecución de la operación asociada a la notificaión.",$Notificacion);
                    }else{
                        echo RespuestasSistema::error("Ya se ha EJECUTADO la operación asociada a la notificacion. Si cree que esto es un error, debe contactar al centro TICS.");
                    }
                }else{
                    echo RespuestasSistema::error("La notificación no tiene una operación asociada para ejecutarse.");
                }
            endforeach;
        } else {
            echo RespuestasSistema::error('No llegarón los datos para ejecutar la operación de [MARCAR COMO LEIDA]. Contacta al centro TICS');
        }
    }
    
    function ejecutarOperacionNotificacion(){
        $Notificacion = Notificaciones::datosCompletos($this->notificacionID);
        if( !is_null($Notificacion->notificacionOPERACION) ){
            echo RespuestasSistema::exito(/*"Se ha registrado la lectura de la notificacion."*/"",$Notificacion);
            Notificaciones::registrarOperacion($this->notificacionID);
        }else{
            echo RespuestasSistema::exito(/*"Se ha registrado la lectura de la notificacion."*/);
        }
    }    
}

