<?php
/*****************************************************************************************
 * DEV: CONTRALORÍA DEL ESTADO SUCRE.
 * MODULO: Control de Eventos.
 * PROGRAMADORES._________________________________________________________________________
 * | # | NOMBRE.              | CORREO.                              | TELÉFONO.
 * | 1 | María B. Rondón R    | dt.sistemas.control@cgesucre.gob.ve  | 0416-3853790
 * | 2 | Maikol J. Isava D    | acc.desarrollo@cgesucre.gob.ve       | 0426-1814058
 * | * |__________________________________________________________________________________
 *****************************************************************************************/
// Esta clase se encarga de gestionar eventos
class gestionEventoControlador extends Controlador
{
	private $atEventoModelo;

	public function __construct()
	{
		parent::__construct();
		Session::metAcceso();
		$this->atHostEmailGevento = Session::metObtener('HOSTEMAILGEVENTO');
        $this->atEmailGevento = Session::metObtener('EMAILGEVENTO');
        $this->atPassEmailGevento = Session::metObtener('PASSWEMAILGEVENTO');
        $this->atIdDetalleOrg = Session::metObtener('IDORGANISMODETALLE');
		$this->atEventoModelo = $this->metCargarModelo('gestionEvento');
	}

	// Método index del controlador
	public function metIndex(){
		$complementosCss = array(
			'DataTables/jquery.dataTables',
			'DataTables/extensions/dataTables.colVis941e',
			'DataTables/extensions/dataTables.tableTools4029',
			'select2/select201ef',
			'bootstrap-datepicker/datepicker',
			'multi-select/multi-select555c',
			'wizard/wizardfa6c',
			'lightGallery-master/dist/css/lightgallery.min'
		);
		$complementosJs = array(
			'select2/select2.min',
			'bootstrap-datepicker/bootstrap-datepicker',
			'inputmask/jquery.inputmask.bundle.min',
			'multi-select/jquery.multi-select',
			'wizard/jquery.bootstrap.wizard.min',
			'lightGallery-master/dist/js/lightgallery.min',
			'lightGallery-master/dist/js/lg-thumbnail.min',
			'lightGallery-master/dist/js/lg-fullscreen.min'
		);
		$js = array(
			'Aplicacion/appFunciones',
			'materialSiace/core/demo/DemoTableDynamic',
			'materialSiace/core/demo/DemoFormWizard',
			'materialSiace/App',
			'materialSiace/core/demo/DemoFormComponents'
		);

		$this->atVista->metCargarCssComplemento($complementosCss);
		$this->atVista->metCargarJsComplemento($complementosJs);
		$this->atVista->metCargarJs($js);
		$validar=array(
			'jquery-validation/dist/jquery.validate.min',
			'jquery-validation/dist/additional-methods.min'
		);
		$this->atVista->metCargarJsComplemento($validar);
		$this->atVista->assign('listadoEvento', $this->atEventoModelo->metListarEvento());
		$this->atVista->metRenderizar('listado');
	}

	//Método que permite registrar un nuevo evento
	public function metNuevoEvento()
	{
		$js = array(
			'materialSiace/core/demo/DemoFormWizard',
			'materialSiace/core/demo/DemoFormComponents'
		);

		$complementosJs = array(
			'select2/select2.min',
			'wizard/jquery.bootstrap.wizard.min',
			'bootstrap-datepicker/bootstrap-datepicker'
		);
		$complementosCss = array(
			'wizard/wizardfa6c',
			'jquery-validation/dist/site-demo',
			'select2/select201ef'

		);

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

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

		if (isset($valido) && $valido == 1) {
			// Paso 1
			$indNombreEvento = $_POST['ind_nombre_evento'];
			$indDescripcionEvento = $_POST['ind_descripcion_evento'];
			$pkNumLugarEvento = $_POST['pk_num_lugar_evento'];
			$pkNumEnte = $_POST['pk_num_ente'];
			$tipoEvento = $_POST['tipo_evento'];
			$fechaInicioPrevio = $_POST['fecha_inicio'];
			$fechaFinPrevio = $_POST['fecha_fin'];
			$horaInicioPrevio = $_POST['hora_inicio'];
			$horarioInicio = $_POST['horario_inicio'];
			$horaFinPrevio = $_POST['hora_fin'];
			$horarioFin = $_POST['horario_fin'];
			$horaTotal = $_POST['hora_total'];
			$fecha_hora = date('Y-m-d H:i:s');
			$fechaRegistro = date('Y-m-d');
			$usuario = Session::metObtener('idUsuario');
			$cantidadTema = $_POST['cantidadTema'];

			// Paso 2
			$cantidadPonente = $_POST['cantidadPonente'];
			$cantidadParticipante = $_POST['cantidadParticipante'];

			$cadenaPonentes = $_POST['cadenaPonentes'];
			$cadenaParticipantes = $_POST['cadenaParticipantes'];
			$cadenaTema = $_POST['cadenaTema'];

			// Paso 3
			if(isset($_POST['ponente'])){ //checkbox de certificados para ponentes (si no está chekeado no es enviado)
				$ponente = $_POST['ponente'];
			} else {
				$ponente = 0;
			}
			if(isset($_POST['participante'])){ //checkbox de certificados para participantes
				$participante = $_POST['participante'];
			} else {
				$participante = 0;
			}
			if(isset($_POST['fondo'])!=''){  //radio para desactivar los fondos
				$fondo = $_POST['fondo'];
			} else {
				$fondo = '';
			}
			// Tratamiento de datos

			if($pkNumEnte == 0)
			{
				$pkNumEnte = NULL;
			}

			// Horas
			$horas = $this->metHoras($horaInicioPrevio, $horaFinPrevio, $horarioInicio, $horarioFin);
			$horaInicio = $horas[0];
			$horaFin = $horas[1];

			// Fechas

			$fechaExplodeInicio = explode("/", $fechaInicioPrevio);
			$fechaInicio = $fechaExplodeInicio[2].'-'.$fechaExplodeInicio[1].'-'.$fechaExplodeInicio[0];
			$fechaExplodeFin = explode("/", $fechaFinPrevio);
			$fechaFin = $fechaExplodeFin[2].'-'.$fechaExplodeFin[1].'-'.$fechaExplodeFin[0];

			// Ponentes-participantes-temas

			$arrayTemasAux = explode("#",$cadenaTema);

			for($i=0; $i< $cantidadTema; $i++)
			{
				$arrayTemas[$i] = explode("/",$arrayTemasAux[$i]);
			}

			$arrayPonentesAux = explode("#",$cadenaPonentes);

			for($i=0; $i< $cantidadPonente; $i++)
			{
				$arrayPonentes[$i] = explode("/", $arrayPonentesAux[$i]);
			}

			$arrayParticipantesAux = explode("#",$cadenaParticipantes);

			for($i=0; $i< $cantidadParticipante; $i++)
			{
				$arrayParticipantes[$i] = explode("/", $arrayParticipantesAux[$i]);
			}

			// GUARDAR

			$pkNumEvento = $this->atEventoModelo->metGuardarEvento($indNombreEvento, $indDescripcionEvento, $pkNumLugarEvento, $tipoEvento, $fechaInicio, $fechaFin, $horaInicio, $horaTotal, $horaFin, $fondo, $fecha_hora, $usuario, $fechaRegistro, $ponente, $participante, $pkNumEnte);
			if($pkNumEvento > 0)//se registro el evento
			{
				//=======registrar tema=============
				for($i=0; $i< $cantidadTema; $i++)
				{
					$this->atEventoModelo->metGuardarTema($pkNumEvento, $fecha_hora, $usuario, $arrayTemas[$i][0]);
				}

				//======registrar ponente ===========

				$tipoPersonaPrevio = $this->atEventoModelo->metConsultarTipoPersona(1);//trae los datos del tipopersona: 4581 (ponente)
				$tipoPersona = $tipoPersonaPrevio['pk_num_miscelaneo_detalle'];//obtenemos el pk del tipo de persona docente para relacionarlo

				for($i=0; $i< $cantidadPonente; $i++)
				{
					$tipoInstruccion = $arrayPonentes[$i][2];
					$indCedulaPonente = $arrayPonentes[$i][0];
					$firmaPonente = $arrayPonentes[$i][3];
					$consultarPersona = $this->atEventoModelo->metConsultarPersona($indCedulaPonente);//trae el pk_persona por la cedula
					$pkNumPersona = $consultarPersona['pk_num_persona'];
					//la asistencia es en ev_c001_persona_evento
					$resp_reg_ponente = $this->atEventoModelo->metGuardarAsistencia($pkNumPersona, $pkNumEvento, $tipoPersona, $usuario, $fecha_hora, 0, 0, $tipoInstruccion, $firmaPonente);
					if($resp_reg_ponente <= 0)
					{
						echo "error al guardar ponente: ".$pkNumPersona."/".$pkNumEvento."/".$tipoPersona."/".$usuario."/".$fecha_hora."/0/0/".$tipoInstruccion."/".$firmaPonente;
						exit;
					}

				}

				//======registrar participante ===========

				$tipoPersonaPrevio = $this->atEventoModelo->metConsultarTipoPersona(2);//trae los datos del tipopersona: 4582 (participante)
				$tipoPersona = $tipoPersonaPrevio['pk_num_miscelaneo_detalle'];

				for($i=0; $i< $cantidadParticipante; $i++)
				{
					$indCedulaParticipante = $arrayParticipantes[$i][0];
					$consultarPersona = $this->atEventoModelo->metConsultarPersona($indCedulaParticipante);
					$pkNumPersona = $consultarPersona['pk_num_persona'];
					//la asistencia es en ev_c001_persona_evento
					$this->atEventoModelo->metGuardarAsistencia($pkNumPersona, $pkNumEvento, $tipoPersona, $usuario, $fecha_hora, 0, 0, 0,0);
				}

				// Retorno
				$fecha = date('d/m/Y');
				$dato = array(
					'pk_num_evento' => $pkNumEvento,
					'ind_nombre_evento' => $indNombreEvento,
					'fecha_registro' => $fecha,
					'fondo' => $fondo
				);
				echo json_encode($dato);
			}
			else
			{
				echo 0;//error al registrar el evento
			}

		}
		else
		{
			$consultarContralor = $this->atEventoModelo->metConsultarContralor();
			$this->atVista->assign('pk_contralor', $consultarContralor["pk_num_empleado"]);//90

			$listarLugar = $this->atEventoModelo->metListarLugar();
			$this->atVista->assign('listarLugar', $listarLugar);
			$listarTema = $this->atEventoModelo->metListarTema();
			$this->atVista->assign('listarTema', $listarTema);
			$listarCertificado = $this->atEventoModelo->metListarCertificado();
			$this->atVista->assign('listarCertificado', $listarCertificado);
			$tipoEvento = $this->atEventoModelo->metMostrarSelect('TIPEV');
			$this->atVista->assign('tipoEvento', $tipoEvento);
			$tipoInstruccion = $this->atEventoModelo->metMostrarSelect('NIVELINS');
			$this->atVista->assign('tipoInstruccion', $tipoInstruccion);
			$listarTipoEnte = $this->atEventoModelo->metListarTipoEnte();
			$this->atVista->assign('tipoEnte', $listarTipoEnte);

			$deps = $this->atEventoModelo->metGetDependencias();
			$this->atVista->assign('deps', $deps);


			$this->atVista->metRenderizar('nuevo', 'modales');
		}
	}

	public function metgetFuncionariosDependencia(){
		if(isset($_POST['dependencia'])){
			$dependencia = $_POST['dependencia'];
		}

		$funcionarios = $this->atEventoModelo->metGetFuncionariosDependencia($dependencia);
		if (!isset($funcionarios)) {
			return json_encode(array('error' => 'Error al obtener funcionarios'));
		}
		echo json_encode($funcionarios);
	}




	// Método que permite transformar las horas de formato estándar a horario militar
	public function metHoras($horaInicioPrevio, $horaFinPrevio, $horarioInicio, $horarioFin)
	{
		// convierto las horas a horario militar
		// Hora Inicio
		$horaInicio = $horaInicioPrevio.$horarioInicio;
		$horaInicio = strtotime($horaInicio);
		$horaInicio = date("H:i:s", $horaInicio);
		// Hora Fin
		$horaFin = $horaFinPrevio.$horarioFin;
		$horaFin = strtotime($horaFin);
		$horaFin = date("H:i:s", $horaFin);
		$horas = array($horaInicio, $horaFin);
		return $horas;
	}

	// Método que permite listar las dependencias del organismo
	public function metBuscarDependencia()
	{
		$pkNumOrganismo = $this->metObtenerInt('pk_num_organismo');
        $usuario = Session::metObtener('idUsuario');
        $idAplicacion = 15;
		$listarDependencia = $this->atEventoModelo->metListarDependencia($pkNumOrganismo, 1, 0, $usuario, $idAplicacion);
		$a = '<div class="form-group floating-label"><select class="form-control dirty" name="pk_num_dependencia" id="pk_num_dependencia"> <option value="">&nbsp;</option>';
		foreach ($listarDependencia as $listarDependencia) {
			$a .= '<option value="' . $listarDependencia['pk_num_dependencia'] . '">' . $listarDependencia['ind_dependencia'] . '</option>';
		}
		$a .= '</select><label for="pk_num_dependencia"><i class="glyphicon glyphicon-briefcase"></i> Dependencia</label></div>';
		echo $a;
	}

	// Método que permite buscar un empleado desde el wizard
	public function metConsultarEmpleado()
	{
		$usuario = Session::metObtener('idUsuario');
		$valorBoton = $_POST['valorBoton'];
		$valor = $_POST['valor'];
		$empleado = $this->atEventoModelo->metUsuario($usuario, 1);
		$pkNumEmpleado = $empleado['pk_num_empleado'];
		$listadoOrganismo = $this->atEventoModelo->metListarOrganismo(0, 1);
		$datosEmpleado = $this->atEventoModelo->metEmpleado($pkNumEmpleado);
		$idAplicacion = 15;
		$listadoDependencia = $this->atEventoModelo->metListarDependencia($datosEmpleado['pk_num_organismo'], 1, 0, $usuario, $idAplicacion);
		$this->atVista->assign('listadoDependencia', $listadoDependencia);
		$datosTrabajador = $this->atEventoModelo->metListarEmpleado();
		// Organismo donde trabaja el empleado
		$empleado = array(
			'pk_num_organismo' => $datosEmpleado['pk_num_organismo'],
			'valorBoton' => $valorBoton,
			'valor' => $valor
		);
		// Envío a la vista
		$this->atVista->assign('emp', $empleado);
		$this->atVista->assign('datosTrabajador', $datosTrabajador);
		$this->atVista->assign('listadoOrganismo', $listadoOrganismo);
		$this->atVista->metRenderizar('buscarEmpleado', 'modales');
	}

