<?php 
/*****************************************************************************************************************************************
 * DEV: CONTRALORIA DE ESTADOS
 * PROYECTO: SISTEMA INTEGRAL ADMINISTRATIVO DE CONTRALORIAS DE ESTADOS
 * MODULO: INTRANET
 * PROCESO: GESTIONAR LAS NOTICIAS
 * PROGRAMADORES:
 * | # |          NOMBRES Y APELLIDOS              |               CORREO               |          TELEFONO              |
 * | 1  |         Maikol Isava                                  |    maikol.isava@gmail.com      |          0426-1814058          |
 * |___|___________________________________________|____________________________________|________________________________|
 *
 * VERSION
 *
 * |          PROGRAMADOR                  |          FECHA          |       VERSION      |
 * |               #1                      |        08-05-2016       |         1.0        |
 * |_______________________________________|_________________________|____________________|
 *
 *****************************************************************************************************************************************/
 class noticiaControlador extends Controlador
{
    private $atModeloNoticias;
    private $atIdUsuario;

    public function __construct()
    {
        parent::__construct();
        Session::metAcceso();
        $this->atIdUsuario = Session::metObtener('idUsuario');
        $this->atIdCgr = Session::metObtener('IDCGRBD');
		$this->atModeloNoticias = $this->metCargarModelo('noticia');

    }

    
    public function metIndex()
    {
		
        $complementosCss = array(
            'DataTables/jquery.dataTables',
            'wizard/wizardfa6c',
            'jquery-validation/dist/site-demo',
            'select2/select201ef',
            'bootstrap-datepicker/datepicker'
        );
        $complementoJs = array(
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min',
            'select2/select2.min',
            'wizard/jquery.bootstrap.wizard.min',
            'bootstrap-datepicker/bootstrap-datepicker',
			'ckeditor/ckeditor',
			'ckeditor/adapters/jquery'
        );
        $js = array(//'materialSiace/core/demo/DemoTableDynamic',
                'materialSiace/core/demo/DemoFormWizard',
                'materialSiace/core/demo/DemoFormComponents',
				'materialSiace/core/demo/DemoFormEditors'

        );


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


        if($this->atIdCgr > 0)
        {
            $datosOrganismo  = $this->atModeloNoticias->metConsultarOrganismos($this->atIdCgr);
            $this->atVista->assign('datosOrganismo', $datosOrganismo);
            $this->atVista->metRenderizar('registrarNoticia');
        }
        else
        {
            echo "CREE EL PARAMETRO 'IDCGRBD' CON EL VALOR CORRESPONDIENTE AL ID EN BD, DEL ORGANISMO EXTERNO CONTRALORIA GENERAL DE LA REPUBLICA";
        }

		
	}

    
    public function  metRegistrar()
    {
        $cod_img= "not".mt_rand();
        $destino =  "publico/imagenes/modIN/noticias/";

        if(isset($_FILES["ind_ruta_img"]))
        {
            $img_f   = $cod_img."_".$_FILES["ind_ruta_img"]["name"];
            $ruta    = $destino.$img_f;
            if (!file_exists($ruta))//False si no existe
            {
                $resultado = move_uploaded_file($_FILES["ind_ruta_img"]["tmp_name"], $ruta);
                chmod($ruta, 0777);
                if ($resultado){
                   //Registrar la noticia
                   $ind_titulo = $this->metObtenerTexto("ind_titulo");
                    $ind_descripcion = $this->metObtenerTexto("ind_descripcion");
                    $txt_cuerpo = $_POST["ckeditor"];
                    $txt_fuente = $_POST["txt_fuente"];
                    $fec_noticia = $_POST["fec_noticia"];

                   $fec_registro = date('Y-m-d');
                   $hora_regisro = date('H:i:s');
                   $ind_ruta_img = $img_f;
                   $ind_status = "m";
                   

                   $resp  = $this->atModeloNoticias->metInsertarNoticia($ind_titulo, $ind_descripcion, $txt_cuerpo, $txt_fuente, $fec_registro,$hora_regisro, $ind_ruta_img, $ind_status,$fec_noticia);
                   if($resp)
                   {
                     echo 1;
                   }
                   else
                   {
                     echo -3;
                   } 
                   
                } 
                else
                {
                    echo -2;//ocurrio un error al mover el archivo
                }
             }
             else
             {
                echo 0;//el nombre ya existe no se registra la noticia
             }
        }
        else
        {
            echo -1;//error al cargar el input file
        }

                  
       
    }

    public function metListarNoticias()
    {
        $complementosCss = array(
            'DataTables/jquery.dataTables',
            'DataTables/extensions/dataTables.colVis941e',
            'DataTables/extensions/dataTables.tableTools4029',
            'wizard/wizardfa6c',
            'jquery-validation/dist/site-demo',
            'select2/select201ef',
            'bootstrap-datepicker/datepicker',

        );
        $complementoJs = array(
            'jquery-validation/dist/jquery.validate.min',
            'jquery-validation/dist/additional-methods.min',
            'select2/select2.min',
            'wizard/jquery.bootstrap.wizard.min',
            'bootstrap-datepicker/bootstrap-datepicker'
        );

        $js = array(
            'materialSiace/App',
            'materialSiace/core/demo/DemoFormWizard',
            'materialSiace/core/demo/DemoFormComponents',
            'modIN/printThis'

        );

        if($this->atIdCgr > 0)
        {

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

            $datosOrganismo = $this->atModeloNoticias->metConsultarOrganismos($this->atIdCgr);
            $datosNoticias = $this->atModeloNoticias->metListarNoticias(trim($datosOrganismo[0]["pk_num_organismo"]), '', '');//EL PRIMER ELEMENTO ES LA CONTRALORIA DE ESTADO

            $this->atVista->assign('datosOrganismo', $datosOrganismo);
            $this->atVista->assign('datosNoticias', $datosNoticias);


            $this->atVista->metRenderizar('listarNoticia');
        }
        else
        {
            echo "CREE EL PARAMETRO 'IDCGRBD' CON EL VALOR CORRESPONDIENTE AL ID EN BD, DEL ORGANISMO EXTERNO CONTRALORIA GENERAL DE LA REPUBLICA";
        }

        
    }

