<?php
/****************************************************************************************
 * DEV: CONTRALORIA DEL ESTADO.
 * MODULO: RECURSOS HUMANOS
 * PROGRAMADORES.________________________________________________________________________
 * | # | NOMBRE.              | CORREO.                              | TELEFONO.
 * | 1 | Fernando Mendoza     | dt.ait.programador1@cgesucre.gob.ve  | 0424-8942068
 * | 2 |
 * |_____________________________________________________________________________________
 * VERSION
 *
 * |          PROGRAMADOR                  |          FECHA          |       VERSION      |
 * |               #1                      |        02-02-2016       |         1.0        |
 * |                                       |                         |                    |
 * |_______________________________________|_________________________|____________________|
 *****************************************************************************************/
class pensionesSobrevivienteControlador extends Controlador
{
    private $atEmpleados;
    private $atIdUsuario;
    private $atPensionesSobreviviente;
    private $atOrganismo;
    private $atDependencias;
    private $atTipoNimina;
    private $atMotivoCese;
    private $atCargo;
    private $atCargaFamiliar;

    public function __construct()
    {
        parent::__construct();
        Session::metAcceso();
        #se carga el Modelo.
        $this->atEmpleados    = $this->metCargarModelo('empleados','gestion');
        $this->atPensionesSobreviviente = $this->metCargarModelo('pensionesSobreviviente','procesos');
        $this->atOrganismo    = $this->metCargarModelo('organismo','maestros','modCV');
        $this->atDependencias = $this->metCargarModelo('dependencias','maestros');
        $this->atMotivoCese   = $this->metCargarModelo('motivoCese','maestros');
        $this->atTipoNimina   = $this->metCargarModelo('tipoNomina','maestros','modNM');
        $this->atCargo        = $this->metCargarModelo('cargos','maestros');
        $this->atIdUsuario    = Session::metObtener('idUsuario');

    }

    #Metodo Index del controlador Pensiones Sobreviviente
    public function metIndex()
    {

        $complementosCss = array(
            'DataTables/jquery.dataTables',
            'DataTables/extensions/dataTables.colVis941e',
            'DataTables/extensions/dataTables.tableTools4029',
            'bootstrap-datepicker/datepicker',
            'select2/select201ef'
        );
        $complementoJs = array(
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min',
            'bootstrap-datepicker/bootstrap-datepicker',
            'select2/select2.min'
        );
        $js= array('materialSiace/core/demo/DemoTableDynamic','materialSiace/App','materialSiace/core/demo/DemoFormComponents');

        $this->atVista->metCargarCssComplemento($complementosCss);
        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);

        $this->atVista->assign('listadoOrganismos',$this->atOrganismo->metListarOrganismo());
        $this->atVista->assign('listadoDependencias',$this->atDependencias->metConsultarDependencias());
        $Empleados = $this->atEmpleados->metListarEmpleado('AP','operaciones','1','1');
        $this->atVista->assign('Empleado',$Empleados);
        $EstadoRegistro = array('PR'=>'PREPARADO','CO'=>'CONFORMADO','AP'=>'APROBADO','AN'=>'ANULADO');
        $this->atVista->assign('EstadoRegistro',$EstadoRegistro);