	// Método que permite buscar un trabajador
	public function metBuscarTrabajador()
	{
		$pkNumOrganismo = $_POST['pk_num_organismo'];
		$pkNumDependencia = $_POST['pk_num_dependencia'];
		$indCedulaDocumento = $_POST['ind_cedula_documento'];
		$opcionBuscar = $_POST['opcionBuscar'];
		$datosTrabajador = $this->atEventoModelo->metBuscarTrabajador($pkNumOrganismo, $pkNumDependencia, $indCedulaDocumento, $opcionBuscar);
		echo json_encode($datosTrabajador);
	}

	// Método que permite buscar un trabajador
	public function metCargarEmpleado()
	{
		$pkNumPersona = $_POST['pk_num_persona'];
		$datosPersona = $this->atEventoModelo->metBuscarPersona($pkNumPersona);
		$persona = array(
			'nombre' => $datosPersona['ind_nombre1'].' '.$datosPersona['ind_nombre2'].' '.$datosPersona['ind_apellido1'].' '.$datosPersona['ind_apellido2'],
			'ind_cedula_documento' => $datosPersona['ind_cedula_documento'],
			'pk_num_persona' => $datosPersona['pk_num_persona']
		);
		echo json_encode($persona);
	}

	// Método que permite transformar las horas de horario militar a horario estándar
	public function metHorarioEstandar($horaEntrada, $horaSalida)
	{
		// Hora de salida
		$horaExplodeInicio = explode(":", $horaEntrada);
		$horaInicio = $horaExplodeInicio[0];
		$minutoInicio = $horaExplodeInicio[1];

		// Hora de entrada
		$horaExplodeFin = explode(":", $horaSalida);
		$horaFin = $horaExplodeFin[0];
		$minutoFin = $horaExplodeFin[1];

		// Convirtiendo a horario estándar
		// Hora Inicio
		if($horaInicio>12){
			$horaInicioPrevio = $horaInicio - 12;
			$hora_inicio = str_pad($horaInicioPrevio, 2, "0", STR_PAD_LEFT);
		}
		if($horaInicio<=12) {
			$hora_inicio = str_pad($horaInicio, 2, "0", STR_PAD_LEFT);
		}
		// Hora Fin
		if($horaFin>12){
			$horaFinPrevio = $horaFin - 12;
			$hora_fin = str_pad($horaFinPrevio, 2, "0", STR_PAD_LEFT);
		}
		if($horaFin<=12) {
			$hora_fin = str_pad($horaFin, 2, "0", STR_PAD_LEFT);
		}
		// Horario
		// Horario Inicio
		if($horaInicio>=12){
			$horarioInicio = 'PM';
		}
		if($horaInicio<12) {
			$horarioInicio = 'AM';
		}
		//Horario Fin
		if($horaFin>=12){
			$horariofin = 'PM';
		}
		if($horaFin<12) {
			$horariofin = 'AM';
		}
		// Los agrupo en un array
		$datoHorario = array($hora_inicio,$minutoInicio, $hora_fin, $minutoFin, $horarioInicio, $horariofin);
		return $datoHorario;
	}

	// Método que permite visualizar un evento
	public function metVerEvento()
	{
		$complementosCss = array(
			'wizard/wizardfa6c'
		);
		$complementosJs = array(
			'wizard/jquery.bootstrap.wizard.min'
		);
		$js = array(
			'materialSiace/core/demo/DemoFormWizard'
		);
		$this->atVista->metCargarJs($js);
		$this->atVista->metCargarJsComplemento($complementosJs);
		$this->atVista->metCargarCssComplemento($complementosCss);
		$pkNumEvento = $_POST['pk_num_evento'];
		$verEvento = $this->atEventoModelo->metVerEvento($pkNumEvento);
		$horaEntrada = $verEvento['fec_hora_entrada'];
		$horaSalida = $verEvento['fec_hora_salida'];
		$hora = $this->metHorarioEstandar($horaEntrada, $horaSalida);
		$datoHora = array(
			'horaInicio' => $hora[0],
			'minutoInicio' => $hora[1],
			'horaFin' => $hora[2],
			'minutoFin' => $hora[3],
			'horarioInicio' => $hora[4],
			'horarioFin' => $hora[5]
		);
		// Ponente
		$ponente = $this->atEventoModelo->metConsultarTipoPersona(1);
		$participante = $this->atEventoModelo->metConsultarTipoPersona(2);
		// Verifico si se le asigno certificado a cada tipo de persona
		if($verEvento['num_flag_certificado_ponente']>0){
			// Verifico si tiene certificados generados
			$consultarPonente = $this->atEventoModelo->metVerPonente($ponente['pk_num_miscelaneo_detalle'], $pkNumEvento, 2);
			$contadorPonente = count($consultarPonente);
			if($contadorPonente>0){
				$cargarPonente = $this->atEventoModelo->metVerPonente($ponente['pk_num_miscelaneo_detalle'], $pkNumEvento, 2);
			} else {
				$cargarPonente = $this->atEventoModelo->metVerPonente($ponente['pk_num_miscelaneo_detalle'], $pkNumEvento, 1);
			}
		} else {
			$cargarPonente = $this->atEventoModelo->metVerPonente($ponente['pk_num_miscelaneo_detalle'], $pkNumEvento, 1);
		}

		if($verEvento['num_flag_certificado_participante']>0){
			// Verifico si tiene certificados generados
			$consultarParticipante = $this->atEventoModelo->metVerPersona($participante['pk_num_miscelaneo_detalle'], $pkNumEvento, 2);
			$contadorParticipante = count($consultarParticipante);
			if($contadorParticipante>0){
				$cargarParticipante = $this->atEventoModelo->metVerPersona($participante['pk_num_miscelaneo_detalle'], $pkNumEvento, 2);
			} else {
				$cargarParticipante = $this->atEventoModelo->metVerPersona($participante['pk_num_miscelaneo_detalle'], $pkNumEvento, 1);
			}
		} else {
			$cargarParticipante = $this->atEventoModelo->metVerPersona($participante['pk_num_miscelaneo_detalle'], $pkNumEvento, 1);
		}
		$verTema = $this->atEventoModelo->metVerTema($pkNumEvento);
        $listarTipoEnte = $this->atEventoModelo->metListarTipoEnte();
        $this->atVista->assign('tipoEnte', $listarTipoEnte);
		$this->atVista->assign('evento', $verEvento);
		$this->atVista->assign('datoHora', $datoHora);
		$this->atVista->assign('verTema', $verTema);
		$this->atVista->assign('cargarPonente', $cargarPonente);
		$this->atVista->assign('cargarParticipante', $cargarParticipante);
		$this->atVista->metRenderizar('ver', 'modales');
	}

	//Método que permite eliminar un evento
	public function metEliminarEvento()
	{
		$pkNumEvento = $_POST['pk_num_evento'];
		$this->atEventoModelo->metEliminarEvento($pkNumEvento);
		$arrayPost = array(
			'status' => 'OK',
			'pk_num_evento' => $pkNumEvento
		);
		echo json_encode($arrayPost);
	}