    public function metVisualizarNoticia()
    {
            $pk_num_noticia = $_POST['pk_num_noticia'];
            
            $datosNoticias  = $this->atModeloNoticias->metBusquedaUnicaNoticia2($pk_num_noticia);
            
            
            $aux = trim($datosNoticias["fec_registro"]);//2016-05-06
            $aux2 = explode('-', $aux);
            $fecha = $aux2[2]."-".$aux2[1]."-".$aux2[0];
            $datosNoticias["fec_registro"] = $fecha." ".$datosNoticias["hora_regisro"];
            
            $this->atVista->assign('datoNoticias', $datosNoticias );
            $this->atVista->metRenderizar('visualizarNoticia', 'modales');        
            
            
    }

    public function metEditarNoticia()
    {
                
        $complementoJs = array(
            
            'ckeditor/ckeditor',
            'ckeditor/adapters/jquery'
        );
        $js = array('materialSiace/core/demo/DemoFormEditors');


        $this->atVista->metCargarJsComplemento($complementoJs);
        $this->atVista->metCargarJs($js);
        
        $pk_num_noticia = $_POST['pk_num_noticia'];
        $datosNoticias  = $this->atModeloNoticias->metBusquedaUnicaNoticia2($pk_num_noticia);

        $datosOrganismo  = $this->atModeloNoticias->metConsultarOrganismos($this->atIdCgr);
        $this->atVista->assign('datosOrganismo', $datosOrganismo);
        
        $this->atVista->assign('datoNoticia', $datosNoticias );
        $this->atVista->metRenderizar('editarNoticia', 'modales');

    }

    public function metBuscarNoticiasFiltro()
    {
        $band = 0;
        if(isset($_POST['ind_descripcion_empresa_listar']))
        {    
            $organismo = $_POST['ind_descripcion_empresa_listar'];
            $band = 1;
        }
        else
            $organismo = '';

        if(isset($_POST['start_fecha_prepa']))
        {    
            $start_fecha_prepa = $_POST['start_fecha_prepa'];
            $end_fecha_prepa = $_POST['end_fecha_prepa'];

            $start_fecha_prepa = $this->atModeloNoticias->formatFechaAMD($start_fecha_prepa);

            $end_fecha_prepa = $this->atModeloNoticias->formatFechaAMD($end_fecha_prepa);
            $band = 1;
        }
        else
        {
            $start_fecha_prepa = '';
            $end_fecha_prepa = '';
        }


        if($band == 1)
            $datosNoticias  = $this->atModeloNoticias->metListarNoticias($organismo, $start_fecha_prepa, $end_fecha_prepa);
        else
            $datosNoticias = false;            


        if($datosNoticias)//FALSE SI NO HUBO RESULTADO
        {
            echo json_encode($datosNoticias);
        }
        else
            echo 0;
        
          
    }

    public function metModificarNoticia()
    {
        $cod_img= mt_rand();
        $destino =  "publico/imagenes/modIN/noticias/";

        if($_POST['swImagen']=='1')//se cambio la imagen
        {

            if(isset($_FILES["ind_ruta_img"]))
            {
                $img_f   = $cod_img."_".$_FILES["ind_ruta_img"]["name"];
                $ruta    = $destino.$img_f;
                if (!file_exists($ruta))//False si no existe
                {
                    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 = "-2 :" . $resultado;//error al mover el archivo
                        }
                    }
                    else
                    {
                        $bandFile = "-3";
                    }
                }
                else
                {
                   $bandFile= 0;//el nombre ya existe no se registra la noticia
                } 
            }
            else
            {
                $bandFile= -1;//error al cargar el input file
            }
        }
        else//No se cambio la imagen
        {
            $bandFile=1;
            $img_f = $_POST["ind_ruta_img_f"];
        }
        

        if($bandFile==1)//se registra
        {
            $ind_titulo = $_POST["ind_titulo"];
            $ind_descripcion = $_POST["ind_descripcion"];
            $txt_cuerpo = $_POST["ckeditor"];
            $txt_fuente = $_POST["txt_fuente"];

            $hora_regisro_editar = $_POST["hora_regisro_editar"];
            $fec_registro_editar = $_POST["fec_registro_editar"];
            $pk_num_noticia_editar= $_POST["pk_num_noticia_editar"];
            $fec_noticia = $_POST["fec_noticia"];

            $fec_ultima_modificacion = date('Y-m-d H:i:s');
                                      
            $ind_ruta_img = $img_f;
            $ind_status = $_POST["ind_status_editar"];

            $resp  = $this->atModeloNoticias->metModificarNoticia($pk_num_noticia_editar, $ind_titulo, $ind_descripcion, $txt_cuerpo, $txt_fuente, $fec_registro_editar,$hora_regisro_editar, $ind_ruta_img, $ind_status, $fec_ultima_modificacion,$fec_noticia );
            if($resp)
            {
                echo 1;
            }
            else
            {
                echo -3;
            } 

        }
        else
        {
            echo $bandFile; 
        } 

    }  

	
	
};
 
?>