        $this->atVista->assign('proceso','Listado');
        $this->atVista->assign('listadoPensionesSobreviviente', $this->atPensionesSobreviviente->metListarPensionesSobreviviente('PR'));
        $this->atVista->metRenderizar('listado');
    }

    /*PERMITE REGISTRAR LA PENSION SOBREVIVIENTE*/
    public function metRegistrar()
    {
        $complementosCss = array(
            'bootstrap-datepicker/datepicker',
            'wizard/wizardfa6c',
            'select2/select201ef'
        );
        $complementoJs = array(
            'bootstrap-datepicker/bootstrap-datepicker',
            'wizard/jquery.bootstrap.wizard.min',
            'select2/select2.min',
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min',
        );
        $js= array('materialSiace/App','materialSiace/core/demo/DemoFormComponents','materialSiace/core/demo/DemoFormWizard');

        $this->atVista->metCargarCssComplemento($complementosCss);
        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);


        $idPensionSobreviviente = $this->metObtenerInt('idPensionSobreviviente');
        $valido  = $this->metObtenerInt('valido');

        if($valido==1) {

            $formTxt   = $this->metObtenerTexto('form','txt');
            $formInt   = $this->metObtenerInt('form','int');

            if(!empty($formInt)) {
                foreach ($formInt as $tituloInt => $valorInt) {
                    if (!empty($formInt[$tituloInt])) {
                        if((strcmp($tituloInt,'num_ultimo_sueldo')==0) || (strcmp($tituloInt,'num_monto_pension')==0) || (strcmp($tituloInt,'sueldo')==0) || (strcmp($tituloInt,'prima')==0) || (strcmp($tituloInt,'total')==0) || (strcmp($tituloInt,'porcentaje')==0) || (strcmp($tituloInt,'s_base')==0) || (strcmp($tituloInt,'jubilacion')==0) ){
                            $validacion[$tituloInt]=str_replace(",",".",preg_replace('/[^0-9 ,]/i', '', $valorInt));
                        }else{
                            $validacion[$tituloInt]=$valorInt;
                        }
                    } else {
                        $validacion[$tituloInt] = '';
                    }
                }
            }
            if(!empty($formTxt)) {
                foreach ($formTxt as $tituloTxt => $valorTxt) {
                    if (!empty($formTxt[$tituloTxt])) {
                        $validacion[$tituloTxt] = $valorTxt;
                    } else {
                        $validacion[$tituloTxt] = '';

                    }
                }
            }

            if(!isset($validacion['txt_observacion_pre'])){
                $validacion['txt_observacion_pre']=NULL;
            }
            if(empty($validacion['fk_rhc032_num_motivo_cese'])){
                $validacion['fk_rhc032_num_motivo_cese']="NULL";
            }

            #array de datos
            $datos = array(
                /*datos para tabla rh_b003_pension*/
                $validacion['fk_rhb001_num_empleado'],
                $validacion['fk_a001_num_organismo'],
                $validacion['ind_organismo'],
                $validacion['fk_a004_num_dependencia'],
                $validacion['ind_dependencia'],
                $validacion['fk_rhc063_num_puestos'],
                $validacion['ind_cargo'],
                $validacion['num_ultimo_sueldo'],
                $validacion['num_anio_servicio'],
                $validacion['num_edad'],
                $validacion['fec_fecha'],
                $validacion['fec_fecha_ingreso'],
                $validacion['fk_a006_num_miscelaneo_detalle_tipopension'],
                $validacion['ind_detalle_tipopension'],
                $validacion['fk_a006_num_miscelaneo_detalle_motivopension'],
                $validacion['ind_detalle_motivopension'],
                /*datos para tabla rh_c035_sobreviviente*/
                $validacion['num_monto_pension'],
                $validacion['jubilacion'],
                $validacion['porcentaje'],
                $validacion['sueldo'],
                $validacion['num_anios_servicio_exceso'],
                $validacion['ind_periodo'],
                $validacion['fk_nmb001_num_tipo_nomina'],
                $validacion['fk_a006_num_miscelaneo_detalle_tipotrab'],
                $validacion['num_situacion_trabajo'],
                $validacion['fk_rhc032_num_motivo_cese'],
                $validacion['fec_fecha_egreso'],
                $validacion['txt_observacion_egreso'],
                $validacion['ind_resolucion'],
                $validacion['txt_observacion_pre'],
                $validacion['cedula'],
                $validacion['ind_sexo'],
                $validacion['sexo'],
                $validacion['prima'],
                $validacion['total'],
                $validacion['s_base'],
                $validacion['listadoBeneficiario'],
                $validacion['txt_cuenta'],
                $validacion['fk_a006_num_miscelaneo_detalle_tipocta']
            );


            $id = $this->atPensionesSobreviviente->metRegistrarPensionSobreviviente($datos);

            if(is_array($id)){
                $validacion['status'] = 'error';
                $validacion['detalleERROR'] = $id;
                echo json_encode($validacion);
                exit;
            }else{
                $validacion['status']='registrar';
                echo json_encode($validacion);
                exit;
            }



        }

        $EstadoRegistro = array('0'=>'NO ACTIVO','1'=>'ACTIVO');
        $this->atVista->assign('EstadoRegistro',$EstadoRegistro);

        $usuario = Session::metObtener('idUsuario');
        $obtenerEmpleado = $this->atEmpleados->metUsuario($usuario, 1);
        $pkNumEmpleado = $obtenerEmpleado['pk_num_empleado'];
        $datosEmpleado = $this->atEmpleados->metEstadoEmpleado($pkNumEmpleado);

        $this->atVista->assign('estadoEmpleado',$datosEmpleado);

        $periodo = date("Y-m");#periodo actual
        $fecha   = date("d-m-Y");#fecha actual


        $miscMotivoPension = $this->atEmpleados->metMostrarSelect('MOTIPEN');
        $this->atVista->assign('MotivoPension',$miscMotivoPension);

        $this->atVista->assign('listadoTipoNomina',$this->atTipoNimina->metListarTipoNomina());
        $this->atVista->assign('listadoTipoTrabajador',$this->atEmpleados->metMostrarSelect('TIPOTRAB'));
        $this->atVista->assign('listadoTipoCuenta',$this->atEmpleados->metMostrarSelect('TIPCUENTAB'));
        $this->atVista->assign('listadoMotivoCese',$this->atMotivoCese->metConsultarMotivoCese());

        $this->atVista->assign('idUsuario',$this->atIdUsuario);
        $this->atVista->assign('nombreUsuario',Session::metObtener('nombreUsuario'));

        $this->atVista->assign('periodo',$periodo);
        $this->atVista->assign('fecha',$fecha);
        /*********************************************************************************************/
        $cod_detalle = 'I';

        /*consulto miscelaneo tipo de concepto*/
        $miscelaneoTipoConcepto = $this->atEmpleados->metMostrarSelect('TDCNM');
        /*recorro el arreglo para obtener el id del miscelaneo detalle tipo concepto*/
        foreach($miscelaneoTipoConcepto as $d){
            if(strcmp($d['cod_detalle'],$cod_detalle)==0){
                $id_tipo_concepto = $d['pk_num_miscelaneo_detalle'];
            }
        }
        //consulto los conceptos disponibles de nomina para el calculo de las jubilaciones y pensiones
        $conceptos = $this->atPensionesSobreviviente->metConsultarConceptosJP($id_tipo_concepto);
        $this->atVista->assign('conceptos',$conceptos);
        $this->atVista->assign('ct','90');
        /*********************************************************************************************/


        $this->atVista->assign('idPensionSobreviviente',$idPensionSobreviviente);
        $this->atVista->assign('proceso','Nuevo');
        $this->atVista->metRenderizar('nuevaPension','modales');
    }


    //Método que permite buscar un empleado desde el wizard
    public function metConsultarEmpleado()
    {

        $proceso = $this->metObtenerTexto('proceso');

        $usuario = Session::metObtener('idUsuario');
        $empleado = $this->atEmpleados->metUsuario($usuario, 1);
        $pkNumEmpleado = $empleado['pk_num_empleado'];

        $listadoOrganismo = $this->atOrganismo->metListarOrganismo();

        $datosEmpleado = $this->atEmpleados->metEstadoEmpleado($pkNumEmpleado);
        $pkNumDependencia = $datosEmpleado['pk_num_dependencia'];

        $listadoEmpleados = $this->atDependencias->metDependenciaEmpleado($pkNumDependencia);
        $this->atVista->assign('empleado', $listadoEmpleados);

        $listadoDependencia = $this->atDependencias->metListarDependenciaOrganismo($datosEmpleado['pk_num_organismo'], 1, 0);
        $this->atVista->assign('listadoDependencia', $listadoDependencia);
        // Organismo donde trabaja el empleado
        $empleado = array(
            'pk_num_organismo' => $datosEmpleado['pk_num_organismo'],
            'pk_num_dependencia' => $pkNumDependencia
        );
        $datosTrabajador = $this->atPensionesSobreviviente->metBuscarTrabajador($datosEmpleado['pk_num_organismo'], $pkNumDependencia, '', '', '', '1', '1', '', '');

        $centroCosto = $this->atPensionesSobreviviente->metListarCentroCosto();
        $tipoNomina = $this->atTipoNimina->metListarTipoNomina();
        $tipoTrabajador = $this->atEmpleados->metMostrarSelect('TIPOTRAB');
        // Envío a la vista
        $this->atVista->assign('datosTrabajador', $datosTrabajador);
        $this->atVista->assign('centroCosto', $centroCosto);
        $this->atVista->assign('emp', $empleado);
        $this->atVista->assign('nomina', $tipoNomina);
        $this->atVista->assign('tipoTrabajador', $tipoTrabajador);
        $this->atVista->assign('listadoOrganismo', $listadoOrganismo);
        $this->atVista->assign('proceso',$proceso);
        $this->atVista->assign('nombreUsuario',Session::metObtener('nombreUsuario'));
        $this->atVista->assign('idUsuario',$this->atIdUsuario);
        $this->atVista->metRenderizar('buscarEmpleado', 'modales');

    }

    // Método que permite listar empleados de acuerdo a la busqueda en nueva pension
    public function metBuscarTrabajador()
    {
        $pkNumOrganismo = $_POST['pk_num_organismo'];
        $pkNumDependencia = $_POST['pk_num_dependencia'];
        $centroCosto = $_POST['centro_costo'];
        $tipoNomina = $_POST['tipo_nomina'];
        $tipoTrabajador = $_POST['tipo_trabajador'];
        $estado_registro = $_POST['estado_registro'];
        $situacionTabajo = $_POST['situacion_trabajo'];
        $fechaInicio = $_POST['fecha_inicio'];
        $fecha_fin = $_POST['fecha_fin'];
        $datosTrabajador = $this->atPensionesSobreviviente->metBuscarTrabajador($pkNumOrganismo, $pkNumDependencia, $centroCosto, $tipoNomina, $tipoTrabajador, $estado_registro, $situacionTabajo, $fechaInicio, $fecha_fin);
        echo json_encode($datosTrabajador);
    }

    #Metodo que permite obtener los datos del empleado
    public function metObtenerDatosEmpleado()
    {
        $idEmpleado = $this->metObtenerInt('idEmpleado');

        $resultado = $this->atPensionesSobreviviente->metObtenerDatosEmpleado($idEmpleado);

        $sueldo = number_format($resultado['num_sueldo_basico'],2,",",".");
        $f_n    = explode("-",$resultado['fec_nacimiento']);
        $f_i    = explode("-",$resultado['fec_ingreso']);
        $f_a    = date("d-m-Y");

        #edad y años de servicio
        list($edad, $EdadMeses, $EdadDias) = $this->metCalcularEdadAnioServicio($f_n[2]."-".$f_n[1]."-".$f_n[0],$f_a);
        list($anio_serv, $MesesServicio, $DiasServicio) = $this->metCalcularEdadAnioServicio($f_i[2]."-".$f_i[1]."-".$f_i[0],$f_a);


        #consulto miscelaneos
        $miscMotivoPen= $this->atEmpleados->metMostrarSelect('MOTIPEN');
        $miscTipoPen= $this->atEmpleados->metMostrarSelect('TIPOPEN');

        foreach($miscMotivoPen as $d1){

            $T = 'FA';//FALLECIMIENTO

            if(strcmp($d1['cod_detalle'],$T)==0){
                $id_motivo_pension = $d1['pk_num_miscelaneo_detalle'];
                $motivo_pension = $d1['cod_detalle'];
            }

        }

        foreach($miscTipoPen as $d2){

            $T = 'SOB';

            if(strcmp($d2['cod_detalle'],$T)==0){
                $id_tipo_pension = $d2['pk_num_miscelaneo_detalle'];
                $tipo_pension = $d2['cod_detalle'];
            }

        }

        //datos mpara mostrar en el formulario
        $datos = array(
            'id_empleado' => $idEmpleado,
            'nombreTrabajador' => $resultado['nombre_completo'],
            'num_sueldo_basico' => $sueldo,
            'fec_nacimiento' => $f_n[2]."-".$f_n[1]."-".$f_n[0],
            'fec_ingreso' => $f_i[2]."-".$f_i[1]."-".$f_i[0],
            'ind_cedula_documento' => $resultado['ind_cedula_documento'],
            'fk_a001_num_organismo' => $resultado['fk_a001_num_organismo'],
            'organismo' => $resultado['organismo'],
            'fk_a004_num_dependencia' => $resultado['fk_a004_num_dependencia'],
            'ind_dependencia' => $resultado['dependencia'],
            'fk_a006_num_miscelaneo_detalle_sexo' => $resultado['fk_a006_num_miscelaneo_detalle_sexo'],
            'sexo' => $resultado['sexo'],
            'fk_rhc063_num_puestos_cargo' => $resultado['fk_rhc063_num_puestos_cargo'],
            'cargo' => $resultado['cargo'],
            'edad' => $edad,
            'anio_serv' => $anio_serv,
            'fk_a006_num_miscelaneo_detalle_motivopension' => $id_motivo_pension,
            'motivo_pension' => $motivo_pension,
            'fk_a006_num_miscelaneo_detalle_tipopension' => $id_tipo_pension,
            'tipo_pension' => $tipo_pension,
            'nomina' => $resultado['fk_nmb001_num_tipo_nomina'],
            'tipo_trabajador' => $resultado['fk_a006_num_miscelaneo_detalle_tipotrabajador'],
            'estatus' => $resultado['estatus_empleado'],
            'tipo' => $T,

        );

        echo json_encode($datos);

    }

    /**
     * PARA VERIFICAR LOS REQUISITOS PARA OPTAR A LA PENSION POR INVALIDEZ
     * VALIDA EL TIEMPO DEL FUNCIONARIO EN LA INSTITUCION Y EL MONTO ASIGNADO A LA PENSION
     **/
    public function metVerificarRequisitos()
    {
        $idEmpleado = $this->metObtenerInt('idEmpleado');
        $sexo = $this->metObtenerTexto('sexo');
        $edad = $this->metObtenerInt('edad');
        $f_a  = date("d-m-Y");

        /************************************************************************************************************************************/
        /*$cod_detalle identifica al miscelaneo tipo entidad, G quiere decir gubernamental*/
        /*los antecedentes de servicios son todas aquellas experiencias laborales tipo gubernamentales*/
        $cod_detalle = 'G';
        /*consulto el miscelaneo tipo de entidad*/
        $miscelaneoTipoEntidad = $this->atEmpleados->metMostrarSelect('TIPOENTE');
        /*recorro el arreglo para obtener el id del miscelaneo detalle*/
        foreach($miscelaneoTipoEntidad as $d){
            if(strcmp($d['cod_detalle'],$cod_detalle)==0){
                $id_tipo_entidad = $d['pk_num_miscelaneo_detalle'];
            }
        }
        $antecedente = $this->atPensionesSobreviviente->metConsultarAntecedente($idEmpleado,$id_tipo_entidad);
        $acumuladorAnio = 0;
        $acumuladorMes = 0;
        $acumuladorDia = 0;
        foreach($antecedente as $ant) {
            $fechaIngresoAnt = $ant['fec_ingreso'];
            $fechaEgresoAnt = $ant['fec_egreso'];
            $tiempoServicioAnt = $this->metTiempoServicio($fechaIngresoAnt, $fechaEgresoAnt);
            $anio = $tiempoServicioAnt['anio'];
            $mes = $tiempoServicioAnt['mes'];
            $dia = $tiempoServicioAnt['dia'];
            $acumuladorAnio = $acumuladorAnio + $anio;
            $acumuladorMes = $acumuladorMes + $mes;
            $acumuladorDia = $acumuladorDia + $dia;
        }
        // Calculo el total de antecedentes de servicio en la institucion
        $servicioEmpleado = $this->atEmpleados->metEstadoEmpleado($idEmpleado);
        $fechaIngreso = $servicioEmpleado['fecha_ingreso'];
        $fechaActual = date('Y-m-d');
        $tiempoServicioInst = $this->metTiempoServicio($fechaIngreso, $fechaActual);
        $diaInst = $tiempoServicioInst['dia'];
        $mesInst = $tiempoServicioInst['mes'];
        $anioInst = $tiempoServicioInst['anio'];
        // Obtengo el total de servicio en cuanto a antecedente
        $totalAntecedente = $this->metObtenerServicio($acumuladorDia, $acumuladorMes, $acumuladorAnio);
        $diaAnt = $totalAntecedente['dia'];
        $mesAnt = $totalAntecedente['mes'];
        $anioAnt = $totalAntecedente['anio'];
        // Tiempo total de Servicio
        $diaTotalPrevio = $diaInst + $diaAnt;
        $mesTotalPrevio = $mesInst + $mesAnt;
        $anioTotalPrevio = $anioInst + $anioAnt;
        $total = $this->metObtenerServicio($diaTotalPrevio, $mesTotalPrevio, $anioTotalPrevio);
        $diaTotal = $total['dia'];
        $mesTotal = $total['mes'];
        $anioTotal = $total['anio'];

        /************OJO****************/
        if($mesTotal >= 8){
            $anioTotal++;
            $mesTotal=0;
            $diaTotal=0;
        }
        /**************OJO***************/
        // Array
        $datosServicio = array (
            'dia' => $diaAnt,
            'mes' => $mesAnt,
            'anio' => $anioAnt,
            'diaInst' => $diaInst,
            'mesInst' => $mesInst,
            'anioInst' => $anioInst,
            'diaTotal' => $diaTotal,
            'mesTotal' => $mesTotal,
            'anioTotal' => $anioTotal
        );
        /*****************************************PARAMETROS DEL SISTEMA PARA VERIFICAR JUBILACION************************************************/

        $EDADJUBM  = Session::metObtener('EDADJUBM');//EDAD JUBILACION MASCULINO
        $MINSERVSI = Session::metObtener('MINSERVSI');//MINIMO DE AÑOS REQUERIDOS SI CUMPLE CON TODOS LOS REQUISITOS DE LA JUBILACION
        $EDADJUBF  = Session::metObtener('EDADJUBF');//EDAD JUBILACION FEMENINO
        $MINSERVNO = Session::metObtener('MINSERVNO');//MINIMO DE AÑOS REQUERIDOS SI NO CUMPLE CON TODOS LOS REQUISITOS DE LA JUBILACION
        $COEPORCJUB= Session::metObtener('COEPORCJUB');//COEFICIENTE A USAR PARA OBTENER EL MONTO DE LA JUBILACION
        $PORSOBPORMAX = Session::metObtener('PORSOBPORMAX'); //PORCENTAJE MAXIMO PARA ESTABLECER EL SUELDO DEL PENSIONADO X SOBREVIVIENTE CON RESPECTO A SU JUBILACION
        $CODSUELDOBAS = Session::metObtener('CODSUELDOBAS');//CODIGO DEL CONCEPTO DE SUELDO BASICO
        $CODPRIANIOSERV = Session::metObtener('CODPRIANIOSERV');//CODIGO DEL CONCEPTO PRIMAS POR AÑOS DE SERVICIO
        /*****************************************PARAMETROS DEL SISTEMA PARA VERIFICAR JUBILACION***********************************************/

        /*****************************************VALIDO JUBILACION SI CUMPLE CON LOS REQUISITOS***************************************************/
        $ANIOS_SERVICIO = $anioTotal;
        $ANIOS_SERVICIO_FINAL = $anioTotal;
        $ANIOS_SERVICIO_EXCESO = 0;
        //$EDAD_RESTA=0;
        $REQUISITO=false;
        $REQUISITO_EXCESO=false;
        /*VALIDO*/
        if($edad==0){
            $REQUISITO=false;
        }
        elseif((strcmp($sexo,'MASCULINO')==0) && ($edad >= $EDADJUBM) && ($ANIOS_SERVICIO >= $MINSERVSI)){
            $REQUISITO=true;
        }elseif (strcmp($sexo,'FEMENINO')==0 && $edad >= $EDADJUBF && $ANIOS_SERVICIO >= $MINSERVSI){
            $REQUISITO=true;
        }elseif ($ANIOS_SERVICIO >= $MINSERVNO){
            $REQUISITO=true;
        }else{
            if($ANIOS_SERVICIO > $MINSERVSI){
                if(strcmp($sexo,'MASCULINO')==0){
                    $EDAD_RESTA = $EDADJUBM - $edad;
                }elseif (strcmp($sexo,'FEMENINO')==0){
                    $EDAD_RESTA = $EDADJUBF - $edad;
                }
                if(($ANIOS_SERVICIO - $MINSERVSI) >= $EDAD_RESTA){
                    $REQUISITO_EXCESO=true;
                    $ANIOS_SERVICIO_FINAL -= $EDAD_RESTA;
                    $ANIOS_SERVICIO_EXCESO = $EDAD_RESTA;
                }
            }else{
                $REQUISITO=false;
            }
        }
        /*****************************************VALIDO JUBILACION SI CUMPLE CON LOS REQUISITOS***************************************************/



        /****************************************CALCULO DE MOSNTOS TOTALES IDEPENDIENTEMENTE DE LA VERIFICACION ANTERIOR***************************/
        /*********************************************************************************************/
        $cod_detalle = 'I';
        /*consulto miscelaneo tipo de concepto*/
        $miscelaneoTipoConcepto = $this->atEmpleados->metMostrarSelect('TDCNM');
        /*recorro el arreglo para obtener el id del miscelaneo detalle tipo concepto*/
        foreach($miscelaneoTipoConcepto as $d){
            if(strcmp($d['cod_detalle'],$cod_detalle)==0){
                $id_tipo_concepto = $d['pk_num_miscelaneo_detalle'];
            }
        }
        //consulto los conceptos disponibles de nomina para el calculo de las jubilaciones y pensiones
        $conceptos = $this->atPensionesSobreviviente->metConsultarConceptosJP($id_tipo_concepto);
        $sumaSB=0;
        $sumaPR=0;
        foreach($conceptos as $dat){
            $concepto = $dat['pk_num_concepto'];
            $relacion = $this->atPensionesSobreviviente->metConsultarRelacionSueldos($idEmpleado,$concepto);
            foreach($relacion as $reg){
                if($reg['fk_nmb002_num_concepto']==$CODSUELDOBAS){//sueldo basico
                    $sumaSB = $sumaSB+$reg['monto'];
                }
                if($reg['fk_nmb002_num_concepto']==$CODPRIANIOSERV){//primas por años de servicio
                    $sumaPR = $sumaPR+$reg['monto'];
                }
            }
        }

        /*********************************************************************************************/

        $TOTAL = $sumaSB + $sumaPR;
        $SUELDO_BASE = $TOTAL /24;
        $PORCENTAJE  = $ANIOS_SERVICIO_FINAL * $COEPORCJUB;
        $COEFICIENTE = $PORCENTAJE / 100;
        $MONTO_JUBILACION = $SUELDO_BASE * $COEFICIENTE;
        $MONTO_PENSION = $MONTO_JUBILACION * $PORSOBPORMAX /100;

        if($REQUISITO || $REQUISITO_EXCESO){
            $req = array(
                'requisito' => '1',
                'anio_servicio_exceso' => $ANIOS_SERVICIO_EXCESO,
                'sexo' => $sexo,
                'edad' => $edad,
                'sueldo' => number_format($sumaSB,2,',','.'),
                'primas' => number_format($sumaPR,2,',','.'),
                'total' => number_format($TOTAL,2,',','.'),
                'porcentaje' => $PORCENTAJE,
                'base' => number_format($SUELDO_BASE,2,',','.'),
                'jubilacion' => number_format($MONTO_JUBILACION,2,',','.'),
                'pension' => number_format($MONTO_PENSION,2,',','.')
            );
        }else{
            $req = array(
                'requisito' => '1',
                'anio_servicio_exceso' => $ANIOS_SERVICIO_EXCESO,
                'sexo' => $sexo,
                'edad' => $edad,
                'sueldo' => number_format($sumaSB,2,',','.'),
                'primas' => number_format($sumaPR,2,',','.'),
                'total' => number_format($TOTAL,2,',','.'),
                'porcentaje' => $PORCENTAJE,
                'base' => number_format($SUELDO_BASE,2,',','.'),
                'jubilacion' => number_format($MONTO_JUBILACION,2,',','.'),
                'pension' => number_format($MONTO_PENSION,2,',','.')
            );
        }
        /****************************************CALCULO DE MOSNTOS TOTALES IDEPENDIENTEMENTE DE LA VERIFICACION ANTERIOR***************************/

        echo json_encode($req);

    }


    // Método que muestra el listado de antecedentes de servicio
    public function metObtenerAntecedentes()
    {
        $pkNumEmpleado = $_POST['pk_num_empleado'];

        /*$cod_detalle identifica al miscelaneo tipo entidad, G quiere decir gubernamental*/
        /*los antecedentes de servicios son todas aquellas experiencias laborales tipo gubernamentales*/
        $cod_detalle = 'G';
        /*consulto el miscelaneo tipo de entidad*/
        $miscelaneoTipoEntidad = $this->atEmpleados->metMostrarSelect('TIPOENTE');
        /*recorro el arreglo para obtener el id del miscelaneo detalle*/
        foreach($miscelaneoTipoEntidad as $d){
            if(strcmp($d['cod_detalle'],$cod_detalle)==0){
                $id_tipo_entidad = $d['pk_num_miscelaneo_detalle'];
                $entidad = $d['ind_nombre_detalle'];
            }
        }
        $antecedente = $this->atPensionesSobreviviente->metConsultarAntecedente($pkNumEmpleado,$id_tipo_entidad);

        $i = 0;
        $acumuladorServicio = 0;

        if(count($antecedente)==0){

            $datosServicio[] = array (
                'fechaIngreso' => '',
                'fechaEgreso' => '',
                'tiempoServicio' => '',
                'empresa' => '',
                'dia' => '',
                'mes'=> '',
                'anio' => ''
            );
        }else{

            foreach($antecedente as $ant){
                $fechaIngresoAnt = $ant['fec_ingreso'];
                $fechaEgresoAnt = $ant['fec_egreso'];

                $fechaIngreso = $ant['fecha_ingreso'];
                $fechaEgreso = $ant['fecha_egreso'];

                $tiempoServicioAnt = $this->metTiempoServicio($fechaIngresoAnt, $fechaEgresoAnt);
                $anio = $tiempoServicioAnt['anio'];
                $mes = $tiempoServicioAnt['mes'];
                $dia = $tiempoServicioAnt['dia'];
                $acumuladorServicio = $acumuladorServicio + $anio;
                $empresa = $ant['ind_empresa'];
                $datosServicio[] = array (
                    'fechaIngreso' => $fechaIngreso,
                    'fechaEgreso' => $fechaEgreso,
                    'tiempoServicio' => $acumuladorServicio,
                    'empresa' => $empresa,
                    'dia' => $dia,
                    'mes'=> $mes,
                    'anio' => $anio
                );
                $i++;
            }
        }


        echo json_encode($datosServicio);
    }

    // Método que permite calcular el tiempo de servicio total
    public function metCalcularAntecedentesTotal()
    {
        $pkNumEmpleado = $_POST['pk_num_empleado'];
        /*$cod_detalle identifica al miscelaneo tipo entidad, G quiere decir gubernamental*/
        /*los antecedentes de servicios son todas aquellas experiencias laborales tipo gubernamentales*/
        $cod_detalle = 'G';

        /*consulto el miscelaneo tipo de entidad*/
        $miscelaneoTipoEntidad = $this->atEmpleados->metMostrarSelect('TIPOENTE');

        /*recorro el arreglo para obtener el id del miscelaneo detalle*/
        foreach($miscelaneoTipoEntidad as $d){

            if(strcmp($d['cod_detalle'],$cod_detalle)==0){
                $id_tipo_entidad = $d['pk_num_miscelaneo_detalle'];
            }

        }

        $antecedente = $this->atPensionesSobreviviente->metConsultarAntecedente($pkNumEmpleado,$id_tipo_entidad);

        $acumuladorAnio = 0;
        $acumuladorMes = 0;
        $acumuladorDia = 0;

        if(count($antecedente)==0){

            $acumuladorAnio = 0;
            $acumuladorMes = 0;
            $acumuladorDia = 0;

            $diaAnt = 0;
            $mesAnt = 0;
            $anioAnt = 0;

        }else{
            foreach($antecedente as $ant) {
                $fechaIngresoAnt = $ant['fec_ingreso'];
                $fechaEgresoAnt = $ant['fec_egreso'];
                $tiempoServicioAnt = $this->metTiempoServicio($fechaIngresoAnt, $fechaEgresoAnt);
                $anio = $tiempoServicioAnt['anio'];
                $mes = $tiempoServicioAnt['mes'];
                $dia = $tiempoServicioAnt['dia'];
                $acumuladorAnio = $acumuladorAnio + $anio;
                $acumuladorMes = $acumuladorMes + $mes;
                $acumuladorDia = $acumuladorDia + $dia;
            }

            // Obtengo el total de servicio en cuanto a antecedente
            $totalAntecedente = $this->metObtenerServicio($acumuladorDia, $acumuladorMes, $acumuladorAnio);
            $diaAnt = $totalAntecedente['dia'];
            $mesAnt = $totalAntecedente['mes'];
            $anioAnt = $totalAntecedente['anio'];
        }


        // Calculo el total de antecedentes de servicio en la institucion
        $servicioEmpleado = $this->atEmpleados->metEstadoEmpleado($pkNumEmpleado);
        $fechaIngreso = $servicioEmpleado['fecha_ingreso'];
        $fechaActual = date('Y-m-d');
        $tiempoServicioInst = $this->metTiempoServicio($fechaIngreso, $fechaActual);
        $diaInst = $tiempoServicioInst['dia'];
        $mesInst = $tiempoServicioInst['mes'];
        $anioInst = $tiempoServicioInst['anio'];

        // Tiempo total de Servicio
        $diaTotalPrevio = $diaInst + $diaAnt;
        $mesTotalPrevio = $mesInst + $mesAnt;
        $anioTotalPrevio = $anioInst + $anioAnt;
        $total = $this->metObtenerServicio($diaTotalPrevio, $mesTotalPrevio, $anioTotalPrevio);
        $diaTotal = $total['dia'];
        $mesTotal = $total['mes'];
        $anioTotal = $total['anio'];

        /************OJO****************/
        if($mesTotal >= 8){
            $anioTotal++;
            $mesTotal=0;
            $diaTotal=0;
        }
        /**************OJO***************/

        // Array
        $datosServicio = array (
            'dia' => $diaAnt,
            'mes' => $mesAnt,
            'anio' => $anioAnt,
            'diaInst' => $diaInst,
            'mesInst' => $mesInst,
            'anioInst' => $anioInst,
            'diaTotal' => $diaTotal,
            'mesTotal' => $mesTotal,
            'anioTotal' => $anioTotal
        );
        echo json_encode($datosServicio);
    }

    // Método que permite calcular el tiempo de servicio de un empleado
    public function metTiempoServicio($fechaIngreso, $fechaEgreso)
    {
        $fechaInicial = new DateTime($fechaIngreso);
        $fechaFinal = new DateTime($fechaEgreso);
        $interval = $fechaInicial->diff($fechaFinal);
        $datosServicio = array(
            'anio' => $interval->format('%y'),
            'mes' => $interval->format('%m'),
            'dia' => $interval->format('%d')
        );
        return $datosServicio;
    }

    // Método que se encarga de obtener el total de antecedentes
    public function metObtenerServicio($acumuladorDia, $acumuladorMes, $acumuladorAnio)
    {

        $_Dias_A_Meses = intval($acumuladorDia / 30);
        $acumuladorMes += $_Dias_A_Meses;
        $_Meses_A_Anios = intval($acumuladorMes / 12);
        $acumuladorAnio += $_Meses_A_Anios;
        $Dias  = $acumuladorDia - (intval($acumuladorDia / 30) * 30);
        $Meses = $acumuladorMes - (intval($acumuladorMes / 12) * 12);
        $Anios = $acumuladorAnio;

        $totalAntecedente = array(
            'anio' => $Anios,
            'mes' => $Meses,
            'dia' => $Dias
        );
        return $totalAntecedente;
    }


    //Método para obtener la relacion de sueldos del empleado
    public function metConsultarRelacionSueldos()
    {

        $idEmpleado = $this->metObtenerInt('pk_num_empleado');
        $concepto   = $this->metObtenerInt('concepto');

        $cod_detalle = 'I';

        /*consulto miscelaneo tipo de concepto*/
        $miscelaneoTipoConcepto = $this->atEmpleados->metMostrarSelect('TDCNM');

        /*recorro el arreglo para obtener el id del miscelaneo detalle tipo concepto*/
        foreach($miscelaneoTipoConcepto as $d){

            if(strcmp($d['cod_detalle'],$cod_detalle)==0){
                $id_tipo_concepto = $d['pk_num_miscelaneo_detalle'];
            }

        }

        //consulto los conceptos disponibles de nomina para el calculo de las jubilaciones y pensiones
        $relacion = $this->atPensionesSobreviviente->metConsultarRelacionSueldos($idEmpleado,$concepto);

        echo json_encode($relacion);


    }

    //Metodo para obtener los benefiarios de la pension del empleado
    public function metConsultarBeneficiarios()
    {
        $idEmpleado = $this->metObtenerInt('pk_num_empleado');

        $this->atCargaFamiliar = $this->metCargarModelo('cargaFamiliar','gestion');

        $cargaFamiliar = $this->atCargaFamiliar->metCargaFamiliarEmpleado($idEmpleado);



        $flag_cumple=false;
        //RECORRO EL ARRAY DE RESULTADOS PARA VERIFICAR SI CUMPLE CON LOS REQUISITOS PARA SER BENEFICIARIOS
        $i=0;

        foreach($cargaFamiliar as $data){

            $f_n = explode("-",$data['fec_nacimiento']);
            $f_a = date("d-m-Y");
            list($edadBeneficiario, $EdadMeses, $EdadDias) = $this->metCalcularEdadAnioServicio($f_n[2]."-".$f_n[1]."-".$f_n[0],$f_a);

            if($data['detalle_parentesco']=="CB"){
                $flag_cumple=true;
            }
            if($data['detalle_parentesco']=="ES" && $data['detalle_sexo']=="M"){
                $flag_cumple=true;
            }
            if($data['detalle_parentesco']=="ES" && $data['detalle_sexo']=="F"){
                $flag_cumple=true;
            }
            if($data['detalle_parentesco']=="HI" && $edadBeneficiario<=14){
                $flag_cumple=true;
            }
            if($data['detalle_parentesco']=="HI" && $data['num_falg_estudia']==1 && $edadBeneficiario<=18){
                $flag_cumple=true;
            }
            if($data['num_flag_discapacidad']==1){
                $flag_cumple=true;
            }

            if($flag_cumple){

                $beneficiarios[] = array(

                    'pk_num_persona' => $data['pk_num_persona'],
                    'cedula' => $data['ind_cedula_documento'],
                    'nombre' => $data['ind_nombre1']." ".$data['ind_nombre2']." ".$data['ind_apellido1']." ".$data['ind_apellido2'],
                    'sexo' => $data['sexo'],
                    'parentesco' => $data['parentesco'],
                    'fecha_nacimiento' => $f_n[2]."-".$f_n[1]."-".$f_n[0],
                    'edad' => $edadBeneficiario

                );

                // $this->metConsultarBeneficiariosSel($beneficiarios);
            }

        }

        echo json_encode($beneficiarios);

    }

    //Metodo para obtener los benefiarios de la pension del empleado
    public function metConsultarBeneficiariosSel()
    {
        $idEmpleado = $this->metObtenerInt('pk_num_empleado');
        $this->atCargaFamiliar = $this->metCargarModelo('cargaFamiliar','gestion');
        $cargaFamiliar = $this->atCargaFamiliar->metCargaFamiliarEmpleado($idEmpleado);

        //RECORRO EL ARRAY DE RESULTADOS PARA VERIFICAR SI CUMPLE CON LOS REQUISITOS PARA SER BENEFICIARIOS
        $i=0;

        foreach($cargaFamiliar as $data){
            $flag_cumple=false;
            $f_n = explode("-",$data['fec_nacimiento']);
            $f_a = date("d-m-Y");
            list($edadBeneficiario, $EdadMeses, $EdadDias) = $this->metCalcularEdadAnioServicio($f_n[2]."-".$f_n[1]."-".$f_n[0],$f_a);

            if($data['detalle_parentesco']=="CB"){
                $flag_cumple=true;
            }
            if($data['detalle_parentesco']=="ES" && $data['detalle_sexo']=="M"){
                $flag_cumple=true;
            }
            if($data['detalle_parentesco']=="ES" && $data['detalle_sexo']=="F"){
                $flag_cumple=true;
            }
            if($data['detalle_parentesco']=="HI" && $edadBeneficiario<=14){
                $flag_cumple=true;
            }
            if($data['detalle_parentesco']=="HI" && $data['num_falg_estudia']==1 && $edadBeneficiario<=18){
                $flag_cumple=true;
            }
            if($data['num_flag_discapacidad']==1){
                $flag_cumple=true;
            }

            if($flag_cumple){

                $beneficiarios[] = array(

                    'pk_num_persona' => $data['pk_num_persona'],
                    'nombre' => $data['ind_nombre1']." ".$data['ind_nombre2']." ".$data['ind_apellido1']." ".$data['ind_apellido2']
                );

            }

        }

        echo json_encode($beneficiarios);
    }

    public function metModificar()
    {
        /**********************************************************************/
        $complementosCss = array(
            'bootstrap-datepicker/datepicker',
            'wizard/wizardfa6c',
            'select2/select201ef'
        );
        $complementoJs = array(
            'bootstrap-datepicker/bootstrap-datepicker',
            'wizard/jquery.bootstrap.wizard.min',
            'select2/select2.min',
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min',
            'inputmask/jquery.inputmask.bundle.min'
        );
        $js= array('materialSiace/App','materialSiace/core/demo/DemoFormComponents','materialSiace/core/demo/DemoFormWizard');

        $this->atVista->metCargarCssComplemento($complementosCss);
        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);


        $idPensionSobreviviente = $this->metObtenerInt('idPensionSobreviviente');
        $valido  = $this->metObtenerInt('valido');

        if($valido==1) {

            $formTxt = $this->metObtenerTexto('form', 'txt');
            $formInt = $this->metObtenerInt('form', 'int');

            if (!empty($formInt)) {
                foreach ($formInt as $tituloInt => $valorInt) {
                    if (!empty($formInt[$tituloInt])) {
                        if((strcmp($tituloInt,'num_ultimo_sueldo')==0) || (strcmp($tituloInt,'num_monto_pension')==0) || (strcmp($tituloInt,'sueldo')==0) || (strcmp($tituloInt,'prima')==0) || (strcmp($tituloInt,'total')==0) || (strcmp($tituloInt,'porcentaje')==0) || (strcmp($tituloInt,'s_base')==0) || (strcmp($tituloInt,'jubilacion')==0) ){
                            $validacion[$tituloInt] = str_replace(",", ".", preg_replace('/[^0-9 ,]/i', '', $valorInt));
                        } else {
                            $validacion[$tituloInt] = $valorInt;
                        }
                    } else {
                        $validacion[$tituloInt] = '';
                    }
                }
            }
            if (!empty($formTxt)) {
                foreach ($formTxt as $tituloTxt => $valorTxt) {
                    if (!empty($formTxt[$tituloTxt])) {
                        $validacion[$tituloTxt] = $valorTxt;
                    } else {
                        $validacion[$tituloTxt] = '';

                    }
                }
            }


            if($idPensionSobreviviente != 0){

                $datos = array(
                    $validacion['fk_nmb001_num_tipo_nomina'],
                    $validacion['fk_a006_num_miscelaneo_detalle_tipotrab'],
                    $validacion['fk_rhc032_num_motivo_cese'],
                    $validacion['fec_fecha_egreso'],
                    $validacion['txt_observacion_egreso'],
                    $validacion['num_situacion_trabajo'],
                    $validacion['ind_resolucion'],
                    $validacion['txt_observacion_pre'],
                    $validacion['num_monto_pension']
                );

                $resultado = $this->atPensionesSobreviviente->metModificarPensionesSobreviviente($idPensionSobreviviente,$datos);

                if(is_array($resultado)){
                    $validacion['status'] = 'error';
                    $validacion['detalleERROR'] = $resultado;
                    echo json_encode($validacion);
                    exit;
                }else{
                    $validacion['status']='modificar';
                    echo json_encode($validacion);
                    exit;
                }

            }

        }

        /***********************************************************************/
        $datosBD = $this->atPensionesSobreviviente->metMostrarPensionesSobreviviente($idPensionSobreviviente);
        $this->atVista->assign('formDB',$datosBD);
        $datosOperacionesPR = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'PR');
        $this->atVista->assign('formDBoperacionesPR',$datosOperacionesPR);
        $datosOperacionesCO = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'CO');
        $this->atVista->assign('formDBoperacionesCO',$datosOperacionesCO);
        $datosOperacionesAP = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AP');
        $this->atVista->assign('formDBoperacionesAP',$datosOperacionesAP);
        $datosOperacionesAN = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AN');
        $this->atVista->assign('formDBoperacionesAN',$datosOperacionesAN);
        /**********************************************************************/

        $this->metMostrarDatos($idPensionSobreviviente,$datosBD['fk_rhb001_num_empleado']);

        $EstadoRegistro = array('0'=>'NO ACTIVO','1'=>'ACTIVO');
        $this->atVista->assign('EstadoRegistro',$EstadoRegistro);

        $usuario = Session::metObtener('idUsuario');
        $obtenerEmpleado = $this->atEmpleados->metUsuario($usuario, 1);
        $pkNumEmpleado = $obtenerEmpleado['pk_num_empleado'];
        $datosEmpleado = $this->atEmpleados->metEstadoEmpleado($pkNumEmpleado);

        $this->atVista->assign('estadoEmpleado',$datosEmpleado);

        $periodo = date("Y-m");#periodo actual
        $fecha   = date("d-m-Y");#fecha actual


        $miscMotivoPension = $this->atEmpleados->metMostrarSelect('MOTIPEN');
        $this->atVista->assign('MotivoPension',$miscMotivoPension);

        $this->atVista->assign('listadoTipoNomina',$this->atTipoNimina->metListarTipoNomina());
        $this->atVista->assign('listadoTipoTrabajador',$this->atEmpleados->metMostrarSelect('TIPOTRAB'));
        $this->atVista->assign('listadoMotivoCese',$this->atMotivoCese->metConsultarMotivoCese());

        $this->atVista->assign('idUsuario',$this->atIdUsuario);
        $this->atVista->assign('nombreUsuario',Session::metObtener('nombreUsuario'));

        $this->atVista->assign('periodo',$periodo);
        $this->atVista->assign('fecha',$fecha);

        $this->atVista->assign('idPensionSobreviviente',$idPensionSobreviviente);
        $this->atVista->assign('proceso','Modificar');
        $this->atVista->metRenderizar('form','modales');

    }

    public function metVer()
    {
        /**********************************************************************/
        $complementosCss = array(
            'bootstrap-datepicker/datepicker',
            'wizard/wizardfa6c',
            'select2/select201ef'
        );
        $complementoJs = array(
            'bootstrap-datepicker/bootstrap-datepicker',
            'wizard/jquery.bootstrap.wizard.min',
            'select2/select2.min',
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min',
            'inputmask/jquery.inputmask.bundle.min'
        );
        $js= array('materialSiace/App','materialSiace/core/demo/DemoFormComponents','materialSiace/core/demo/DemoFormWizard');

        $this->atVista->metCargarCssComplemento($complementosCss);
        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);


        $idPensionSobreviviente = $this->metObtenerInt('idPensionSobreviviente');
        /***********************************************************************/
        $datosBD = $this->atPensionesSobreviviente->metMostrarPensionesSobreviviente($idPensionSobreviviente);
        $this->atVista->assign('formDB',$datosBD);
        $datosOperacionesPR = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'PR');
        $this->atVista->assign('formDBoperacionesPR',$datosOperacionesPR);
        $datosOperacionesCO = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'CO');
        $this->atVista->assign('formDBoperacionesCO',$datosOperacionesCO);
        $datosOperacionesAP = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AP');
        $this->atVista->assign('formDBoperacionesAP',$datosOperacionesAP);
        $datosOperacionesAN = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AN');
        $this->atVista->assign('formDBoperacionesAN',$datosOperacionesAN);
        /**********************************************************************/

        $this->metMostrarDatos($idPensionSobreviviente,$datosBD['fk_rhb001_num_empleado']);

        $EstadoRegistro = array('0'=>'NO ACTIVO','1'=>'ACTIVO');
        $this->atVista->assign('EstadoRegistro',$EstadoRegistro);

        $usuario = Session::metObtener('idUsuario');
        $obtenerEmpleado = $this->atEmpleados->metUsuario($usuario, 1);
        $pkNumEmpleado = $obtenerEmpleado['pk_num_empleado'];
        $datosEmpleado = $this->atEmpleados->metEstadoEmpleado($pkNumEmpleado);

        $this->atVista->assign('estadoEmpleado',$datosEmpleado);

        $periodo = date("Y-m");#periodo actual
        $fecha   = date("d-m-Y");#fecha actual


        $miscMotivoPension = $this->atEmpleados->metMostrarSelect('MOTIPEN');
        $this->atVista->assign('MotivoPension',$miscMotivoPension);

        $this->atVista->assign('listadoTipoNomina',$this->atTipoNimina->metListarTipoNomina());
        $this->atVista->assign('listadoTipoTrabajador',$this->atEmpleados->metMostrarSelect('TIPOTRAB'));
        $this->atVista->assign('listadoMotivoCese',$this->atMotivoCese->metConsultarMotivoCese());

        $this->atVista->assign('idUsuario',$this->atIdUsuario);
        $this->atVista->assign('nombreUsuario',Session::metObtener('nombreUsuario'));

        $this->atVista->assign('periodo',$periodo);
        $this->atVista->assign('fecha',$fecha);

        $this->atVista->assign('idPensionSobreviviente',$idPensionSobreviviente);
        $this->atVista->assign('proceso','Ver');
        $this->atVista->metRenderizar('form','modales');

    }



    /*PERMITE MOSTRAR LOS DATOS EN FORMULARIOS*/
    public function metMostrarDatos($id_pension,$empleado)
    {
        /*************************************************************************/
        $resultado = $this->atPensionesSobreviviente->metObtenerDatosEmpleado($empleado);

        $f_n    = explode("-",$resultado['fec_nacimiento']);
        $f_i    = explode("-",$resultado['fec_ingreso']);
        $f_a    = date("d-m-Y");
        #edad y años de servicio
        $dias = mktime(0,0,0,$f_n[1],$f_n[2],$f_n[0]);
        $edad= (int)((time()-$dias)/31556926);
        list($anio_serv, $MesesServicio, $DiasServicio) = $this->metCalcularEdadAnioServicio($f_i[2]."-".$f_i[1]."-".$f_i[0],$f_a);

        $this->atVista->assign('edad',$edad);
        $this->atVista->assign('anio_servicio',$anio_serv);
        $this->atVista->assign('fec_ingreso',$resultado['fec_ingreso']);
        /*************************************************************************/
        /****ANTECEDENTES DE SERVICIO DEL EMPLEADO******/
        $antecedentes_servicio = $this->atPensionesSobreviviente->metConsultarAntecedentesServicio($empleado,$id_pension);
        $this->atVista->assign('antecedentes',$antecedentes_servicio);
        /*$cod_detalle identifica al miscelaneo tipo entidad, G quiere decir gubernamental*/
        /*los antecedentes de servicios son todas aquellas experiencias laborales tipo gubernamentales*/
        $cod_detalle = 'G';
        /*consulto el miscelaneo tipo de entidad*/
        $miscelaneoTipoEntidad = $this->atEmpleados->metMostrarSelect('TIPOENTE');
        /*recorro el arreglo para obtener el id del miscelaneo detalle*/
        foreach($miscelaneoTipoEntidad as $d){
            if(strcmp($d['cod_detalle'],$cod_detalle)==0){
                $id_tipo_entidad = $d['pk_num_miscelaneo_detalle'];
            }
        }
        $antecedente = $this->atPensionesSobreviviente->metConsultarAntecedente($empleado,$id_tipo_entidad);
        $acumuladorAnio = 0;
        $acumuladorMes = 0;
        $acumuladorDia = 0;
        foreach($antecedente as $ant) {
            $fechaIngresoAnt = $ant['fec_ingreso'];
            $fechaEgresoAnt = $ant['fec_egreso'];
            $tiempoServicioAnt = $this->metTiempoServicio($fechaIngresoAnt, $fechaEgresoAnt);
            $anio = $tiempoServicioAnt['anio'];
            $mes = $tiempoServicioAnt['mes'];
            $dia = $tiempoServicioAnt['dia'];
            $acumuladorAnio = $acumuladorAnio + $anio;
            $acumuladorMes = $acumuladorMes + $mes;
            $acumuladorDia = $acumuladorDia + $dia;
        }
        // Calculo el total de antecedentes de servicio en la institucion
        $servicioEmpleado = $this->atEmpleados->metEstadoEmpleado($empleado);
        $fechaIngreso = $servicioEmpleado['fecha_ingreso'];
        $fechaActual = date('Y-m-d');
        $tiempoServicioInst = $this->metTiempoServicio($fechaIngreso, $fechaActual);
        $diaInst = $tiempoServicioInst['dia'];
        $mesInst = $tiempoServicioInst['mes'];
        $anioInst = $tiempoServicioInst['anio'];
        // Obtengo el total de servicio en cuanto a antecedente
        $totalAntecedente = $this->metObtenerServicio($acumuladorDia, $acumuladorMes, $acumuladorAnio);
        $diaAnt = $totalAntecedente['dia'];
        $mesAnt = $totalAntecedente['mes'];
        $anioAnt = $totalAntecedente['anio'];
        // Tiempo total de Servicio
        $diaTotalPrevio = $diaInst + $diaAnt;
        $mesTotalPrevio = $mesInst + $mesAnt;
        $anioTotalPrevio = $anioInst + $anioAnt;
        $total = $this->metObtenerServicio($diaTotalPrevio, $mesTotalPrevio, $anioTotalPrevio);
        $diaTotal = $total['dia'];
        $mesTotal = $total['mes'];
        $anioTotal = $total['anio'];
        /************OJO****************/
        if($mesTotal >= 8){
            $anioTotal++;
            $mesTotal=0;
            $diaTotal=0;
        }
        /**************OJO***************/
        // Array
        $datosServicio = array (
            'dia' => $diaAnt,
            'mes' => $mesAnt,
            'anio' => $anioAnt,
            'diaInst' => $diaInst,
            'mesInst' => $mesInst,
            'anioInst' => $anioInst,
            'diaTotal' => $diaTotal,
            'mesTotal' => $mesTotal,
            'anioTotal' => $anioTotal
        );
        $this->atVista->assign('i',1);
        $this->atVista->assign('tiempoServicio',$datosServicio);
        /*******ANTECEDENTES DE SERVICIO DEL EMPLEADO**********/


        /*************************RELACION DE SUELDOS***********************************************/
        $CODSUELDOBAS = Session::metObtener('CODSUELDOBAS');//CODIGO DEL CONCEPTO DE SUELDO BASICO
        $CODPRIANIOSERV = Session::metObtener('CODPRIANIOSERV');//CODIGO DEL CONCEPTO PRIMAS POR AÑOS DE SERVICIO
        $PORSOBPORMAX = Session::metObtener('PORSOBPORMAX'); //PORCENTAJE MAXIMO PARA ESTABLECER EL SUELDO DEL PENSIONADO X SOBREVIVIENTE CON RESPECTO A SU JUBILACION

        $cod_detalle = 'I';
        /*consulto miscelaneo tipo de concepto*/
        $miscelaneoTipoConcepto = $this->atEmpleados->metMostrarSelect('TDCNM');
        /*recorro el arreglo para obtener el id del miscelaneo detalle tipo concepto*/
        foreach($miscelaneoTipoConcepto as $d){
            if(strcmp($d['cod_detalle'],$cod_detalle)==0){
                $id_tipo_concepto = $d['pk_num_miscelaneo_detalle'];
            }
        }
        //consulto los conceptos disponibles de nomina para el calculo de las jubilaciones y pensiones
        $conceptos = $this->atPensionesSobreviviente->metConsultarConceptosJP($id_tipo_concepto);
        $this->atVista->assign('conceptos',$conceptos);
        $this->atVista->assign('SB',$CODSUELDOBAS);
        $this->atVista->assign('PR',$CODPRIANIOSERV);
        $this->atVista->assign('i1',1);
        $this->atVista->assign('i2',1);
        $this->atVista->assign('ct','90');
        $sumaSB=0;
        $sumaPR=0;

        foreach($conceptos as $dat){
            $concepto = $dat['pk_num_concepto'];
            if($concepto==$CODSUELDOBAS){
                $relacion = $this->atPensionesSobreviviente->metConsultarRelacionSueldosPension($id_pension,$concepto);
                $this->atVista->assign('relacionSB',$relacion);
                foreach($relacion as $reg){
                    $sumaSB = $sumaSB+$reg['num_monto'];
                }
            }
            if($concepto==$CODPRIANIOSERV){
                $relacion = $this->atPensionesSobreviviente->metConsultarRelacionSueldosPension($id_pension,$concepto);
                $this->atVista->assign('relacionPR',$relacion);
                foreach($relacion as $reg){
                    $sumaPR = $sumaPR+$reg['num_monto'];
                }
            }
        }
        /***********************************RELACION DE SUELDOS********************************************/

        /**************************MONTOS****************************/
        $datos = $this->atPensionesSobreviviente->metMostrarPensionesSobreviviente($id_pension);
        $TOTAL = $sumaSB + $sumaPR;
        $SUELDO_BASE = $TOTAL /24;
        $PORCENTAJE  = $datos['num_coeficiente'] * 100;
        $COEFICIENTE = $datos['num_coeficiente'];
        $MONTO_JUBILACION = $SUELDO_BASE * $COEFICIENTE;
        $MONTO_PENSION = $MONTO_JUBILACION * $PORSOBPORMAX /100;
        /*************************MONTO*********************************/

        $this->atVista->assign('sueldo',$sumaSB);
        $this->atVista->assign('prima',$sumaPR);
        $this->atVista->assign('total',$TOTAL);
        $this->atVista->assign('porcentaje',$PORCENTAJE);
        $this->atVista->assign('base',$SUELDO_BASE);
        $this->atVista->assign('jubilacion',$MONTO_JUBILACION);
        /*******************************BENEFICIARIOS********************************************/
        $beneficiarios = $this->atPensionesSobreviviente->metConsultarBeneficiariosPension($id_pension);

        foreach($beneficiarios as $ben){
            $aux = explode("-",$ben['fecha_nacimiento']);
            $dias = mktime(0,0,0,$aux[1],$aux[0],$aux[2]);
            $edad= (int)((time()-$dias)/31556926);
            $datosBeneficiarios [] = array(
                'pk_num_persona' => $ben['pk_num_persona'],
                'ind_cedula_documento' => $ben['ind_cedula_documento'],
                'nombre_completo' => $ben['nombre_completo'],
                'parentesco' => $ben['parentesco'],
                'sexo' => $ben['sexo'],
                'fec_nacimiento' => $ben['fecha_nacimiento'],
                'edad' => $edad
            );
        }
        $this->atVista->assign('beneficiarios',$datosBeneficiarios);
        /*******************************BENEFICIARIOS********************************************/

        /************************************************************/
        $this->atVista->assign('formDB',$datos);
        /************************************************************/


    }

    public function metAnular()
    {
        /**********************************************************************/
        $complementosCss = array(
            'bootstrap-datepicker/datepicker',
            'wizard/wizardfa6c',
            'select2/select201ef'
        );
        $complementoJs = array(
            'bootstrap-datepicker/bootstrap-datepicker',
            'wizard/jquery.bootstrap.wizard.min',
            'select2/select2.min',
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min'
        );
        $js= array('materialSiace/App','materialSiace/core/demo/DemoFormComponents','materialSiace/core/demo/DemoFormWizard');

        $this->atVista->metCargarCssComplemento($complementosCss);
        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);


        $idPensionSobreviviente = $this->metObtenerInt('idPensionSobreviviente');
        $valido  = $this->metObtenerInt('valido');

        if($valido==1){

            $formTxt = $this->metObtenerTexto('form', 'txt');
            $formInt = $this->metObtenerInt('form', 'int');

            if (!empty($formInt)) {
                foreach ($formInt as $tituloInt => $valorInt) {
                    if (!empty($formInt[$tituloInt])) {
                        if((strcmp($tituloInt,'num_ultimo_sueldo')==0) || (strcmp($tituloInt,'num_monto_pension')==0) || (strcmp($tituloInt,'sueldo')==0) || (strcmp($tituloInt,'prima')==0) || (strcmp($tituloInt,'total')==0) || (strcmp($tituloInt,'porcentaje')==0) || (strcmp($tituloInt,'s_base')==0) || (strcmp($tituloInt,'jubilacion')==0) ){
                            $validacion[$tituloInt] = str_replace(",", ".", preg_replace('/[^0-9 ,]/i', '', $valorInt));
                        } else {
                            $validacion[$tituloInt] = $valorInt;
                        }
                    } else {
                        $validacion[$tituloInt] = '';
                    }
                }
            }
            if (!empty($formTxt)) {
                foreach ($formTxt as $tituloTxt => $valorTxt) {
                    if (!empty($formTxt[$tituloTxt])) {
                        $validacion[$tituloTxt] = $valorTxt;
                    } else {
                        $validacion[$tituloTxt] = '';

                    }
                }
            }

            if($idPensionSobreviviente != 0){


                $resultado = $this->atPensionesSobreviviente->metAnularPensionesSobreviviente($idPensionSobreviviente,$validacion['txt_observacion_anulado']);

                if(is_array($resultado)){
                    $validacion['status'] = 'error';
                    $validacion['detalleERROR'] = $resultado;
                    echo json_encode($validacion);
                    exit;
                }else{
                    $validacion['status']='anular';
                    echo json_encode($validacion);
                    exit;
                }

            }
        }

        /***********************************************************************/
        $datosBD = $this->atPensionesSobreviviente->metMostrarPensionesSobreviviente($idPensionSobreviviente);
        $this->atVista->assign('formDB',$datosBD);
        $datosOperacionesPR = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'PR');
        $this->atVista->assign('formDBoperacionesPR',$datosOperacionesPR);
        $datosOperacionesCO = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'CO');
        $this->atVista->assign('formDBoperacionesCO',$datosOperacionesCO);
        $datosOperacionesAP = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AP');
        $this->atVista->assign('formDBoperacionesAP',$datosOperacionesAP);
        $datosOperacionesAN = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AN');
        $this->atVista->assign('formDBoperacionesAN',$datosOperacionesAN);
        /**********************************************************************/

        $this->metMostrarDatos($idPensionSobreviviente,$datosBD['fk_rhb001_num_empleado']);


        $EstadoRegistro = array('0'=>'NO ACTIVO','1'=>'ACTIVO');
        $this->atVista->assign('EstadoRegistro',$EstadoRegistro);

        $usuario = Session::metObtener('idUsuario');
        $obtenerEmpleado = $this->atEmpleados->metUsuario($usuario, 1);
        $pkNumEmpleado = $obtenerEmpleado['pk_num_empleado'];
        $datosEmpleado = $this->atEmpleados->metEstadoEmpleado($pkNumEmpleado);

        $this->atVista->assign('estadoEmpleado',$datosEmpleado);

        $periodo = date("Y-m");#periodo actual
        $fecha   = date("d-m-Y");#fecha actual

        $miscMotivoPension = $this->atEmpleados->metMostrarSelect('MOTIPEN');
        $this->atVista->assign('MotivoPension',$miscMotivoPension);

        $this->atVista->assign('listadoTipoNomina',$this->atTipoNimina->metListarTipoNomina());
        $this->atVista->assign('listadoTipoTrabajador',$this->atEmpleados->metMostrarSelect('TIPOTRAB'));
        $this->atVista->assign('listadoMotivoCese',$this->atMotivoCese->metConsultarMotivoCese());

        $this->atVista->assign('idUsuario',$this->atIdUsuario);
        $this->atVista->assign('nombreUsuario',Session::metObtener('nombreUsuario'));

        $this->atVista->assign('periodo',$periodo);
        $this->atVista->assign('fecha',$fecha);

        $this->atVista->assign('idPensionSobreviviente',$idPensionSobreviviente);
        $this->atVista->assign('proceso','Anular');
        $this->atVista->metRenderizar('form','modales');

    }


    public function metConformar()
    {
        /**********************************************************************/
        $complementosCss = array(
            'bootstrap-datepicker/datepicker',
            'wizard/wizardfa6c',
            'select2/select201ef'
        );
        $complementoJs = array(
            'bootstrap-datepicker/bootstrap-datepicker',
            'wizard/jquery.bootstrap.wizard.min',
            'select2/select2.min',
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min'
        );
        $js= array('materialSiace/App','materialSiace/core/demo/DemoFormComponents','materialSiace/core/demo/DemoFormWizard');

        $this->atVista->metCargarCssComplemento($complementosCss);
        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);


        $idPensionSobreviviente = $this->metObtenerInt('idPensionSobreviviente');
        $valido  = $this->metObtenerInt('valido');

        if($valido==1){

            $formTxt = $this->metObtenerTexto('form', 'txt');
            $formInt = $this->metObtenerInt('form', 'int');

            if (!empty($formInt)) {
                foreach ($formInt as $tituloInt => $valorInt) {
                    if (!empty($formInt[$tituloInt])) {
                        if((strcmp($tituloInt,'num_ultimo_sueldo')==0) || (strcmp($tituloInt,'num_monto_pension')==0) || (strcmp($tituloInt,'sueldo')==0) || (strcmp($tituloInt,'prima')==0) || (strcmp($tituloInt,'total')==0) || (strcmp($tituloInt,'porcentaje')==0) || (strcmp($tituloInt,'s_base')==0) || (strcmp($tituloInt,'jubilacion')==0) ){
                            $validacion[$tituloInt] = str_replace(",", ".", preg_replace('/[^0-9 ,]/i', '', $valorInt));
                        } else {
                            $validacion[$tituloInt] = $valorInt;
                        }
                    } else {
                        $validacion[$tituloInt] = '';
                    }
                }
            }
            if (!empty($formTxt)) {
                foreach ($formTxt as $tituloTxt => $valorTxt) {
                    if (!empty($formTxt[$tituloTxt])) {
                        $validacion[$tituloTxt] = $valorTxt;
                    } else {
                        $validacion[$tituloTxt] = '';

                    }
                }
            }

            if($idPensionSobreviviente != 0){


                $resultado = $this->atPensionesSobreviviente->metConformarPensionesSobreviviente($idPensionSobreviviente,$validacion['txt_observacion_con']);

                if(is_array($resultado)){
                    $validacion['status'] = 'error';
                    $validacion['detalleERROR'] = $resultado;
                    echo json_encode($validacion);
                    exit;
                }else{
                    $validacion['status']='conformado';
                    echo json_encode($validacion);
                    exit;
                }
            }
        }

        /***********************************************************************/
        $datosBD = $this->atPensionesSobreviviente->metMostrarPensionesSobreviviente($idPensionSobreviviente);
        $this->atVista->assign('formDB',$datosBD);
        $datosOperacionesPR = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'PR');
        $this->atVista->assign('formDBoperacionesPR',$datosOperacionesPR);
        $datosOperacionesCO = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'CO');
        $this->atVista->assign('formDBoperacionesCO',$datosOperacionesCO);
        $datosOperacionesAP = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AP');
        $this->atVista->assign('formDBoperacionesAP',$datosOperacionesAP);
        $datosOperacionesAN = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AN');
        $this->atVista->assign('formDBoperacionesAN',$datosOperacionesAN);
        /**********************************************************************/


        $this->metMostrarDatos($idPensionSobreviviente,$datosBD['fk_rhb001_num_empleado']);


        $EstadoRegistro = array('0'=>'NO ACTIVO','1'=>'ACTIVO');
        $this->atVista->assign('EstadoRegistro',$EstadoRegistro);

        $usuario = Session::metObtener('idUsuario');
        $obtenerEmpleado = $this->atEmpleados->metUsuario($usuario, 1);
        $pkNumEmpleado = $obtenerEmpleado['pk_num_empleado'];
        $datosEmpleado = $this->atEmpleados->metEstadoEmpleado($pkNumEmpleado);

        $this->atVista->assign('estadoEmpleado',$datosEmpleado);

        $periodo = date("Y-m");#periodo actual
        $fecha   = date("d-m-Y");#fecha actual

        $miscMotivoPension = $this->atEmpleados->metMostrarSelect('MOTIPEN');
        $this->atVista->assign('MotivoPension',$miscMotivoPension);

        $this->atVista->assign('listadoTipoNomina',$this->atTipoNimina->metListarTipoNomina());
        $this->atVista->assign('listadoTipoTrabajador',$this->atEmpleados->metMostrarSelect('TIPOTRAB'));
        $this->atVista->assign('listadoMotivoCese',$this->atMotivoCese->metConsultarMotivoCese());

        $this->atVista->assign('idUsuario',$this->atIdUsuario);
        $this->atVista->assign('nombreUsuario',Session::metObtener('nombreUsuario'));

        $this->atVista->assign('periodo',$periodo);
        $this->atVista->assign('fecha',$fecha);

        $this->atVista->assign('idPensionSobreviviente',$idPensionSobreviviente);
        $this->atVista->assign('proceso','Conformar');
        $this->atVista->metRenderizar('form','modales');

    }


    public function metAprobar()
    {
        /**********************************************************************/
        $complementosCss = array(
            'bootstrap-datepicker/datepicker',
            'wizard/wizardfa6c',
            'select2/select201ef'
        );
        $complementoJs = array(
            'bootstrap-datepicker/bootstrap-datepicker',
            'wizard/jquery.bootstrap.wizard.min',
            'select2/select2.min',
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min'
        );
        $js= array('materialSiace/App','materialSiace/core/demo/DemoFormComponents','materialSiace/core/demo/DemoFormWizard');

        $this->atVista->metCargarCssComplemento($complementosCss);
        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);


        $idPensionSobreviviente = $this->metObtenerInt('idPensionSobreviviente');
        $valido  = $this->metObtenerInt('valido');

        if($valido==1){

            $formTxt = $this->metObtenerTexto('form', 'txt');
            $formInt = $this->metObtenerInt('form', 'int');

            if (!empty($formInt)) {
                foreach ($formInt as $tituloInt => $valorInt) {
                    if (!empty($formInt[$tituloInt])) {
                        if((strcmp($tituloInt,'num_ultimo_sueldo')==0) || (strcmp($tituloInt,'num_monto_pension')==0) || (strcmp($tituloInt,'sueldo')==0) || (strcmp($tituloInt,'prima')==0) || (strcmp($tituloInt,'total')==0) || (strcmp($tituloInt,'porcentaje')==0) || (strcmp($tituloInt,'s_base')==0) || (strcmp($tituloInt,'jubilacion')==0) ){
                            $validacion[$tituloInt] = str_replace(",", ".", preg_replace('/[^0-9 ,]/i', '', $valorInt));
                        } else {
                            $validacion[$tituloInt] = $valorInt;
                        }
                    } else {
                        $validacion[$tituloInt] = '';
                    }
                }
            }
            if (!empty($formTxt)) {
                foreach ($formTxt as $tituloTxt => $valorTxt) {
                    if (!empty($formTxt[$tituloTxt])) {
                        $validacion[$tituloTxt] = $valorTxt;
                    } else {
                        $validacion[$tituloTxt] = '';

                    }
                }
            }

            if($idPensionSobreviviente != 0){

                #array de datos
                $datos = array(
                    $validacion['fk_rhb001_num_empleado'],
                    $validacion['fk_nmb001_num_tipo_nomina'],
                    $validacion['fk_a006_num_miscelaneo_detalle_tipotrab'],
                    $validacion['num_situacion_trabajo'],
                    $validacion['fk_rhc032_num_motivo_cese'],
                    $validacion['fec_fecha_egreso'],
                    $validacion['txt_observacion_egreso'],
                    $validacion['ind_resolucion'],
                    $validacion['num_ultimo_sueldo'],
                    $validacion['fk_a001_num_organismo'],
                    $validacion['fk_a004_num_dependencia'],
                    $validacion['fk_rhc063_num_puestos'],
                    $validacion['ind_cargo'],
                    $validacion['ind_periodo'],
                    $validacion['fec_fecha'],
                    $validacion['num_anio_servicio'],
                    $validacion['num_edad'],
                    $validacion['fec_fecha_ingreso'],
                    $validacion['num_monto_pension']
                );


                $resultado = $this->atPensionesSobreviviente->metAprobarPensionesSobreviviente($idPensionSobreviviente,$validacion['txt_observacion_apro'],$datos);

                if(is_array($resultado)){
                    $validacion['status'] = 'error';
                    $validacion['detalleERROR'] = $resultado;
                    echo json_encode($validacion);
                    exit;
                }else{
                    $validacion['status']='aprobado';
                    echo json_encode($validacion);
                    exit;
                }
            }
        }

        /***********************************************************************/
        $datosBD = $this->atPensionesSobreviviente->metMostrarPensionesSobreviviente($idPensionSobreviviente);
        $this->atVista->assign('formDB',$datosBD);
        $datosOperacionesPR = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'PR');
        $this->atVista->assign('formDBoperacionesPR',$datosOperacionesPR);
        $datosOperacionesCO = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'CO');
        $this->atVista->assign('formDBoperacionesCO',$datosOperacionesCO);
        $datosOperacionesAP = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AP');
        $this->atVista->assign('formDBoperacionesAP',$datosOperacionesAP);
        $datosOperacionesAN = $this->atPensionesSobreviviente->metMostrarPensionesSobrevivienteOperaciones($idPensionSobreviviente,'AN');
        $this->atVista->assign('formDBoperacionesAN',$datosOperacionesAN);
        /**********************************************************************/


        $this->metMostrarDatos($idPensionSobreviviente,$datosBD['fk_rhb001_num_empleado']);


        $EstadoRegistro = array('0'=>'NO ACTIVO','1'=>'ACTIVO');
        $this->atVista->assign('EstadoRegistro',$EstadoRegistro);

        $usuario = Session::metObtener('idUsuario');
        $obtenerEmpleado = $this->atEmpleados->metUsuario($usuario, 1);
        $pkNumEmpleado = $obtenerEmpleado['pk_num_empleado'];
        $datosEmpleado = $this->atEmpleados->metEstadoEmpleado($pkNumEmpleado);

        $this->atVista->assign('estadoEmpleado',$datosEmpleado);

        $periodo = date("Y-m");#periodo actual
        $fecha   = date("d-m-Y");#fecha actual

        $miscMotivoPension = $this->atEmpleados->metMostrarSelect('MOTIPEN');
        $this->atVista->assign('MotivoPension',$miscMotivoPension);

        $this->atVista->assign('listadoTipoNomina',$this->atTipoNimina->metListarTipoNomina());
        $this->atVista->assign('listadoTipoTrabajador',$this->atEmpleados->metMostrarSelect('TIPOTRAB'));
        $this->atVista->assign('listadoMotivoCese',$this->atMotivoCese->metConsultarMotivoCese());

        $this->atVista->assign('idUsuario',$this->atIdUsuario);
        $this->atVista->assign('nombreUsuario',Session::metObtener('nombreUsuario'));

        $this->atVista->assign('periodo',$periodo);
        $this->atVista->assign('fecha',$fecha);

        $this->atVista->assign('idPensionSobreviviente',$idPensionSobreviviente);
        $this->atVista->assign('proceso','Aprobar');
        $this->atVista->metRenderizar('form','modales');

    }


    public function metListadoConformar()
    {
        $complementosCss = array(
            'DataTables/jquery.dataTables',
            'DataTables/extensions/dataTables.colVis941e',
            'DataTables/extensions/dataTables.tableTools4029',
            'bootstrap-datepicker/datepicker'
        );
        $complementoJs = array(
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min',
            'bootstrap-datepicker/bootstrap-datepicker'
        );
        $js= array('materialSiace/core/demo/DemoTableDynamic','materialSiace/App','materialSiace/core/demo/DemoFormComponents');

        $this->atVista->metCargarCssComplemento($complementosCss);
        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);

        $this->atVista->assign('proceso','Conformar');
        $this->atVista->assign('listadoPensionesSobreviviente', $this->atPensionesSobreviviente->metListarPensionesSobreviviente('PR'));
        $this->atVista->metRenderizar('listado');
    }


    public function metListadoAprobar()
    {
        $complementosCss = array(
            'DataTables/jquery.dataTables',
            'DataTables/extensions/dataTables.colVis941e',
            'DataTables/extensions/dataTables.tableTools4029',
            'bootstrap-datepicker/datepicker'
        );
        $complementoJs = array(
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min',
            'bootstrap-datepicker/bootstrap-datepicker'
        );
        $js= array('materialSiace/core/demo/DemoTableDynamic','materialSiace/App','materialSiace/core/demo/DemoFormComponents');

        $this->atVista->metCargarCssComplemento($complementosCss);
        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);

        $this->atVista->assign('proceso','Aprobar');
        $this->atVista->assign('listadoPensionesSobreviviente', $this->atPensionesSobreviviente->metListarPensionesSobreviviente('CO'));
        $this->atVista->metRenderizar('listado');
    }

    public function metCalcularEdadAnioServicio($_DESDE,$_HASTA)
    {
        $error = 0;
        $listo = 0;
        if ((strlen($_DESDE)) < 10) $error = 1;
        else {
            list($d, $m, $a) = explode("-", $_HASTA);
            $diaActual = $d;
            $mesActual = $m;
            $annioActual = $a;
            ##
            list($d, $m, $a) = explode("-", $_DESDE);
            $dia = intval($d);
            $mes = intval($m);
            $annio = intval($a);
            $dias = 0;
            $meses = 0;
            $annios = 0;
            ##
            if ($annio > $annioActual || ($annio == $annioActual && $mes > $mesActual) || ($annio == $annioActual && $mes == $mesActual && $dia > $diaActual)) $error = 2;
            else {
                $annios = $annioActual - $annio;
                $meses = $mesActual - $mes;
                $dias = $diaActual - $dia;
                ##
                if ($dias < 0) { $meses--; $dias = 30 + $dias; }
                if ($meses < 0) { $annios--; $meses = 12 + $meses; }
                ##
                if ($dias >= 30) { $meses++; $dias = 0; }
                if ($meses >= 12) { $annios++; $meses = 0; }
                ##
                return array($annios, $meses, $dias);
            }
        }
        if ($error!=0) return array("", "", "");
    }



    public function metBusquedaFiltro()
    {

        $organismo   = $this->metObtenerInt('organismo');
        $dependencia = $this->metObtenerInt('dependencia');
        $estatus_persona  = $this->metObtenerInt('estatus_persona');
        $estatus_empleado = $this->metObtenerInt('estatus_empleado');

        $datos = $this->atEmpleados->metListarEmpleadoOrganizacion($organismo,$dependencia,$estatus_persona,$estatus_empleado);

        echo json_encode($datos);


    }

    public function metBusquedaFiltroListado()
    {
        $organismo   = $this->metObtenerInt('organismo');
        $dependencia = $this->metObtenerInt('dependencia');
        $estatus  = $this->metObtenerTexto('estatus');

        $datos = $this->atPensionesSobreviviente->metListarPensionesSobrevivienteFiltro($organismo,$dependencia,$estatus);

        echo json_encode($datos);

    }




}