	//Método que permite editar un evento
	public function metEditarEvento()
	{
		$pkNumEvento = $this->metObtenerInt('pk_num_evento');
		$valido = $this->metObtenerInt('valido');
		if (isset($valido) && $valido == 1)
		{ //si se cumple es que se estan enviando las modificaciones a bd, si no es que solo se esta cargando la modal para las modificaciones.
			$this->metValidarToken();
			// Paso 1
			$indNombreEvento = $_POST['ind_nombre_evento'];
			$indDescripcionEvento = $_POST['ind_descripcion_evento'];
			$pkNumLugarEvento = $_POST['pk_num_lugar_evento'];
			$tipoEvento = $_POST['tipo_evento'];
			$fechaInicioPrevio = $_POST['fecha_inicio'];
			$fechaFinPrevio = $_POST['fecha_fin'];
			$horaInicioPrevio = $_POST['hora_inicio'];
			$horarioInicio = $_POST['horario_inicio'];
			$horaFinPrevio = $_POST['hora_fin'];
			$horarioFin = $_POST['horario_fin'];
			$horaTotal = $_POST['hora_total'];
			$fecha_hora = date('Y-m-d H:i:s');
			$usuario = Session::metObtener('idUsuario');
			$cantidadTema = $_POST['cantidadTema'];

			if(!isset($_POST['pk_num_ente']) || $_POST['pk_num_ente'] == '0' )
			{
                $pkNumEnte = null;
			}
			else
			{
                $pkNumEnte = $_POST['pk_num_ente'];
			}

            $cadenaPonentes = $_POST['cadenaPonentes'];
            $cadenaParticipantes = $_POST['cadenaParticipantes'];
            $cadenaTema = $_POST['cadenaTema'];

			// Paso 2
			$cantidadPonente = $_POST['cantidadPonente'];
			$cantidadParticipante = $_POST['cantidadParticipante'];
			// Paso 3
			if(isset($_POST['ponente'])){
				$ponente = $_POST['ponente']; //RECIBIRAN CERTIFICADO LOS PONENTES
			} else {
				$ponente = 0; //NO RECIBIRAN
			}
			if(isset($_POST['participante'])){
				$participante = $_POST['participante']; //RECIBIRAN CERTIFICADO LOS PONENTES
			} else {
				$participante = 0; //NO RECIBIRAN
			}

			if(isset($_POST['fondo'])!=''){ //nombre del certificado
				$fondo = $_POST['fondo'];
			} else {
				$fondo = '';
			}
			// Tratamiento de datos
			// Horas
			$horas = $this->metHoras($horaInicioPrevio, $horaFinPrevio, $horarioInicio, $horarioFin);
			$horaInicio = $horas[0];
			$horaFin = $horas[1];
			// Fechas
			$fechaExplodeInicio = explode("/", $fechaInicioPrevio);
			$fechaInicio = $fechaExplodeInicio[2].'-'.$fechaExplodeInicio[1].'-'.$fechaExplodeInicio[0];
			$fechaExplodeFin = explode("/", $fechaFinPrevio);
			$fechaFin = $fechaExplodeFin[2].'-'.$fechaExplodeFin[1].'-'.$fechaExplodeFin[0];
			// Elimino los temas, participantes y ponentes antes de realizar el guardado
			$this->atEventoModelo->metEliminarTema($pkNumEvento);
			$this->atEventoModelo->metEliminarPersona($pkNumEvento);
			// EDITO EL EVENTO
			$this->atEventoModelo->metEditarEvento($indNombreEvento, $indDescripcionEvento, $pkNumLugarEvento, $tipoEvento, $fechaInicio, $fechaFin, $horaInicio, $horaTotal, $horaFin, $fondo, $fecha_hora, $usuario, $ponente, $participante, $pkNumEvento, $pkNumEnte);

			// Ponentes-participantes-temas

            $arrayTemasAux = explode("#",$cadenaTema);//VIENE CON UN DELIMITADOR ADICIONAL
            $cantidadTemaCad = count($arrayTemasAux)-1;//ELIMINAMOS EL INDICE DE MAS

            for($i=0; $i< $cantidadTemaCad; $i++)
            {
                $arrayTemas[$i] = explode("/",$arrayTemasAux[$i]); //SE CREA UNA MATRIZ CON TODOS LOS TEMAS
            }

            $arrayPonentesAux = explode("#",$cadenaPonentes);

            $cantidadPonenteCad = count($arrayPonentesAux)-1;
            for($i=0; $i< $cantidadPonenteCad; $i++)
            {
                $arrayPonentes[$i] = explode("/", $arrayPonentesAux[$i]);
            }

            $arrayParticipantesAux = explode("#",$cadenaParticipantes);
            $cantidadParticipanteCad = count($arrayParticipantesAux)-1;
            for($i=0; $i< $cantidadParticipanteCad; $i++)
            {
                $arrayParticipantes[$i] = explode("/", $arrayParticipantesAux[$i]);
            }

            //GUARDAR TEMAS=============

			for($i=0; $i< $cantidadTemaCad; $i++)
			{
                    $pkNumTemaEvento = $arrayTemas[$i][0];
                    $this->atEventoModelo->metGuardarTema($pkNumEvento, $fecha_hora, $usuario, $pkNumTemaEvento);

            }

            $verEvento = $this->atEventoModelo->metVerEvento($pkNumEvento);
            $ponenteCerificado = $verEvento['num_flag_certificado_ponente'];//si recibiran o no certificado los ponentes 1/0
            $participanteCertificado = $verEvento['num_flag_certificado_participante'];

			// Ponente

            $tipoPersonaPrevio = $this->atEventoModelo->metConsultarTipoPersona(1);
            $tipoPersona = $tipoPersonaPrevio['pk_num_miscelaneo_detalle'];

            for($i=0; $i < $cantidadPonenteCad; $i++)
            {
                $indCedulaPonente = $arrayPonentes[$i][0];
                $tipoInstruccion = $arrayPonentes[$i][2];
                $consultarPersona = $this->atEventoModelo->metConsultarPersona($indCedulaPonente);
                $pkNumPersona = $consultarPersona['pk_num_persona'];
                // Guardo los checkbox
                $culminoPonente = $arrayPonentes[$i][4];
                if($culminoPonente > 0)//culmino el ponente el evento
                {
                    if ($ponenteCerificado > 0) //se entregara certificado a los ponentes
                    {
                        $this->metCargarCertificado($pkNumEvento, $pkNumPersona, $fecha_hora, $usuario);//ASOCIA UNA PERSONA A UN CERTIFICADO
                    }
                }

                $recibirPonente = $arrayPonentes[$i][5];
                $tipoFirma = $arrayPonentes[$i][3];

                $this->atEventoModelo->metGuardarAsistencia($pkNumPersona, $pkNumEvento, $tipoPersona, $usuario, $fecha_hora, $culminoPonente, $recibirPonente, $tipoInstruccion, $tipoFirma);

			}

			// Participante
            $tipoPersonaPrevio = $this->atEventoModelo->metConsultarTipoPersona(2);
            $tipoPersona = $tipoPersonaPrevio['pk_num_miscelaneo_detalle'];
            for($i=0; $i < $cantidadParticipanteCad; $i++)
			{
                $indCedulaParticipante = $arrayParticipantes[$i][0];
                $consultarPersona = $this->atEventoModelo->metConsultarPersona($indCedulaParticipante);
                $pkNumPersona = $consultarPersona['pk_num_persona'];
                $culminoParticipante = $arrayParticipantes[$i][2];
                if($culminoParticipante > 0)
				{
                    if($participanteCertificado>0)
                    {
                        $this->metCargarCertificado($pkNumEvento, $pkNumPersona, $fecha_hora, $usuario);
                    }
				}

                $recibirParticipante = $arrayParticipantes[$i][3];
                $this->atEventoModelo->metGuardarAsistencia($pkNumPersona, $pkNumEvento, $tipoPersona, $usuario, $fecha_hora, $culminoParticipante, $recibirParticipante, 0, 0);

			}


			// Retorno
			$dato = array(
				'pk_num_evento' => $pkNumEvento,
				'ind_nombre_evento' => $verEvento['ind_nombre_evento'],
				'fecha_registro' => $verEvento['fecha_registro'],
				'ind_certificado' => $verEvento['ind_certificado']
			);
			echo json_encode($dato);
			exit;
		}

		//========MODAL EDITAR EVENTO====================
		if (!empty($pkNumEvento)) {
			$js = array(
				'materialSiace/core/demo/DemoFormWizard',
				'materialSiace/core/demo/DemoFormComponents',
			);
			$complementosJs = array(
				'select2/select2.min',
				'wizard/jquery.bootstrap.wizard.min',
				'bootstrap-datepicker/bootstrap-datepicker',
			);
			$complementosCss = array(
				'wizard/wizardfa6c',
				'select2/select201ef'
			);
			$this->atVista->metCargarJs($js);
			$this->atVista->metCargarJsComplemento($complementosJs);
			$this->atVista->metCargarCssComplemento($complementosCss);
			//============================
			$verEvento = $this->atEventoModelo->metVerEvento($pkNumEvento);//trae todos los datos del evento
			$horaEntrada = $verEvento['fec_hora_entrada'];
			$horaSalida = $verEvento['fec_hora_salida'];
			$hora = $this->metHorarioEstandar($horaEntrada, $horaSalida);
			$datoHora = array(
				'horaInicio' => $hora[0],
				'minutoInicio' => $hora[1],
				'horaFin' => $hora[2],
				'minutoFin' => $hora[3],
				'horarioInicio' => $hora[4],
				'horarioFin' => $hora[5]
			);
			// Ponente
			$ponente = $this->atEventoModelo->metConsultarTipoPersona(1);//trae el codigo que identifica una persona del tipo ponente 760
			$participante = $this->atEventoModelo->metConsultarTipoPersona(2);//trae el codigo que identifica a una persona del tipo participante 761
			$cargarPonente = $this->atEventoModelo->metVerPonente($ponente['pk_num_miscelaneo_detalle'], $pkNumEvento, 1);//trae los ponentes del evento

				if(!empty($cargarPonente))//hay ponentes
				{
                    $totalFirmas = 0;
					foreach ($cargarPonente as $pon)
					{
						$ponenteCedula[] = $pon['ind_cedula_documento'];
						$ponenteNombre[] = $pon['ind_nombre1'] . ' ' . $pon['ind_nombre2'] . ' ' . $pon['ind_apellido1'] . ' ' . $pon['ind_apellido2'];
						$ponenteCulmino[] = $pon['num_flag_culmino_evento'];
						$ponenteRecibio[] = $pon['num_flag_recibio_certificado'];
						$nivelInstruccion[] = $pon['pk_num_miscelaneo_detalle'];
						$tipo_firma[] = $pon['num_firma'];
						$pk_ponente[] = $pon['pk_num_persona'];


						if($pon['num_firma'] != '0')
						{

							$totalFirmas++;

							$check_firma[] = 's';
                            $cad_checked_firma[] = 'checked';
                            //===
							if($pon['num_firma'] == '1')//escrita
							{
                                $cad_tipo_firma[] = '<option value="0">...</option><option value="1" selected>Escrita</option><option value="2" data-toggle="modal" data-target="#formModal3" data-keyboard="false" data-backdrop="static" >Imagen</option><option value="3" data-toggle="modal" data-target="#formModal3" data-keyboard="false" data-backdrop="static">Sello + Imagen</option>';
							}
							else if($pon['num_firma'] == '2')//imagen 2
							{
                                $cad_tipo_firma[] = '<option value="0">...</option><option value="1">Escrita</option><option value="2" data-toggle="modal" data-target="#formModal3" data-keyboard="false" data-backdrop="static"  selected>Imagen</option><option value="3" data-toggle="modal" data-target="#formModal3" data-keyboard="false" data-backdrop="static">Sello + Imagen</option>';
							}
							else{
								$cad_tipo_firma[] = '<option value="0">...</option><option value="1">Escrita</option><option value="2" data-toggle="modal" data-target="#formModal3" data-keyboard="false" data-backdrop="static">Imagen</option><option value="3" data-toggle="modal" data-target="#formModal3" data-keyboard="false" data-backdrop="static" selected>Sello + Imagen</option>';
							}

							$cad_activar_tipo_firma[] = '';
                            $cad_valor_caja[] = 's';

						}
						else
						{
                            $check_firma[] = 'n';
                            $cad_checked_firma[] = '';
                            $cad_tipo_firma[] = '<option value="0">...</option><option value="1" >Escrita</option><option value="2" data-toggle="modal" data-target="#formModal3" data-keyboard="false" data-backdrop="static" >Imagen</option>';
                            $cad_activar_tipo_firma[] = 'disabled="disabled"';
							$cad_valor_caja[] = 'n';
						}


					}

					$cantidadPonentePrevio = count($cargarPonente);
					$cantidadPonente = $cantidadPonentePrevio - 1;
					$cantidadPonente = array(
						'cantidadPon' => $cantidadPonente
					);
				}
				else//no hay ponentes - array vacio
				{

					$cantidadPonente = -1;
					$cantidadPonente = array(
						'cantidadPon' => $cantidadPonente
					);
				}


			//Participantes
			$cargarParticipante = $this->atEventoModelo->metVerPersona($participante['pk_num_miscelaneo_detalle'], $pkNumEvento, 1);
			foreach($cargarParticipante as $part){
				$participanteCedula[] = $part['ind_cedula_documento'];
				$participanteNombre[] = $part['ind_nombre1'].' '.$part['ind_nombre2'].' '.$part['ind_apellido1'].' '.$part['ind_apellido2'];
				$participanteCulmino[] = $part['num_flag_culmino_evento'];
				$participanteRecibio[] = $part['num_flag_recibio_certificado'];
                $pk_parti[] = $part['pk_num_persona'];
			}
			$cantidadParticipantePrevio = count($cargarParticipante);
			$cantidadParticipante = $cantidadParticipantePrevio - 1;
			$cantidad = array(
				'cantidadPart' => $cantidadParticipante
			);

			//====Temas====
			$verTema = $this->atEventoModelo->metVerTema($pkNumEvento);
            if(!empty($verTema))
            {
				$contadorTema = count($verTema);
				foreach($verTema as $tema){
					$temaId[] = $tema['pk_num_tema_evento'];
					$indTema[] = $tema['ind_tema'];
				}
				$cantidadTema = array(
					'cantidadTem' => $contadorTema-1
				);

                $this->atVista->assign('temaId', $temaId);
                $this->atVista->assign('indTema', $indTema);
            }
            else//No hay participante
			{
                $cantidadTema = array(
                    'cantidadTem' => -1
                );
			}
			//=============
			$listarLugar = $this->atEventoModelo->metListarLugar();
			$listarTipoEnte = $this->atEventoModelo->metListarTipoEnte();
			$this->atVista->assign('tipoEnte', $listarTipoEnte);
			$listarTema = $this->atEventoModelo->metListarTema();
			$listarCertificado = $this->atEventoModelo->metListarCertificado();
			$tipoEvento = $this->atEventoModelo->metMostrarSelect('TIPEV');
			$listarEntes = $this->atEventoModelo->metConsultarEnte();
			$this->atVista->assign('listarEntes', $listarEntes);
			$this->atVista->assign('cantidadTema', $cantidadTema);
			$this->atVista->assign('tipoEvento', $tipoEvento);
			$this->atVista->assign('evento', $verEvento);
			$deps = $this->atEventoModelo->metGetDependencias();
			$this->atVista->assign('deps', $deps);

			$this->atVista->assign('datoHora', $datoHora);
			$this->atVista->assign('cargarPonente', $cargarPonente);
			$this->atVista->assign('participanteCedula', $participanteCedula);
			$this->atVista->assign('participanteNombre', $participanteNombre);
			$this->atVista->assign('participanteCulmino', $participanteCulmino);
			$this->atVista->assign('participanteRecibio', $participanteRecibio);
            $this->atVista->assign('pk_parti', $pk_parti);

            $consultarContralor = $this->atEventoModelo->metConsultarContralor();
            $this->atVista->assign('pk_contralor', $consultarContralor["pk_num_empleado"]);//90

			//=====Ponentes========================
			if($cantidadPonente["cantidadPon"]>=0)//si no trajo ponente sera -1
			{

				$this->atVista->assign('ponenteCedula', $ponenteCedula);
				$this->atVista->assign('ponenteNombre', $ponenteNombre);
				$this->atVista->assign('ponenteCulmino', $ponenteCulmino);
				$this->atVista->assign('ponenteRecibio', $ponenteRecibio);
				$this->atVista->assign('nivelInstruccion', $nivelInstruccion);

				$this->atVista->assign('tipo_firma', $tipo_firma);
                $this->atVista->assign('check_firma', $check_firma);
                $this->atVista->assign('cad_checked_firma', $cad_checked_firma);
                $this->atVista->assign('cad_tipo_firma', $cad_tipo_firma);
                $this->atVista->assign('cad_activar_tipo_firma', $cad_activar_tipo_firma);
                $this->atVista->assign('totalFirmas', $totalFirmas);
                $this->atVista->assign('pk_ponente', $pk_ponente);
                $this->atVista->assign('pk_ponen', $pk_ponente);
                $this->atVista->assign('cad_valor_caja',$cad_valor_caja);





			}
			$this->atVista->assign('cantidadPonente', $cantidadPonente);
			//============Participante==============================
			$this->atVista->assign('cantidadParticipante', $cantidad);
			$this->atVista->assign('listarCertificado', $listarCertificado);
			$this->atVista->assign('listarTema', $listarTema);
			$this->atVista->assign('listarLugar', $listarLugar);
			$tipoInstruccion = $this->atEventoModelo->metMostrarSelect('NIVELINS');
			$this->atVista->assign('tipoInstruccion', $tipoInstruccion);
			$this->atVista->metRenderizar('editar', 'modales');
		}
	}

	// Método que permite asociar un certificado a una persona asistente al evento
	public function metCargarCertificado($pkNumEvento, $pkNumPersona, $fecha_hora, $usuario)
	{
		// Verifico si la persona ya tiene un certificado
		$obtenerCertificado = $this->atEventoModelo->metObtenerCertificado($pkNumEvento, $pkNumPersona, 1);
		$contadorCertificado = count($obtenerCertificado);
		if($contadorCertificado==0) {
			// Consulto cual fue el ultimo certificado que se guardo
			$ultimo = $this->atEventoModelo->metConsultarUltimoCertificado();
			$proximo = $ultimo['maximo'] + 1;
			// Guardo el certificado
			$this->atEventoModelo->metGuardarPersonaCertificado($pkNumEvento, $pkNumPersona, $proximo, $fecha_hora, $usuario);
		}
	}

	// Método que permite buscar los meses
	public function metBuscarMes($mesFecha)
	{
		switch($mesFecha){
			case 1:
				$mes="Enero";
				break;
			case 2:
				$mes="Febrero";
				break;
			case 3:
				$mes="Marzo";
				break;
			case 4:
				$mes="Abril";
				break;
			case 5:
				$mes="Mayo";
				break;
			case 6:
				$mes="Junio";
				break;
			case 7:
				$mes="Julio";
				break;
			case 8:
				$mes="Agosto";
				break;
			case 9:
				$mes="Septiembre";
				break;
			case 10:
				$mes="Octubre";
				break;
			case 11:
				$mes="Noviembre";
				break;
			case 12:
				$mes="Diciembre";
				break;
		}
		return $mes;
	}

	// Método que permite generar las abreviaturas
	public function metGenerarAbreviatura($instruccionPrevia, $sexo)
	{
		switch($instruccionPrevia){
			case 1:
				$abreviatura = 'BR.';
				break;
			case 2:
				$abreviatura = 'TSU.';
				break;
			case 3:
				if($sexo=='M'){
					$abreviatura = 'LCDO.';
				} else {
					$abreviatura = 'LCDA.';
				}
				break;
			case 4:
				$abreviatura = 'ING.';
				break;
			case 5:
				$abreviatura = 'ESP.';
				break;
			case 6:
				$abreviatura = 'MG.';
				break;
			case 7:
				$abreviatura = 'ECON.';
				break;
			case 8:
				$abreviatura = 'MED.';
				break;
			case 9:
				$abreviatura = 'ABG.';
				break;
			case 10:
				if($sexo=='M'){
					$abreviatura = 'DR.';
				} else {
					$abreviatura = 'DRA.';
				}
				break;
		}
		return $abreviatura;
	}

    public function metGenerarAbreviaturaContralor($instruccion, $sexo)
    {
        switch($instruccion){
            case "BACHILLER":
                $abreviatura = 'BR.';
                break;
            case "TECNICO SUPERIOR UNIVERSITARIO":
                $abreviatura = 'TSU.';
                break;
            case "LICENCIADO":
                if($sexo=='M'){
                    $abreviatura = 'LCDO.';
                } else {
                    $abreviatura = 'LCDA.';
                }
                break;
            case "INGENIERO":
                $abreviatura = 'ING.';
                break;
            case "MEDICO":
                $abreviatura = 'MED.';
                break;
            case "ABOGADO":
                $abreviatura = 'ABG.';
                break;
            case "DOCTOR":
                if($sexo=='M'){
                    $abreviatura = 'DR.';
                } else {
                    $abreviatura = 'DRA.';
                }
                break;
			default:
                $abreviatura = '';
        }
        return $abreviatura;
    }

	//Método que permite generar los certificados de un evento
	public function metGenerarCertificado()
	{
		ini_set('error_reporting', 'E_ALL & ~E_STRICT');
		$pkNumEvento = $_GET['pk_num_evento'];
		$this->metObtenerLibreria('cabeceraEvento', 'modEV');
		$pdf = new pdfGeneralEvento('L', 'mm', 'Letter');
		// Obtengo el fondo del certificado
		$verEvento = $this->atEventoModelo->metVerEvento($pkNumEvento);
		//Verifico el tipo de evento

		if(($verEvento['cod_detalle']==1)||($verEvento['cod_detalle']==6)||($verEvento['cod_detalle']==8)||($verEvento['cod_detalle']==9)||($verEvento['cod_detalle']==10) || ($verEvento['cod_detalle']==12) ){
			$continuacion = 'A LA';
			$continuacionPonente = 'LA';
		} else {
			$continuacion = 'AL';
			$continuacionPonente = 'EL';
		}

		// Duración
		$explodeDuracion = explode(":", $verEvento['fec_horas_total']);
		$duracionHora = $explodeDuracion[0];
		if($duracionHora>1){
			$duracion = $duracionHora.' horas académicas';
		} else{
			$duracion = $duracionHora.' hora académica';
		}
		// Fecha
		$explodeFecha = explode("/", $verEvento['fecha_fin']);//fecha_registro
		$diaFecha = $explodeFecha[0];
		$mesFecha = $explodeFecha[1];
		$buscarMes = $this->metBuscarMes($mesFecha);

		//Consulta del contralor Vigente
		$consultarContralor = $this->atEventoModelo->metConsultarContralor();
        $infoOrganismoCert = $this->atEventoModelo->metConsultarInfoDetalleOrganismo($this->atIdDetalleOrg);
        $ciudadCertificado = ucwords(mb_strtolower($infoOrganismoCert["ind_ciudad"]));
        $instruccionContralor = $this->atEventoModelo->metInstruccionContralor($consultarContralor["pk_num_empleado"]);
        $sexoContralorCert = $this->atEventoModelo->metObtenerSexo($consultarContralor["pk_num_empleado"]);
        $abreviaturaContralor = $this->metGenerarAbreviaturaContralor(trim($instruccionContralor["ind_nombre_nivel_grado"]), $sexoContralorCert["cod_detalle"]);
        //====================
		$ponenteTipo = $this->atEventoModelo->metConsultarTipoPersona(1);

		if($verEvento['num_flag_certificado_ponente']>0)//se entregara certificado a los ponentes
		{
            // Listar a los ponentes - ponentes que han culminado evento
			$listarPonente = $this->atEventoModelo->metListarPersona($pkNumEvento, $ponenteTipo['pk_num_miscelaneo_detalle']);
			foreach ($listarPonente as $ponente)
			{

				$pdf->AliasNbPages();
				$pdf->AddPage(); 
				$pdf->SetAutoPageBreak(true, 5);
				$pdf->imagenCertificado($verEvento['ind_certificado']);

				$pdf->SetFont	('Arial', 'B', 8);
				$pkNumPersona = $ponente['fk_a003_num_persona'];

				$verCertificado = $this->atEventoModelo->metObtenerCertificado($pkNumEvento, $pkNumPersona, 2);
                $pdf->setXY(105, 74);
                $pdf->Cell(22, 4, utf8_decode("Certificado N° "), 0, 0, 'C', 0);
                $pdf->Cell(26, 4, utf8_decode("Actividad N° "), 0, 0, 'C', 0);
                $pdf->Cell(17, 4, "Fecha", 0, 0, 'C', 0);
				$pdf->setXY(105, 79);
				$pdf->Cell(22, 4, $verCertificado['num_certificado'], 0, 0, 'C', 0);
				$pdf->Cell(26, 4, str_pad($verEvento['pk_num_evento'], 6, "0", STR_PAD_LEFT) . '-' . $verEvento['anio_registro'], 0, 0, 'C', 0);
				$pdf->Cell(17, 4, $verEvento['fecha_registro'], 0, 0, 'C', 0);
				$pdf->Ln();
				$pdf->Ln();
				$pdf->Ln();
				$pdf->Ln();
				$pdf->SetFont('Arial', 'B', 16);
				$pdf->MultiCell(0, 7, utf8_decode($ponente['ind_nombre1'] . ' ' . $ponente['ind_apellido1']), '', 'C', 0);
				$pdf->Ln(1);
				$pdf->MultiCell(0, 7, "C.I " . number_format($ponente['ind_cedula_documento'], 0, "", "."), '', 'C', 0);
				$pdf->Ln();
				$pdf->SetFont('Arial', '', 11);
				$pdf->MultiCell(0, 7, utf8_decode('POR HABER DICTADO ' . $continuacionPonente . ' ' . $verEvento['ind_nombre_detalle']), '', 'C', 0);
				$pdf->SetFont('Arial', 'BI', 17);
				$pdf->SetTextColor(0,0,160);
				$pdf->SetX(30);
				$pdf->MultiCell(220, 7, utf8_decode($verEvento['ind_nombre_evento']), '', 'C', 0);
				$pdf->SetTextColor(0, 0, 0);
				$pdf->SetFont('Arial', '', 10.5);
				$pdf->MultiCell(0, 7, utf8_decode('Duración: ' . $duracion), '', 'C', 0);
				$pdf->MultiCell(0, 7, utf8_decode($ciudadCertificado.', ' . $diaFecha . ' de ' . $buscarMes . ' de ' . $verEvento['anio_registro']), '', 'C', 0);
				$pdf->Ln();
				$pdf->Ln();
				$pdf->SetX(95);
				$pdf->SetFont('Arial', 'B', 10);
				//====================
                $rutaFirmaContralor = $this->atEventoModelo->metConsultarFirmaContralor($consultarContralor["pk_num_empleado"]);
				if ($rutaFirmaContralor['ind_firma_png'])
                {
                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaContralor['ind_firma_png'], 115, 155, 50, 30);
                	$pdf->Cell(130, 5, "                                       ", 0, 0, 'C', 0);
                }
                else//Si no tiene firma registrada el contralor
                {
                    $pdf->SetXY(95,170);
                    $pdf->Cell(190 / 2, 5, "_______________________________________", 0, 1, 'C', 0);
                }
				//====================

                $pdf->SetXY(95,175);
                $pdf->Cell(190 / 2, 5, utf8_decode($abreviaturaContralor." ".$consultarContralor['ind_nombre1'].' '.$consultarContralor['ind_apellido1']), 0, 1, 'C', 0);
                $pdf->SetXY(95,180);
                $pdf->Cell(190 / 2, 4, $infoOrganismoCert['ind_cargo_representante'], '', 0, 'C', 0);

				// CODIGO QR
				$this->metObtenerLibreria('qrlib', 'phpqrcode');
				$nombreFichero = ROOT . 'librerias' . DS . 'modEV' . DS . 'codigoQR' . DS. $pkNumEvento.$ponente['ind_cedula_documento'].'.png';
				if (file_exists($nombreFichero)) {

				} else {
					QRcode::png($verCertificado['num_certificado'].' '.$pkNumPersona.' '.$ponente['ind_nombre1'] . ' ' . $ponente['ind_apellido1'].' '.$ponente['ind_cedula_documento'].' '.$verEvento['ind_nombre_evento'], $nombreFichero);
				}
				$pdf->SetXY(95, 90);
				$pdf->Cell(100,100); $pdf->Image(ROOT.'librerias'. DS . 'modEV' . DS . 'codigoQR'. DS. $pkNumEvento.$ponente['ind_cedula_documento'].'.png',10, 150,22,22);
			}
		}

		// Certificados participantes
		if($verEvento['num_flag_certificado_participante']>0)
		{
			//ponentes que firman los certificados de los participantes y culminaron evento
			$listarPonente = $this->atEventoModelo->metConsultarPonentesFirmantesCert($pkNumEvento, $ponenteTipo['pk_num_miscelaneo_detalle']);
			$contadorPonente = count($listarPonente);
			$i = 0;
			foreach($listarPonente as $ponente){
				$ponenteNombre[$i] = $ponente['ind_nombre1'].' '.$ponente['ind_nombre2'].' '.$ponente['ind_apellido1'];//.' '.$ponente['ind_apellido2'];
				$instruccionPrevia = $ponente['cod_detalle'];
				$pkNumPersona = $ponente['fk_a003_num_persona'];

				//=======================================================
                $tipoFirmaParticipante= $ponente['ind_firma_png'];
                $rutaFirmaParticipante= $ponente['num_firma'];
                $pkFirmaPonente[] = $ponente['fk_a003_num_persona'];
                $tipoFirmaPonente[] = $ponente['num_firma'];
                $rutaFirmaPonente[] = $ponente['ind_firma_png'];
				$rutaFirmaPonenteSello[] = $ponente['ind_firma_png_sello'];
                //=======================================================
				$numPersonasPonentes[$i] = $pkNumPersona;
				$consultarSexo = $this->atEventoModelo->metObtenerSexo($pkNumPersona);

				if(empty($ponente['cargo_visita']))
				{
					$cargoVisita = $this->atEventoModelo->metBuscarCargo($pkNumPersona);
					$cargoEmpleado[$i] = $cargoVisita["ind_nombre_cargo"];
				}
				else//la persona es un visitante con cargo
				{
					$cargoEmpleado[$i] = $ponente['cargo_visita'];
				}
				//************************************************************************
				if($consultarSexo['cod_detalle']=='M'){
					$facilitar[$i] = 'FACILITADOR';
				} else {
					$facilitar[$i] = 'FACILITADORA';
				}
				$abreviatura[$i] = $this->metGenerarAbreviatura($instruccionPrevia, $consultarSexo['cod_detalle']);
				$i++;
			}

			$participante = $this->atEventoModelo->metConsultarTipoPersona(2);//participantes

			$listarPersona = $this->atEventoModelo->metListarPersona($pkNumEvento, $participante['pk_num_miscelaneo_detalle']);
			foreach ($listarPersona as $persona) { //para cada certificado
				$pdf->AliasNbPages();
				$pdf->AddPage();
				$pdf->SetAutoPageBreak(true, 5); 
				$pdf->imagenCertificado($verEvento['ind_certificado']);

				$pdf->SetFont('Arial', 'B', 8);
				$pkNumPersona = $persona['fk_a003_num_persona']; 
				$verCertificado = $this->atEventoModelo->metObtenerCertificado($pkNumEvento, $pkNumPersona, 2);
                $pdf->setXY(105, 74);
                $pdf->Cell(22, 4, utf8_decode("Certificado N° "), 0, 0, 'C', 0);
                $pdf->Cell(26, 4, utf8_decode("Actividad N° "), 0, 0, 'C', 0);
                $pdf->Cell(17, 4, "Fecha", 0, 0, 'C', 0);
				$pdf->setXY(105, 79);
                $pdf->Cell(22, 4, $verCertificado['num_certificado'], 0, 0, 'C', 0);
				$pdf->Cell(26, 4, str_pad($verEvento['pk_num_evento'], 6, "0", STR_PAD_LEFT) . '-' . $verEvento['anio_registro'], 0, 0, 'C', 0);
				$pdf->Cell(17, 4, $verEvento['fecha_registro'], 0, 0, 'C', 0);
				$pdf->Ln();
				$pdf->Ln();
				$pdf->Ln();
				$pdf->Ln();
				$pdf->SetFont('Arial', 'B', 16);
				$pdf->MultiCell(0, 7, utf8_decode($persona['ind_nombre1'] . ' '.$persona['ind_nombre2'] .' '. $persona['ind_apellido1'].' '. $persona['ind_apellido2']), '', 'C', 0);
				$pdf->Ln(1);
				$pdf->MultiCell(0, 7, "C.I " . number_format($persona['ind_cedula_documento'], 0, "", "."), '', 'C', 0);
				$pdf->Ln();
				$pdf->SetFont('Arial', '', 11);
				//=======
				if(strcmp("RECONOCIMIENTO", trim($verEvento['ind_nombre_detalle']))!=0)
				{
                    $pdf->MultiCell(0, 7, utf8_decode('POR HABER ASISTIDO ' . $continuacion . ' ' . $verEvento['ind_nombre_detalle']), '', 'C', 0);
                    $cad_duracion_eve = 'Duración: ' . $duracion;
				}
				else
				{
                    $cad_duracion_eve = '';
				}
				//=======
				$pdf->SetFont('Arial', 'BI', 17);
				$pdf->SetTextColor(0,0,160);
				$pdf->SetX(30);
				$pdf->MultiCell(220, 7, utf8_decode($verEvento['ind_nombre_evento']), '', 'C', 0);
				$pdf->SetTextColor(0, 0, 0);
				$pdf->SetFont('Arial', '', 10.5);
				$pdf->MultiCell(0, 7, utf8_decode($cad_duracion_eve), '', 'C', 0);
				$pdf->MultiCell(0, 7, utf8_decode($ciudadCertificado.', ' . $diaFecha . ' de ' . $buscarMes . ' de ' . $verEvento['anio_registro']), '', 'C', 0);
				$pdf->SetFont('Arial', 'B', 10);
				$pdf->Ln();
				$pdf->Ln();
				//=======
                if(strcmp("RECONOCIMIENTO", trim($verEvento['ind_nombre_detalle']))!=0)//EL EVENTO ES DISTINTO A UN RECONOCIMIENTO
				{
					//NOTA: SOLO SE PERMITEN 3 FIRMAS, EL CONTRALOR FIRMA TODOS LOS CERTIFICADOS
					if($contadorPonente==1)// 1 SOLO PONENTE
					{
						if($pkFirmaPonente[0] > 0)//PONENTE FIRMA
						{
							if ($pkFirmaPonente[0] == $consultarContralor["pk_num_empleado"])// 1 FIRMA - EXPONTE CONTRALOR
							{

								$pdf->SetFont('Arial', 'B', 10);
								//=======
								if ($tipoFirmaPonente[0] == 1)//firma escrita
								{

                                    $pdf->SetXY(95,170);
									$pdf->Cell(190 / 2, 5, "_______________________________________", 0, 1, 'C', 0);
								}
								else
									if ($tipoFirmaPonente[0] == 2)//firma de imagen
									{
										$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 115, 155, 50, 30);
									}
									
								else
								if ($tipoFirmaPonente[0] == 3)//firma de imagen + sello
								{
									$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonenteSello[0], 115, 155, 50, 30);
								}
								//======
                                $pdf->SetXY(95,175);
                                $pdf->Cell(190 / 2, 5, utf8_decode($abreviaturaContralor." ". $consultarContralor['ind_nombre1'] . ' ' . $consultarContralor['ind_apellido1']), 0, 1, 'C', 0);
                                $pdf->SetXY(95,180);
								$pdf->Cell(190 / 2, 4, $infoOrganismoCert['ind_cargo_representante'], '', 0, 'C', 0);
							}
							else// PONENTE - NO ES EL CONTRALOR - 2 FIRMAS
							{

								$rutaFirmaContralor = $this->atEventoModelo->metConsultarFirmaContralor($consultarContralor["pk_num_empleado"]);

								if ($rutaFirmaContralor['ind_firma_png'])
								{
									$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaContralor['ind_firma_png'], 50, 155, 50, 30);

								}
								else//Si no tiene firma registrada el contralor
								{
                                    $pdf->SetXY(10,170);
									$pdf->Cell(130, 5, "__________________________________", 0, 0, 'C', 0);
								}

								if ($tipoFirmaPonente[0] == 1)
								{
                                    $pdf->SetXY(140,170);
									$pdf->Cell(130, 5, "__________________________________", 0, 1, 'C', 0);
								}
								else
								{
									if ($tipoFirmaPonente[0] == 2)
									{
										$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 180, 155, 50, 30);

									}
								}

                                $pdf->SetXY(10,175);
								$pdf->Cell(130, 5, utf8_decode($abreviaturaContralor.' ' . $consultarContralor['ind_nombre1'] . ' ' . $consultarContralor['ind_nombre2'] . ' ' . $consultarContralor['ind_apellido1'] . ' ' . $consultarContralor['ind_apellido2']), 0, 0, 'C', 0);
                                $pdf->SetXY(10,180);
                                $pdf->Cell(130, 4, $infoOrganismoCert['ind_cargo_representante'], 0, 0, 'C', 0);
                                //===
                                $pdf->SetXY(140,175);
								$pdf->Cell(130, 5, utf8_decode($abreviatura[0] . ' ' . $ponenteNombre[0]), 0, 1, 'C', 0);
                                $pdf->SetXY(140,180);
								$pdf->Cell(130, 4, $facilitar[0], 0, 0, 'C', 0);
							}
						}

					}
					else
					{
						if($contadorPonente==2)//2 PONENTES
						{
							if( $numPersonasPonentes[0] == $consultarContralor["pk_num_empleado"] || $numPersonasPonentes[1] == $consultarContralor["pk_num_empleado"])
							{   //UNO DE LOS PONENTES ES EL CONTRALOR - SOLO 2 FIRMAS

								if($numPersonasPonentes[0] == $consultarContralor["pk_num_empleado"])
								{

									$cad_facilitar1 = $infoOrganismoCert['ind_cargo_representante'];
									$cad_facilitar2 = $facilitar[1];
								}
								else
								{

									$cad_facilitar2 = $infoOrganismoCert['ind_cargo_representante'];
									$cad_facilitar1 = $facilitar[0];

								}

								//====
								if ($tipoFirmaPonente[0] == 1)
								{

                                    $pdf->SetXY(10,170);
                                    $pdf->Cell(130, 5, "__________________________________", 0, 0, 'C', 0);

								}
								else
								{
									if ($tipoFirmaPonente[0] == 2)
									{
										$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 50, 155, 50, 30);

									}

								}

								if ($tipoFirmaPonente[1] == 1)
								{

                                    $pdf->SetXY(140,170);
                                    $pdf->Cell(130, 5, "__________________________________", 0, 1, 'C', 0);

								}
								else
								{
									if ($tipoFirmaPonente[1] == 2)
									{
										$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[1], 180, 155, 50, 30);

									}

								}
								//====
                                $pdf->SetXY(10,175);
                                $pdf->Cell(130, 5, utf8_decode($abreviatura[0] . $ponenteNombre[0] ), 0, 0, 'C', 0);
                                $pdf->SetXY(10,180);
                                $pdf->Cell(130, 4, $cad_facilitar1, 0, 0, 'C', 0);
                                //===
                                $pdf->SetXY(140,175);
                                $pdf->Cell(130, 5, utf8_decode($abreviatura[1] . ' ' . $ponenteNombre[1]), 0, 1, 'C', 0);
                                $pdf->SetXY(140,180);
                                $pdf->Cell(130, 4, $cad_facilitar2, 0, 0, 'C', 0);

							}
							else //NINGUNO DE LOS DOS PONENTES ES CONTRALOR - 3 FIRMAS
							{
                                $pdf->SetFont('Arial', 'B', 9);
								//===CONTRALOR
								$rutaFirmaContralor = $this->atEventoModelo->metConsultarFirmaContralor($consultarContralor["pk_num_empleado"]);

								if ($rutaFirmaContralor['ind_firma_png'])
								{
									$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaContralor['ind_firma_png'], 120, 155, 50, 30);

								}
								else//Si no tiene firma registrada el contralor
								{
                                    $pdf->SetXY(120,170);
                                    $pdf->Cell(50, 5, "__________________________", 0, 0, 'C', 0);
								}


                                $pdf->SetXY(80,175);
                                $pdf->Cell(130, 5, utf8_decode($abreviaturaContralor." ". $consultarContralor['ind_nombre1'] . ' ' . $consultarContralor['ind_nombre2'] . ' ' . $consultarContralor['ind_apellido1'] . ' ' . $consultarContralor['ind_apellido2'] ), 0, 0, 'C', 0);
                                $pdf->SetXY(80,180);
                                $pdf->Cell(130, 4, $infoOrganismoCert['ind_cargo_representante'], 0, 0, 'C', 0);

								//=====PONENTE 1
								if ($tipoFirmaPonente[0] == 1)
								{

                                    $pdf->SetXY(40,170);
                                    $pdf->Cell(50, 5, "__________________________", 0, 0, 'C', 0);

								}
								else//Si no tiene firma registrada el contralor
								{
									if ($tipoFirmaPonente[0] == 2)
									{
										$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 40, 155, 50, 30);

									}

								}

                                $pdf->SetXY(10,175);
                                $pdf->Cell(110, 5, utf8_decode($abreviatura[0] . ' ' . $ponenteNombre[0]), 0, 0, 'C', 0);
                                $pdf->SetXY(10,180);
                                $pdf->Cell(110, 4, $facilitar[0], 0, 0, 'C', 0);


								//=====PONENTE 2
								if ($tipoFirmaPonente[1] == 1)
								{

                                    $pdf->SetXY(200,170);
                                    $pdf->Cell(50, 5, "__________________________", 0, 1, 'C', 0);

								}
								else//Si no tiene firma registrada el contralor
								{
									if ($tipoFirmaPonente[1] == 2)
									{
										$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[1], 200, 155, 50, 30);

									}

								}

                                $pdf->SetXY(170,175);
                                $pdf->Cell(110, 5, utf8_decode($abreviatura[1] . ' ' . $ponenteNombre[1]), 0, 1, 'C', 0);
                                $pdf->SetXY(170,180);
                                $pdf->Cell(110, 4, $facilitar[1], 0, 0, 'C', 0);

							}
						}
						else //3 FIRMAS
						{
							// 3 PONENTES Y UNO ES CONTRALOR
                            $pdf->SetFont('Arial', 'B', 9);

							if($numPersonasPonentes[0] == $consultarContralor["pk_num_empleado"])
							{
								$facilitar[0] = $infoOrganismoCert['ind_cargo_representante'];

							}
							else
							{
								if($numPersonasPonentes[1] == $consultarContralor["pk_num_empleado"])
								{
									$facilitar[1] = $infoOrganismoCert['ind_cargo_representante'];

								}
								else
								{
									$facilitar[2] = $infoOrganismoCert['ind_cargo_representante'];
								}
							}

							if($tipoFirmaPonente[0] == 1)
							{
                                $pdf->SetXY(40,170);
                                $pdf->Cell(50, 5, "__________________________", 0, 0, 'C', 0);
							}
							else
							{
								if ($tipoFirmaPonente[0] == 2)
								{
                                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 40, 155, 50, 30);
								}
							}

                            $pdf->SetXY(10,175);
                            $pdf->Cell(110, 5, utf8_decode($abreviatura[0] . ' ' . $ponenteNombre[0]), 0, 0, 'C', 0);
                            $pdf->SetXY(10,180);
                            $pdf->Cell(110, 4, $facilitar[0], 0, 0, 'C', 0);

                            //==

							if($tipoFirmaPonente[1] == 1)
							{
                                $pdf->SetXY(119,170);
                                $pdf->Cell(50, 5, "__________________________", 0, 0, 'C', 0);
							}
							else
							{
								if ($tipoFirmaPonente[1] == 2)
								{
                                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[1], 119, 155, 50, 30);
								}
							}

                            $pdf->SetXY(80,175);
                            $pdf->Cell(130, 5, utf8_decode($abreviatura[1] . ' ' . $ponenteNombre[1]), 0, 0, 'C', 0);
                            $pdf->SetXY(80,180);
                            $pdf->Cell(130, 4, $facilitar[1], 0, 0, 'C', 0);

                            //===

							if($tipoFirmaPonente[2] == 1)
							{
                                $pdf->SetXY(200,170);
                                $pdf->Cell(50, 5, "__________________________", 0, 1, 'C', 0);
							}
							else
							{
								if ($tipoFirmaPonente[2] == 2)
								{
									$pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[2], 200, 155, 50, 30);

								}
							}

                            $pdf->SetXY(170,175);
                            $pdf->Cell(110, 5, utf8_decode($abreviatura[2] . ' ' . $ponenteNombre[2]), 0, 1, 'C', 0);
                            $pdf->SetXY(170,180);
                            $pdf->Cell(110, 4, $facilitar[2], 0, 0, 'C', 0);

						}
					}
                }
                else
				{
					//ES UN RECONOCIMIENTO
                    $pdf->SetFont('Arial', 'B', 10);

					$rutaFirmaContralor = $this->atEventoModelo->metConsultarFirmaContralor($consultarContralor["pk_num_empleado"]);

                    $pdf->Ln();

                    if ($rutaFirmaContralor['ind_firma_png'])
                    {
                        $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaContralor['ind_firma_png'], 115, 155, 50, 30);

                    }
                    else//Si no tiene firma registrada el contralor
                    {
                        $pdf->SetXY(95,170);
                        $pdf->Cell(190 / 2, 5, "_______________________________________", 0, 1, 'C', 0);
                    }

                    $pdf->SetXY(95,175);
                    $pdf->Cell(190 / 2, 5, utf8_decode($abreviaturaContralor." ". $consultarContralor['ind_nombre1'] . ' ' . $consultarContralor['ind_apellido1']), 0, 1, 'C', 0);
                    $pdf->SetXY(95,180);
                    $pdf->Cell(190 / 2, 4, $infoOrganismoCert['ind_cargo_representante'], '', 0, 'C', 0);

				}
				// CODIGO QR
				$this->metObtenerLibreria('qrlib', 'phpqrcode');
				$nombreFichero = ROOT . 'librerias' . DS . 'modEV' . DS . 'codigoQR' . DS. $pkNumEvento.$persona['ind_cedula_documento'].'.png';
				if (file_exists($nombreFichero)) {

				} else { //echo "fdfdf: ".$nombreFichero;
					QRcode::png($verCertificado['num_certificado'].' '.$pkNumPersona.' '.$persona['ind_nombre1'] . ' ' . $persona['ind_apellido1'].' '.$persona['ind_cedula_documento'].' '.$verEvento['ind_nombre_evento'], $nombreFichero);
					//echo "maikol";					
				}
					
				$pdf->SetXY(95, 90); 
				$pdf->Cell(100,100); $pdf->Image(ROOT.'librerias'. DS . 'modEV' . DS . 'codigoQR'. DS. $pkNumEvento.$persona['ind_cedula_documento'].'.png',10, 150,22,22);
			}
		}
		$pdf->AliasNbPages();
		$pdf->AddPage();
		$pdf->SetAutoPageBreak(true, 5);
		$pdf->SetFont('Arial','B',20);
		$pdf->Ln();
		$pdf->SetXY(10, 15);
		$pdf->Cell(40,5,"CONTENIDO:",'',0,'C',0);
		$pdf->Ln();
		$verTema = $this->atEventoModelo->metVerTema($pkNumEvento); 
		$pdf->Ln();
		$pdf->SetFont('Arial','',12);
		$pdf->SetTextColor(0, 0, 0); 
		foreach($verTema as $tema){
			$pdf->MultiCell(0, 7, utf8_decode('.- ' .$tema['ind_tema']), '', 'L', 0);
		}
		$pdf->Output();
	}

	// Método que permite calcular la diferencia entre dos horas dadas
	public function metRestarHoras($horaini, $horafin)
	{
		$horai=substr($horaini,0,2);
		$mini=substr($horaini,3,2);
		$segi=substr($horaini,6,2);
		$horaf=substr($horafin,0,2);
		$minf=substr($horafin,3,2);
		$segf=substr($horafin,6,2);
		$ini=((($horai*60)*60)+($mini*60)+$segi);
		$fin=((($horaf*60)*60)+($minf*60)+$segf);
		$dif=$fin-$ini;
		$difh=floor($dif/3600);
		$difm=floor(($dif-($difh*3600))/60);
		$difs=$dif-($difm*60)-($difh*3600);
		return date("H:i:s",mktime($difh,$difm,$difs));
	}

	// Método que permite recibir los parámetros para calcular el tiempo del permiso
	public function metCalcularTiempoEvento()
	{
		$fechaInicioPrevia = $_POST['fechaInicio'];
		$fechaFinPrevia = $_POST['fechaFin'];
		$horaInicioPrevio = $_POST['horaInicio'];
		$horaFinPrevio = $_POST['horaFin'];
		$horarioInicio = $_POST['horarioInicio'];
		$horarioFin = $_POST['horarioFin'];
		$this->metCalcularTiempo($fechaInicioPrevia, $fechaFinPrevia, $horaInicioPrevio, $horaFinPrevio, $horarioInicio, $horarioFin);
	}

	//Método que permite calcular el tiempo del permiso
	public function metCalcularTiempo($fechaInicioPrevia, $fechaFinPrevia, $horaInicioPrevio, $horaFinPrevio, $horarioInicio, $horarioFin)
	{
		//recibiendo los valores
		$fechaExplodeInicio = explode("/", $fechaInicioPrevia);
		$anioInicio = $fechaExplodeInicio[2];
		$mesInicio = $fechaExplodeInicio[1];
		$diaInicio = $fechaExplodeInicio[0];
		$fechaExplodeFin = explode("/", $fechaFinPrevia);
		$anioFin = $fechaExplodeFin[2];
		$mesFin = $fechaExplodeFin[1];
		$diaFin = $fechaExplodeFin[0];
		//calculo timestam de las dos fechas
		$timestamp1 = mktime(0,0,0,$mesInicio, $diaInicio, $anioInicio);
		$timestamp2 = mktime(4,12,0,$mesFin,$diaFin,$anioFin);
		//resto a una fecha la otra
		$segundos_diferencia = $timestamp1 - $timestamp2;
		//echo $segundos_diferencia;
		//convierto segundos en días
		$dias_diferencia = $segundos_diferencia / (60 * 60 * 24);
		//obtengo el valor absoulto de los días (quito el posible signo negativo)
		$dias_diferencia = abs($dias_diferencia);
		//quito los decimales a los días de diferencia
		$dias_diferencia = floor($dias_diferencia);
		$diasDiferencia = $dias_diferencia + 1;
		// Convierto las horas de horario estándar a horario militar
		$horas = $this->metHoras($horaInicioPrevio, $horaFinPrevio, $horarioInicio, $horarioFin);
		$horaInicioPrevio = $horas[0];
		$horaFinPrevio = $horas[1];
		$diferenciaHorasPrevio = $this->metRestarHoras($horaInicioPrevio, $horaFinPrevio);
		$diferenciaHoras = explode(":", $diferenciaHorasPrevio);
		$horaDiferencia = $diferenciaHoras[0];
		$minutoDiferencia = $diferenciaHoras[1];
		$horaAcumulador = 0;
		$minutoAcumulador = 0;
		for ($i=1; $i<=$diasDiferencia; $i++) {
			$horaAcumulador = $horaAcumulador + $horaDiferencia;
			$minutoAcumulador = $minutoAcumulador + $minutoDiferencia;
		}
		while($minutoAcumulador>=60) {
			if($minutoAcumulador>=60) {
				$horaAcumulador = $horaAcumulador + 1;
				$minutoAcumulador = $minutoAcumulador - 60;
			}
		}
		$total = str_pad($horaAcumulador, 2, "0", STR_PAD_LEFT).':'.str_pad($minutoAcumulador, 2, "0", STR_PAD_LEFT);
		$horaTotal = array(
			'horaTotal' => $total
		);
		echo json_encode($horaTotal);
	}
	
	// Método que ayuda a verificar la existencia de una persona en el listado
	public function metVerificarPersona()
	{
		$cedulaDocumento = $_POST['cedulaDocumento'];
		$personaNum = $this->atEventoModelo->metObtenerPersona($cedulaDocumento);
		$persona = array(
			'pkNumPersona' => $personaNum['pk_num_persona']
		);
		echo json_encode($persona);
	}

	// Método que permite buscar un tema desde el wizard
	public function metConsultarTema()
	{
		$valorBoton = $_POST['valorBoton'];
		$temaBoton = array(
			'valorBoton' => $valorBoton
		);
		// Envío a la vista
		$listarTema = $this->atEventoModelo->metListarTema();
		$this->atVista->assign('temaBoton', $temaBoton);
		$this->atVista->assign('listarTema', $listarTema);
		$this->atVista->metRenderizar('buscarTema', 'modales');
	}

	// Método que permite buscar un lugar desde el wizard
	public function metConsultarLugar()
	{
		$listarLugar = $this->atEventoModelo->metListarLugar();
		$this->atVista->assign('listarLugar', $listarLugar);
		$this->atVista->metRenderizar('buscarLugar', 'modales');
	}

	// Método que permite cargar un tema de un evento en particular
	public function metCargarTema()
	{
		$pkNumTemaEvento = $_POST['pk_num_tema_evento'];
		$consultarTema = $this->atEventoModelo->metConsultarTema($pkNumTemaEvento);
		$nombreTema = array(
			'ind_tema' => $consultarTema['ind_tema'],
			'pk_num_tema_evento' => $consultarTema['pk_num_tema_evento']
		);
		echo json_encode($nombreTema);
	}

	// Método que permite cargar un lugar de un evento en particular
	public function metCargarLugar()
	{
		$pkNumLugarEvento = $_POST['pk_num_lugar_evento'];
		$consultarLugar = $this->atEventoModelo->metConsultarLugar($pkNumLugarEvento);
		$nombreLugar = array(
			'ind_lugar_evento' => $consultarLugar['ind_lugar_evento'],
			'pk_num_lugar_evento' => $consultarLugar['pk_num_lugar_evento']
		);
		echo json_encode($nombreLugar);
	}

	// Metodo que permite realizar el envio de certificado
	public function metEnviarCertificado()
	{
		//Verificamos si se le enviara certificado a ponentes
		$pkNumEvento = $_POST['pk_num_evento'];
		if(isset($_POST['ponente'])){
            $ponente = $_POST['ponente'];
            $cantidadPonente = 1;
		} else {
			$ponente = 0;
            $cantidadPonente = 0;
		}
		//Verificamos si se le enviara certificado a participantes
		if(isset($_POST['participante'])){
            $participante = $_POST['participante'];
            $cantidadParticipante = 1;
		} else {
			$participante = 0;
            $cantidadParticipante = 0;
		}

		$total = $cantidadPonente + $cantidadParticipante;

		// Para enviar a los seleccionados
		if($total>0){
			if($cantidadPonente>0){
                for ($i = 0; $i < count($ponente); $i++) {
                	$pkNumPersonaPonente = $ponente[$i];
					$buscarCorreo = $this->atEventoModelo->metObtenerCorreoPersona($pkNumPersonaPonente);
					$correoPonente = $buscarCorreo['ind_email'];
                    $tipo = $this->atEventoModelo->metConsultarTipoPersona(1);
					$culminarEvento = $this->atEventoModelo->metListarPersonaCertificado($pkNumEvento, $tipo['pk_num_miscelaneo_detalle'], $pkNumPersonaPonente);
					if(($correoPonente!='')&&($culminarEvento['num_flag_culmino_evento']==1)){

						$this->metEnviarCorreoPersona($pkNumEvento, $pkNumPersonaPonente, 1);
					}
                }
			}

			if($cantidadParticipante>0){
                for ($i = 0; $i < count($participante); $i++) {
                    $pkNumPersonaParticipante = $participante[$i];
                    $buscarCorreo = $this->atEventoModelo->metObtenerCorreoPersona($pkNumPersonaParticipante);
                    $correoParticipante = $buscarCorreo['ind_email'];
                    $tipo = $this->atEventoModelo->metConsultarTipoPersona(2);
                    $culminarEvento = $this->atEventoModelo->metListarPersonaCertificado($pkNumEvento, $tipo['pk_num_miscelaneo_detalle'], $pkNumPersonaParticipante);
                    if(($correoParticipante!='')&&($culminarEvento['num_flag_culmino_evento']==1)){

                    	$this->metEnviarCorreoPersona($pkNumEvento, $pkNumPersonaParticipante, 2);
                    }
                }
			}

		}
		else
		{
			// Para enviarle a todos
			// Obtengo el listado de ponentes asistentes al evento que hayan culminado
            if($_POST["flag_certificado_ponente"] > 0)//se entregara a todos los ponentes
            {
                $tipoPonente = $this->atEventoModelo->metConsultarTipoPersona(1);
                $tipoPersonaPonente = $tipoPonente['pk_num_miscelaneo_detalle'];
                $listarPonente = $this->atEventoModelo->metListarPersona($pkNumEvento, $tipoPersonaPonente);
                foreach ($listarPonente as $ponente) {
                    $pkNumPersonaPonente = $ponente['fk_a003_num_persona'];
                    $buscarCorreo = $this->atEventoModelo->metObtenerCorreoPersona($pkNumPersonaPonente);
                    $correoPonente = $buscarCorreo['ind_email'];
                    $culminarEvento = $this->atEventoModelo->metListarPersonaCertificado($pkNumEvento, $tipoPersonaPonente, $pkNumPersonaPonente);
                    if (($correoPonente != '') && ($culminarEvento['num_flag_culmino_evento'] == 1)) {
                        $this->metEnviarCorreoPersona($pkNumEvento, $pkNumPersonaPonente, 1);
                    }
                }
            }

            if($_POST["flag_certificado_participante"] > 0)//se entregara a todos los participantes
            {
                // Obtengo el listado de participantes asistentes al evento que hayan culminado
                $tipoParticipante = $this->atEventoModelo->metConsultarTipoPersona(2);
                $tipoPersonaParticipante = $tipoParticipante['pk_num_miscelaneo_detalle'];
                $listarParticipante = $this->atEventoModelo->metListarPersona($pkNumEvento, $tipoPersonaParticipante);
                foreach ($listarParticipante as $participante) {
                    $pkNumPersonaParticipante = $participante['fk_a003_num_persona'];
                    $buscarCorreo = $this->atEventoModelo->metObtenerCorreoPersona($pkNumPersonaParticipante);
                    $correoParticipante = $buscarCorreo['ind_email'];
                    $culminarEvento = $this->atEventoModelo->metListarPersonaCertificado($pkNumEvento, $tipoPersonaParticipante, $pkNumPersonaParticipante);
                    if (($correoParticipante != '') && ($culminarEvento['num_flag_culmino_evento'] == 1)) {
                        $this->metEnviarCorreoPersona($pkNumEvento, $pkNumPersonaParticipante, 2);
                    }
                }
            }
		}
	}

	// Metodo que permite enviar certificado a los ponentes y participantes
	public function metEnviarCorreoPersona($pkNumEvento, $pkNumPersona, $tipoPersona)
	{
        ini_set('error_reporting', 'E_ALL & ~E_STRICT');
        $this->metObtenerLibreria('cabeceraEvento', 'modEV');
        $pdf = new pdfGeneralEvento('L', 'mm', 'Letter');
        // Obtengo el fondo del certificado
        $verEvento = $this->atEventoModelo->metVerEvento($pkNumEvento);
        //Verifico el tipo de evento

        if(($verEvento['cod_detalle']==1)||($verEvento['cod_detalle']==6)||($verEvento['cod_detalle']==8)||($verEvento['cod_detalle']==9)||($verEvento['cod_detalle']==10) || ($verEvento['cod_detalle']==12) ){
            $continuacion = 'A LA';
            $continuacionPonente = 'LA';
        } else {
            $continuacion = 'AL';
            $continuacionPonente = 'EL';
        }

        // Duración
        $explodeDuracion = explode(":", $verEvento['fec_horas_total']);
        $duracionHora = $explodeDuracion[0];
        if($duracionHora>1){
            $duracion = $duracionHora.' horas académicas';
        } else{
            $duracion = $duracionHora.' hora académica';
        }
        // Fecha
        $explodeFecha = explode("/", $verEvento['fecha_fin']);
        $diaFecha = $explodeFecha[0];
        $mesFecha = $explodeFecha[1];
        $buscarMes = $this->metBuscarMes($mesFecha);
        // Consulta del contralor Vigente
        $consultarContralor = $this->atEventoModelo->metConsultarContralor();
        $infoOrganismoCert = $this->atEventoModelo->metConsultarInfoDetalleOrganismo($this->atIdDetalleOrg);
        $ciudadCertificado = ucwords(mb_strtolower($infoOrganismoCert["ind_ciudad"]));
        $instruccionContralor = $this->atEventoModelo->metInstruccionContralor($consultarContralor["pk_num_empleado"]);
        $sexoContralorCert = $this->atEventoModelo->metObtenerSexo($consultarContralor["pk_num_empleado"]);
        $abreviaturaContralor = $this->metGenerarAbreviaturaContralor(trim($instruccionContralor["ind_nombre_nivel_grado"]), $sexoContralorCert["cod_detalle"]);
        //====================
		if($tipoPersona==1){ //Certificados del ponente
            $ponenteTipo = $this->atEventoModelo->metConsultarTipoPersona($tipoPersona);
            $ponente = $this->atEventoModelo->metListarPersonaCertificado($pkNumEvento, $ponenteTipo['pk_num_miscelaneo_detalle'], $pkNumPersona);
            $correo = $ponente['ind_email'];

            $pdf->AliasNbPages();
            $pdf->AddPage();
            $pdf->SetAutoPageBreak(true, 5);
            $pdf->imagenCertificado($verEvento['ind_certificado']);

            $pdf->SetFont	('Arial', 'B', 8);

            $verCertificado = $this->atEventoModelo->metObtenerCertificado($pkNumEvento, $pkNumPersona, 2);
            $pdf->setXY(105, 74);
            $pdf->Cell(22, 4, utf8_decode("Certificado N° "), 0, 0, 'C', 0);
            $pdf->Cell(26, 4, utf8_decode("Actividad N° "), 0, 0, 'C', 0);
            $pdf->Cell(17, 4, "Fecha", 0, 0, 'C', 0);
            $pdf->setXY(105, 79);
            $pdf->Cell(22, 4, $verCertificado['num_certificado'], 0, 0, 'C', 0);
            $pdf->Cell(26, 4, str_pad($verEvento['pk_num_evento'], 6, "0", STR_PAD_LEFT) . '-' . $verEvento['anio_registro'], 0, 0, 'C', 0);
            $pdf->Cell(17, 4, $verEvento['fecha_registro'], 0, 0, 'C', 0);
            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            $pdf->SetFont('Arial', 'B', 16);
            $pdf->MultiCell(0, 7, utf8_decode($ponente['ind_nombre1'] . ' ' . $ponente['ind_apellido1']), '', 'C', 0);
            $pdf->Ln(1);
            $pdf->MultiCell(0, 7, "C.I " . number_format($ponente['ind_cedula_documento'], 0, "", "."), '', 'C', 0);
            $pdf->Ln();
            $pdf->SetFont('Arial', '', 11);
            $pdf->MultiCell(0, 7, utf8_decode('POR HABER DICTADO ' . $continuacionPonente . ' ' . $verEvento['ind_nombre_detalle']), '', 'C', 0);
            $pdf->SetFont('Arial', 'BI', 17);
            $pdf->SetTextColor(0,0,160);
            $pdf->MultiCell(0, 7, utf8_decode($verEvento['ind_nombre_evento']), '', 'C', 0);
            $pdf->SetTextColor(0, 0, 0);
            $pdf->SetFont('Arial', '', 10.5);
            $pdf->MultiCell(0, 7, utf8_decode('Duración: ' . $duracion), '', 'C', 0);
            $pdf->MultiCell(0, 7, utf8_decode($ciudadCertificado.', ' . $diaFecha . ' de ' . $buscarMes . ' de ' . $verEvento['anio_registro']), '', 'C', 0);
            $pdf->Ln();
            $pdf->Ln();
            $pdf->SetX(95);
            $pdf->SetFont('Arial', 'B', 10);

            $rutaFirmaContralor = $this->atEventoModelo->metConsultarFirmaContralor($consultarContralor["pk_num_empleado"]);
            if ($rutaFirmaContralor['ind_firma_png'])
            {
                $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaContralor['ind_firma_png'], 115, 155, 50, 30);
                $pdf->Cell(130, 5, "                                       ", 0, 0, 'C', 0);
            }
            else//Si no tiene firma registrada el contralor
            {
                $pdf->SetXY(95,170);
                $pdf->Cell(190 / 2, 5, "_______________________________________", 0, 1, 'C', 0);
            }

            $pdf->SetXY(95,175);
            $pdf->Cell(190 / 2, 5, utf8_decode($abreviaturaContralor." ".$consultarContralor['ind_nombre1'].' '.$consultarContralor['ind_apellido1']), 0, 1, 'C', 0);
            $pdf->SetXY(95,180);
            $pdf->Cell(190 / 2, 4, $infoOrganismoCert['ind_cargo_representante'], '', 0, 'C', 0);

            // CODIGO QR
            $this->metObtenerLibreria('qrlib', 'phpqrcode');
            $nombreFichero = ROOT . 'librerias' . DS . 'modEV' . DS . 'codigoQR' . DS. $pkNumEvento.$ponente['ind_cedula_documento'].'.png';
            if (file_exists($nombreFichero)) {

            } else {
                    QRcode::png($verCertificado['num_certificado'].' '.$pkNumPersona.' '.$ponente['ind_nombre1'] . ' ' . $ponente['ind_apellido1'].' '.$ponente['ind_cedula_documento'].' '.$verEvento['ind_nombre_evento'], $nombreFichero);
            }
            $pdf->SetXY(95, 90);
            $pdf->Cell(100,100); $pdf->Image(ROOT.'librerias'. DS . 'modEV' . DS . 'codigoQR'. DS. $pkNumEvento.$ponente['ind_cedula_documento'].'.png',10, 150,22,22);

		} else { //ponentes - certificados participantes

            $ponenteTipo = $this->atEventoModelo->metConsultarTipoPersona(1);
            $listarPonente = $this->atEventoModelo->metConsultarPonentesFirmantesCert($pkNumEvento, $ponenteTipo['pk_num_miscelaneo_detalle']);//metConsultarPonentes($pkNumEvento, $ponenteTipo['pk_num_miscelaneo_detalle']);
            $contadorPonente = count($listarPonente);
            $i=0;
            foreach($listarPonente as $ponente){
                $ponenteNombre[$i] = $ponente['ind_nombre1'].' '.$ponente['ind_nombre2'].' '.$ponente['ind_apellido1'];
                $instruccionPrevia = $ponente['cod_detalle'];
                $pkNumPersonaPonente = $ponente['fk_a003_num_persona'];

                //=======================================================

                $pkFirmaPonente[] = $ponente['fk_a003_num_persona'];
                $tipoFirmaPonente[] = $ponente['num_firma'];
                $rutaFirmaPonente[] = $ponente['ind_firma_png'];
                //=======================================================
                $numPersonasPonentes[$i] = $pkNumPersonaPonente;
                $consultarSexo = $this->atEventoModelo->metObtenerSexo($pkNumPersonaPonente);

                if(empty($ponente['cargo_visita']))
                {
                    $cargoVisita = $this->atEventoModelo->metBuscarCargo($pkNumPersonaPonente);
                    $cargoEmpleado[$i] = $cargoVisita["ind_nombre_cargo"];
                }
                else//la persona es un visitante con cargo
                {
                    $cargoEmpleado[$i] = $ponente['cargo_visita'];
                }

                if($consultarSexo['cod_detalle']=='M'){
                    $facilitar[$i] = 'FACILITADOR';
                } else {
                    $facilitar[$i] = 'FACILITADORA';
                }
                $abreviatura[$i] = $this->metGenerarAbreviatura($instruccionPrevia, $consultarSexo['cod_detalle']);
                $i++;
            }

            //datos del partcicipante===============================
            $participante = $this->atEventoModelo->metConsultarTipoPersona(2);
            $persona = $this->atEventoModelo->metListarPersonaCertificado($pkNumEvento, $participante['pk_num_miscelaneo_detalle'], $pkNumPersona);
            $correo = $persona['ind_email'];

            $pdf->AliasNbPages();
            $pdf->AddPage();
            $pdf->SetAutoPageBreak(true, 5);
            $pdf->imagenCertificado($verEvento['ind_certificado']);

            $pdf->SetFont('Arial', 'B', 8);
            $verCertificado = $this->atEventoModelo->metObtenerCertificado($pkNumEvento, $pkNumPersona, 2);
            $pdf->setXY(105, 74);
            $pdf->Cell(22, 4, utf8_decode("Certificado N°"), 0, 0, 'C', 0);
            $pdf->Cell(26, 4, utf8_decode("Actividad N° "), 0, 0, 'C', 0);
            $pdf->Cell(17, 4, "Fecha", 0, 0, 'C', 0);
            $pdf->setXY(105, 79);
            $pdf->Cell(22, 4, $verCertificado['num_certificado'], 0, 0, 'C', 0);
            $pdf->Cell(26, 4, str_pad($verEvento['pk_num_evento'], 6, "0", STR_PAD_LEFT) . '-' . $verEvento['anio_registro'], 0, 0, 'C', 0);
            $pdf->Cell(17, 4, $verEvento['fecha_registro'], 0, 0, 'C', 0);
            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            $pdf->Ln();
            //==============
            $pdf->SetFont('Arial', 'B', 16);
            $pdf->MultiCell(0, 7, utf8_decode($persona['ind_nombre1'] . ' ' . $persona['ind_apellido1']), '', 'C', 0);
            $pdf->Ln(1);
            $pdf->MultiCell(0, 7, "C.I " . number_format($persona['ind_cedula_documento'], 0, "", "."), '', 'C', 0);
            $pdf->Ln();
            $pdf->SetFont('Arial', '', 11);
            //=======
            if(strcmp("RECONOCIMIENTO", trim($verEvento['ind_nombre_detalle']))!=0)
            {
                $pdf->MultiCell(0, 7, utf8_decode('POR HABER ASISTIDO ' . $continuacion . ' ' . $verEvento['ind_nombre_detalle']), '', 'C', 0);
                $cad_duracion_eve = 'Duración: ' . $duracion;
            }
            else
            {
                $cad_duracion_eve = '';
            }
            //=======
            $pdf->SetFont('Arial', 'BI', 17);
            $pdf->SetTextColor(0,0,160);
            $pdf->MultiCell(0, 7, utf8_decode($verEvento['ind_nombre_evento']), '', 'C', 0);
            $pdf->SetTextColor(0, 0, 0);
            $pdf->SetFont('Arial', '', 10.5);
            $pdf->MultiCell(0, 7, utf8_decode($cad_duracion_eve), '', 'C', 0);
            $pdf->MultiCell(0, 7, utf8_decode($ciudadCertificado.', ' . $diaFecha . ' de ' . $buscarMes . ' de ' . $verEvento['anio_registro']), '', 'C', 0);
            $pdf->SetFont('Arial', 'B', 10);
            $pdf->Ln();
            $pdf->Ln();
            //=======
            if(strcmp("RECONOCIMIENTO", trim($verEvento['ind_nombre_detalle']))!=0)//EL EVENTO ES DISTINTO A UN RECONOCIMIENTO
            {
                //NOTA: SOLO SE PERMITEN 3 FIRMAS, EL CONTRALOR FIRMA TODOS LOS CERTIFICADOS
                if($contadorPonente==1)// 1 SOLO PONENTE
                {
                    if($pkFirmaPonente[0] > 0)//PONENTE FIRMA
                    {
                        if ($pkFirmaPonente[0] == $consultarContralor["pk_num_empleado"])// 1 FIRMA - EXPONTE CONTRALOR
                        {

                            $pdf->SetFont('Arial', 'B', 10);
                            //=======
                            if ($tipoFirmaPonente[0] == 1)//firma escrita
                            {

                                $pdf->SetXY(95,170);
                                $pdf->Cell(190 / 2, 5, "_______________________________________", 0, 1, 'C', 0);
                            }
                            else
                                if ($tipoFirmaPonente[0] == 2)//firma de imagen
                                {
                                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 115, 155, 50, 30);
                                }
                            //======
                            $pdf->SetXY(95,175);
                            $pdf->Cell(190 / 2, 5, utf8_decode($abreviaturaContralor." ". $consultarContralor['ind_nombre1'] . ' ' . $consultarContralor['ind_apellido1']), 0, 1, 'C', 0);
                            $pdf->SetXY(95,180);
                            $pdf->Cell(190 / 2, 4, $infoOrganismoCert['ind_cargo_representante'], '', 0, 'C', 0);
                        }
                        else// PONENTE - NO ES EL CONTRALOR - 2 FIRMAS
                        {

                            $rutaFirmaContralor = $this->atEventoModelo->metConsultarFirmaContralor($consultarContralor["pk_num_empleado"]);

                            if ($rutaFirmaContralor['ind_firma_png'])
                            {
                                $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaContralor['ind_firma_png'], 50, 155, 50, 30);

                            }
                            else//Si no tiene firma registrada el contralor
                            {
                                $pdf->SetXY(10,170);
                                $pdf->Cell(130, 5, "__________________________________", 0, 0, 'C', 0);
                            }

                            if ($tipoFirmaPonente[0] == 1)
                            {
                                $pdf->SetXY(140,170);
                                $pdf->Cell(130, 5, "__________________________________", 0, 1, 'C', 0);
                            }
                            else
                            {
                                if ($tipoFirmaPonente[0] == 2)
                                {
                                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 180, 155, 50, 30);

                                }
                            }

                            $pdf->SetXY(10,175);
                            $pdf->Cell(130, 5, utf8_decode($abreviaturaContralor.' ' . $consultarContralor['ind_nombre1'] . ' ' . $consultarContralor['ind_nombre2'] . ' ' . $consultarContralor['ind_apellido1'] . ' ' . $consultarContralor['ind_apellido2']), 0, 0, 'C', 0);
                            $pdf->SetXY(10,180);
                            $pdf->Cell(130, 4, $infoOrganismoCert['ind_cargo_representante'], 0, 0, 'C', 0);
                            //===
                            $pdf->SetXY(140,175);
                            $pdf->Cell(130, 5, utf8_decode($abreviatura[0] . ' ' . $ponenteNombre[0]), 0, 1, 'C', 0);
                            $pdf->SetXY(140,180);
                            $pdf->Cell(130, 4, $facilitar[0], 0, 0, 'C', 0);
                        }
                    }

                }
                else
                {
                    if($contadorPonente==2)//2 PONENTES
                    {
                        if( $numPersonasPonentes[0] == $consultarContralor["pk_num_empleado"] || $numPersonasPonentes[1] == $consultarContralor["pk_num_empleado"])
                        {   //UNO DE LOS PONENTES ES EL CONTRALOR - SOLO 2 FIRMAS

                            if($numPersonasPonentes[0] == $consultarContralor["pk_num_empleado"])
                            {

                                $cad_facilitar1 = $infoOrganismoCert['ind_cargo_representante'];
                                $cad_facilitar2 = $facilitar[1];
                            }
                            else
                            {

                                $cad_facilitar2 = $infoOrganismoCert['ind_cargo_representante'];
                                $cad_facilitar1 = $facilitar[0];

                            }

                            //====
                            if ($tipoFirmaPonente[0] == 1)
                            {

                                $pdf->SetXY(10,170);
                                $pdf->Cell(130, 5, "__________________________________", 0, 0, 'C', 0);

                            }
                            else
                            {
                                if ($tipoFirmaPonente[0] == 2)
                                {
                                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 50, 155, 50, 30);

                                }

                            }

                            if ($tipoFirmaPonente[1] == 1)
                            {

                                $pdf->SetXY(140,170);
                                $pdf->Cell(130, 5, "__________________________________", 0, 1, 'C', 0);

                            }
                            else
                            {
                                if ($tipoFirmaPonente[1] == 2)
                                {
                                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[1], 180, 155, 50, 30);

                                }

                            }
                            //====
                            $pdf->SetXY(10,175);
                            $pdf->Cell(130, 5, utf8_decode($abreviatura[0] . $ponenteNombre[0] ), 0, 0, 'C', 0);
                            $pdf->SetXY(10,180);
                            $pdf->Cell(130, 4, $cad_facilitar1, 0, 0, 'C', 0);
                            //===
                            $pdf->SetXY(140,175);
                            $pdf->Cell(130, 5, utf8_decode($abreviatura[1] . ' ' . $ponenteNombre[1]), 0, 1, 'C', 0);
                            $pdf->SetXY(140,180);
                            $pdf->Cell(130, 4, $cad_facilitar2, 0, 0, 'C', 0);

                        }
                        else //NINGUNO DE LOS DOS PONENTES ES CONTRALOR - 3 FIRMAS
                        {
                            $pdf->SetFont('Arial', 'B', 9);
                            //===CONTRALOR
                            $rutaFirmaContralor = $this->atEventoModelo->metConsultarFirmaContralor($consultarContralor["pk_num_empleado"]);

                            if ($rutaFirmaContralor['ind_firma_png'])
                            {
                                $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaContralor['ind_firma_png'], 120, 155, 50, 30);

                            }
                            else//Si no tiene firma registrada el contralor
                            {
                                $pdf->SetXY(120,170);
                                $pdf->Cell(50, 5, "__________________________", 0, 0, 'C', 0);
                            }


                            $pdf->SetXY(80,175);
                            $pdf->Cell(130, 5, utf8_decode($abreviaturaContralor." ". $consultarContralor['ind_nombre1'] . ' ' . $consultarContralor['ind_nombre2'] . ' ' . $consultarContralor['ind_apellido1'] . ' ' . $consultarContralor['ind_apellido2'] ), 0, 0, 'C', 0);
                            $pdf->SetXY(80,180);
                            $pdf->Cell(130, 4, $infoOrganismoCert['ind_cargo_representante'], 0, 0, 'C', 0);

                            //=====PONENTE 1
                            if ($tipoFirmaPonente[0] == 1)
                            {

                                $pdf->SetXY(40,170);
                                $pdf->Cell(50, 5, "__________________________", 0, 0, 'C', 0);

                            }
                            else//Si no tiene firma registrada el contralor
                            {
                                if ($tipoFirmaPonente[0] == 2)
                                {
                                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 40, 155, 50, 30);

                                }

                            }

                            $pdf->SetXY(10,175);
                            $pdf->Cell(110, 5, utf8_decode($abreviatura[0] . ' ' . $ponenteNombre[0]), 0, 0, 'C', 0);
                            $pdf->SetXY(10,180);
                            $pdf->Cell(110, 4, $facilitar[0], 0, 0, 'C', 0);


                            //=====PONENTE 2
                            if ($tipoFirmaPonente[1] == 1)
                            {

                                $pdf->SetXY(200,170);
                                $pdf->Cell(50, 5, "__________________________", 0, 1, 'C', 0);

                            }
                            else//Si no tiene firma registrada el contralor
                            {
                                if ($tipoFirmaPonente[1] == 2)
                                {
                                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[1], 200, 155, 50, 30);

                                }

                            }

                            $pdf->SetXY(170,175);
                            $pdf->Cell(110, 5, utf8_decode($abreviatura[1] . ' ' . $ponenteNombre[1]), 0, 1, 'C', 0);
                            $pdf->SetXY(170,180);
                            $pdf->Cell(110, 4, $facilitar[1], 0, 0, 'C', 0);

                        }
                    }
                    else //3 FIRMAS
                    {
                        // 3 PONENTES Y UNO ES CONTRALOR
                        $pdf->SetFont('Arial', 'B', 9);

                        if($numPersonasPonentes[0] == $consultarContralor["pk_num_empleado"])
                        {
                            $facilitar[0] = $infoOrganismoCert['ind_cargo_representante'];

                        }
                        else
                        {
                            if($numPersonasPonentes[1] == $consultarContralor["pk_num_empleado"])
                            {
                                $facilitar[1] = $infoOrganismoCert['ind_cargo_representante'];

                            }
                            else
                            {
                                $facilitar[2] = $infoOrganismoCert['ind_cargo_representante'];
                            }
                        }

                        if($tipoFirmaPonente[0] == 1)
                        {
                            $pdf->SetXY(40,170);
                            $pdf->Cell(50, 5, "__________________________", 0, 0, 'C', 0);
                        }
                        else
                        {
                            if ($tipoFirmaPonente[0] == 2)
                            {
                                $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[0], 40, 155, 50, 30);
                            }
                        }

                        $pdf->SetXY(10,175);
                        $pdf->Cell(110, 5, utf8_decode($abreviatura[0] . ' ' . $ponenteNombre[0]), 0, 0, 'C', 0);
                        $pdf->SetXY(10,180);
                        $pdf->Cell(110, 4, $facilitar[0], 0, 0, 'C', 0);

                        //==

                        if($tipoFirmaPonente[1] == 1)
                        {
                            $pdf->SetXY(119,170);
                            $pdf->Cell(50, 5, "__________________________", 0, 0, 'C', 0);
                        }
                        else
                        {
                            if ($tipoFirmaPonente[1] == 2)
                            {
                                $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[1], 119, 155, 50, 30);
                            }
                        }

                        $pdf->SetXY(80,175);
                        $pdf->Cell(130, 5, utf8_decode($abreviatura[1] . ' ' . $ponenteNombre[1]), 0, 0, 'C', 0);
                        $pdf->SetXY(80,180);
                        $pdf->Cell(130, 4, $facilitar[1], 0, 0, 'C', 0);

                        //===

                        if($tipoFirmaPonente[2] == 1)
                        {
                            $pdf->SetXY(200,170);
                            $pdf->Cell(50, 5, "__________________________", 0, 1, 'C', 0);
                        }
                        else
                        {
                            if ($tipoFirmaPonente[2] == 2)
                            {
                                $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaPonente[2], 200, 155, 50, 30);

                            }
                        }

                        $pdf->SetXY(170,175);
                        $pdf->Cell(110, 5, utf8_decode($abreviatura[2] . ' ' . $ponenteNombre[2]), 0, 1, 'C', 0);
                        $pdf->SetXY(170,180);
                        $pdf->Cell(110, 4, $facilitar[2], 0, 0, 'C', 0);

                    }
                }
            }
            else
            {
                //ES UN RECONOCIMIENTO
                $pdf->SetFont('Arial', 'B', 10);

				$rutaFirmaContralor = $this->atEventoModelo->metConsultarFirmaContralor($consultarContralor["pk_num_empleado"]);

                $pdf->Ln();

                if ($rutaFirmaContralor['ind_firma_png'])
                {
                    $pdf->Image(ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' . DS . 'firmas' . DS . $rutaFirmaContralor['ind_firma_png'], 115, 155, 50, 30);

                }
                else//Si no tiene firma registrada el contralor
                {
                    $pdf->SetXY(95,170);
                    $pdf->Cell(190 / 2, 5, "_______________________________________", 0, 1, 'C', 0);
                }

                $pdf->SetXY(95,175);
                $pdf->Cell(190 / 2, 5, utf8_decode($abreviaturaContralor." ". $consultarContralor['ind_nombre1'] . ' ' . $consultarContralor['ind_apellido1']), 0, 1, 'C', 0);
                $pdf->SetXY(95,180);
                $pdf->Cell(190 / 2, 4, $infoOrganismoCert['ind_cargo_representante'], '', 0, 'C', 0);

            }

            // CODIGO QR
            $this->metObtenerLibreria('qrlib', 'phpqrcode');
            $nombreFichero = ROOT . 'librerias' . DS . 'modEV' . DS . 'codigoQR' . DS. $pkNumEvento.$persona['ind_cedula_documento'].'.png';
            if (file_exists($nombreFichero)) {

            } else {
                QRcode::png($verCertificado['num_certificado'].' '.$pkNumPersona.' '.$persona['ind_nombre1'] . ' ' . $persona['ind_apellido1'].' '.$persona['ind_cedula_documento'].' '.$verEvento['ind_nombre_evento'], $nombreFichero);
            } 
            $pdf->SetXY(95, 90);
            $pdf->Cell(100,100); $pdf->Image(ROOT.'librerias'. DS . 'modEV' . DS . 'codigoQR'. DS. $pkNumEvento.$persona['ind_cedula_documento'].'.png',10, 150,22,22);
		}
        $pdf->AliasNbPages();
        $pdf->AddPage();
        $pdf->SetAutoPageBreak(true, 5);
        $pdf->SetFont('Arial','B',20);
        $pdf->Ln();
        $pdf->SetXY(10, 15);
        $pdf->Cell(40,5,"CONTENIDO:",'',0,'C',0);
        $pdf->Ln();
        $verTema = $this->atEventoModelo->metVerTema($pkNumEvento);
        $pdf->Ln();
        $pdf->SetFont('Arial','',12);
        $pdf->SetTextColor(0, 0, 0);
        foreach($verTema as $tema){
            $pdf->MultiCell(0, 7, utf8_decode('.- ' .$tema['ind_tema']), '', 'L', 0);
        }
        // Ruta donde guardare temporalmente el pdf
		$archivo = ROOT . 'publico' . DS . 'imagenes' . DS . 'modEV' .DS.'certificado'.$pkNumPersona.''.$pkNumEvento.'.pdf';
        $pdf->Output($archivo);
        $nombreEvento = $verEvento['ind_nombre_evento'];
        $cuerpoCorreo = utf8_decode('Buenas! Adjunto se envía Certificado de Participación en el evento "'.$nombreEvento.'", por parte de la Contraloría del estado Sucre');
        // Valores a enviar
        $this->metConfigurarCorreo($archivo, $nombreEvento, $correo, $nombrePersona, $cuerpoCorreo);
		// Fin del PDF

	}

	// Configuracion del correo a enviar
	public function metConfigurarCorreo($archivo, $nombreEvento, $correo, $nombrePersona, $cuerpoCorreo)
	{


		$this->metObtenerLibreria('PHPMailerAutoload', 'PHPMailer');
        $mail = new PHPMailer();
		//Definir que vamos a usar SMTP
        $mail->IsSMTP();

        $mail->SMTPOptions = array(
            'ssl' => array (
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
		//Esto es para activar el modo depuración. En entorno de pruebas lo mejor es 2, en producción siempre 0
		// 0 = off (producción)
		// 1 = client messages
		// 2 = client and server messages
        $mail->SMTPDebug  = 0;
		//Ahora definimos gmail como servidor que aloja nuestro SMTP
        $mail->Host       = $this->atHostEmailGevento;//'smtp.gmail.com';
		//El puerto será el 587 ya que usamos encriptación TLS
        $mail->Port       = 587;
		//Definmos la seguridad como TLS
        $mail->SMTPSecure = 'TLS';
		//Tenemos que usar gmail autenticados, así que esto a TRUE
        $mail->SMTPAuth   = true;
		//Definimos la cuenta que vamos a usar. Dirección completa de la misma

		$mail->Username =  $this->atEmailGevento;
		//Introducimos nuestra contraseña de gmail

        $mail->Password   = $this->atPassEmailGevento;
		//Definimos el remitente (dirección y, opcionalmente, nombre)
        $mail->SetFrom($this->atEmailGevento, utf8_decode('Contraloría del estado Sucre'));
		//Esta línea es por si queréis enviar copia a alguien (dirección y, opcionalmente, nombre)
		//$mail->AddReplyTo('correo_de_la_copia@hotmail.com','El de la réplica');
		//Y, ahora sí, definimos el destinatario (dirección y, opcionalmente, nombre)
        $mail->AddAddress($correo, $nombrePersona);
		//Definimos el tema del email
        $mail->Subject = 'CERTIFICADO DEL EVENTO '.utf8_decode($nombreEvento);
		//Y por si nos bloquean el contenido HTML (algunos correos lo hacen por seguridad) una versión alternativa en texto plano (también será válida para lectores de pantalla)
        $mail->Body = $cuerpoCorreo;
		//Enviamos el correo
        $mail->addAttachment($archivo);
        // Envio el correo
       // $mail->Send();


		$result = $mail->Send();


		if(!$result) {
			//echo "error ".$mail->ErrorInfo;
			$datos['mensaje'] = 'no';
			$datos['error'] = $mail->ErrorInfo;
			echo json_encode($datos);
		} else {
			$datos['mensaje'] = 'ok';
			echo json_encode($datos);
		}
		chmod($archivo, 0777);
		unlink($archivo);
	}

    //Método que permite listar el
    public function metBuscarEnte()
    {
        $pkNumTipoEnte = $_POST['pk_num_tipo_ente'];
        $listarEntePadre=$this->atEventoModelo->metBuscarEntePadre($pkNumTipoEnte);
        $a = '<div class="form-group floating-label"><select class="form-control dirty" name="pk_num_ente" id="pk_num_ente"><option value="0">&nbsp;</option>';
        foreach( $listarEntePadre as $listarPadre){
            $a .='<option value="'.$listarPadre['pk_num_ente'].'">'.$listarPadre['ind_nombre_ente'].'</option>';
        }
        $a .= '</select><p class="help-block">Opcional</p><label for="pk_num_ente""><i class="glyphicon glyphicon-menu-hamburger"></i> Ente</label></div>';
        echo $a;
    }

	public function metFirmaImpresa()
	{
		$pk_persona = $_POST['pk_persona'];
		$valor_indice = $_POST['valor_indice'];
		$nombre = $_POST['ind_nombre'];
		$cedula = $_POST['ind_cedula_documento'];
		$imagenFirma = $this->atEventoModelo->metBuscarFirmaImpresa($pk_persona);

		if($imagenFirma["ind_firma_png"])
		{
			$band = 1;//hay firma png
			$this->atVista->assign('imagenFirma', $imagenFirma["ind_firma_png"]);
		}
		else
		{
		    $band = 0;//No hay firma png
		}


		$this->atVista->assign('valor_indice', $valor_indice);
		$this->atVista->assign('pk_persona', $pk_persona);
		$this->atVista->assign('band', $band);
		$this->atVista->assign('nombre', $nombre);
		$this->atVista->assign('cedula', $cedula);
		$this->atVista->metRenderizar('firmaImpresa');
	}
	
	public function metFirmaImpresaSello()
	{
		$pk_persona = $_POST['pk_persona'];
		$valor_indice = $_POST['valor_indice'];
		$nombre = $_POST['ind_nombre'];
		$cedula = $_POST['ind_cedula_documento'];
		$imagenFirma = $this->atEventoModelo->metBuscarFirmaImpresaSello($pk_persona);

		if($imagenFirma["ind_firma_png_sello"])
		{
			$band = 1;//hay firma png
			$this->atVista->assign('imagenFirma', $imagenFirma["ind_firma_png_sello"]);
		}
		else
		{
		    $band = 0;//No hay firma png
		}


		$this->atVista->assign('valor_indice', $valor_indice);
		$this->atVista->assign('pk_persona', $pk_persona);
		$this->atVista->assign('band', $band);
		$this->atVista->assign('nombre', $nombre);
		$this->atVista->assign('cedula', $cedula);
		$this->atVista->metRenderizar('firmaImpresaSello');
	}

	public function metGuardarFirmaPng()
	{
		$pk_persona = $_POST['pk_persona'];

		if(isset($_FILES["ind_ruta_img"]["name"]))
		{
			$cod_firma= mt_rand();
			$nombre_firma_f   = $cod_firma."_".$_FILES["ind_ruta_img"]["name"];
			$ruta_carpeta =  "publico/imagenes/modEV/firmas/";
			$ruta = $ruta_carpeta.$nombre_firma_f;
			if (!file_exists($ruta))
			{
				if (is_uploaded_file($_FILES['ind_ruta_img']['tmp_name']))
				{
					$resultado = move_uploaded_file($_FILES["ind_ruta_img"]["tmp_name"], $ruta);

					if ($resultado)
					{
						chmod($ruta, 0777);
						$bandFile = 1;
					}
					else
					{
						$bandFile = 0;
					}

					if($bandFile == 1)
					{
						$respuesta = $this->atEventoModelo->metRegistratFirmaPng($pk_persona, $nombre_firma_f);
						if($respuesta)
						{
							echo 1;
						}
						else
						{
							echo -3;//error al actualizar bd
						}
					}
					else
					{
						echo -2;//error al renombrar archivo
					}
				}
			}
			else
			{
				echo 0; //el nombre de la firma ya existe
			}

		}
		else
		{
			echo -1;//error no se subio el archivo
		}
	}

	public function metJsonDataTabla($opcionBuscar=false , $pkNumOrganismo=false,$pkNumDependencia=false, $indCedulaDocumento=false  )
	{

		#obtengo los rodes de usuario, Nota: esto es obligatorio
		$rol=Session::metObtener('perfil');
		#cacturo la busqueda enviada por la datatabla, Nota: esto es obligatorio
		$busqueda = $this->metObtenerFormulas('search');
		#construyo el sql, Nota: esto es obligatorio

		$filtro=" ";

		if ($opcionBuscar == 1) {
			if ($pkNumOrganismo) {
				$filtro .= " and b.fk_a001_num_organismo=$pkNumOrganismo";
			}
			if ($pkNumDependencia) {
				$filtro .= " and b.fk_a004_num_dependencia=$pkNumDependencia";
			}
			if ($indCedulaDocumento) {
				  $filtro .= " and p.ind_cedula_documento  LIKE '%$indCedulaDocumento%'";
			}

				$sql="select p.pk_num_persona, p.pk_num_empleado, p.ind_cedula_documento, p.ind_nombre1, p.ind_nombre2, p.ind_apellido1, p.ind_apellido2,CONCAT_WS(' ', p.ind_nombre1, p.ind_nombre2, p.ind_apellido1, p.ind_apellido2) AS nombre_completo 
						from vl_rh_persona_empleado as p
						inner join vl_rh_persona_empleado_datos_laborales as b on p.pk_num_empleado = b.pk_num_empleado
						where 
						    p.ind_estatus_empleado = 1 
						    " . $filtro;

		} else {
			if ($indCedulaDocumento != '') {
				$filtro = "AND p.ind_cedula_documento LIKE '%$indCedulaDocumento%'";
			} else {
				$filtro = '';
			}

				$sql="select pk_num_persona, ind_cedula_documento,CONCAT_WS(' ', ind_nombre1, ind_nombre2, ind_apellido1, ind_apellido2) AS nombre_completo from a003_persona p WHERE 1=1 $filtro";
		}

		if ($busqueda['value']) {
			$sql .= " AND
                        (p.ind_cedula_documento LIKE '%$busqueda[value]%' OR
                        p.ind_nombre1 LIKE '%$busqueda[value]%' OR
                        p.ind_nombre2 LIKE '%$busqueda[value]%' OR
                        p.ind_apellido1 LIKE '%$busqueda[value]%' OR
                        p.ind_apellido2 LIKE '%$busqueda[value]%' 
                        ) 
                        ";
		}

		#creo un arreglo de los campos a mostrar, Nota: esto es obligatorio
		#campo primario de la tabla, Nota: esto es obligatorio
		$clavePrimaria = 'pk_num_persona';
		$campos=array('pk_num_persona','pk_num_persona','nombre_completo','ind_cedula_documento');
		$camposExtra="";
		#construyo el listado de botones
		$campos['boton']['Nuevo'] = "               
                <button type='button' num_persona='$clavePrimaria' 
                class='cargar logsUsuario btn ink-reaction btn-raised btn-xs btn-primary' 
                descripcion='El usuario ha buscado un empleado' title='Cargar empleado'>
                <i class='glyphicon glyphicon-download'></i></button>
                </button>
                ";

		#hago el llamado de la datatabla del controlador principal.
		$this->metDataTabla($sql,$campos,$clavePrimaria,$camposExtra);
	}







}
?>
