<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
 
class Queja extends CI_Controller{
    function __construct()
    {
        parent::__construct();
        $this->load->model('Queja_model');
        $this->load->model('Comentarioqueja_model');
    } 

    /*
     * Listing of quejas
     */
    function index($page = FALSE)
    {
        if(!($this->session->userdata('id'))) 
        {
            redirect(base_url()."login");
        };

        $breadcrumb = array(
            "Quejas" => ""
        );
        $data['breadcrumb'] = $breadcrumb;

        $params['page'] = $page;
        $params['limit'] = 5; 
        $params['offset'] = $page ? (($page - 1) * $params['limit']) : 0;
        
        $config = $this->config->item('pagination');
        $config['base_url'] = site_url('queja/page');
        $config['total_rows'] = $this->Queja_model->get_all_quejas_count();
        $config['per_page'] = $params['limit'];
        $config['use_page_numbers'] = TRUE;
        $config['first_url'] = base_url('queja');
        $config['attributes'] = array('class' => 'page-link');
        $config['full_tag_open'] = '<ul class="pagination">';
        $config['full_tag_close'] = '</ul>';
        $config['cur_tag_open'] = '<li class="page-item active"><span class="page-link">';
        $config['cur_tag_close'] = '</span></li>';
        $config['num_tag_open'] = '<li class="page-item">';
        $config['num_tag_close'] = '</li>';
        $config['prev_tag_open'] = '<li class="page-item">';
        $config['prev_tag_close'] = '</li>';
        $config['next_tag_open'] = '<li class="page-item">';
        $config['next_tag_close'] = '</li>';
        $config['first_tag_open'] = '<li class="page-item">';
        $config['first_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li class="page-item">';
        $config['last_tag_close'] = '</li>';
        $config['first_link'] = "<<";
        $config['last_link'] = ">>";
        $this->pagination->initialize($config);

        $data['listado'] = FALSE;
        $data['controlador'] = 'queja';
        $data['quejas'] = $this->Queja_model->get_all_quejas($params);
        
        $data['contenido'] = 'queja/index';
        $data['titulo'] = 'Quejas';
        $this->load->view('templates/template_admin', $data);
    }

    /*
     * Adding a new queja Un administrador no puede registrar quejas
     */
    function add()
    {   
        $this->load->library('form_validation');

		$this->form_validation->set_rules('titulo','Titulo','required');
		$this->form_validation->set_rules('descripcion','Descripcion','required');
		
		if($this->form_validation->run())     
        {   
            $params = array(
				'titulo' => $this->input->post('titulo'),
				'descripcion' => $this->input->post('descripcion'),
				'imagen' => $this->input->post('imagen'),
				'id_condominio' => $this->input->post('id_condominio'),
				'id_autor' => $this->input->post('id_autor'),
				'fecha_registro' => $this->input->post('fecha_registro'),
				'fecha_modificacion' => $this->input->post('fecha_modificacion'),
				'estado' => $this->input->post('estado'),
            );
            
            $queja_id = $this->Queja_model->add_queja($params);
            redirect('queja/index');
        }
        else
        {            
            $data['_view'] = 'queja/add';
            $this->load->view('layouts/main',$data);
        }
    } 

    /*
     * Editing a queja
     */
    function edit($id)
    {   
        if(!($this->session->userdata('id'))) 
        {
            redirect(base_url()."login");
        };
        $breadcrumb = array(
            "Quejas" => "../",
            "Editar" => ""
        );
        $data['breadcrumb'] = $breadcrumb;
        // check if the queja exists before trying to edit it
        $data['queja'] = $this->Queja_model->get_queja($id);
        
        if(isset($data['queja']['id']))
        {
            $this->load->library('form_validation');

			$this->form_validation->set_rules('titulo','Titulo','required');
			$this->form_validation->set_rules('descripcion','Descripcion','required');
		
			if($this->form_validation->run())     
            {   
                $subir = $this->cargar_archivo($_FILES['userfile']['name']);

                if (!$subir['correcto']) {
                    // ERROR
                        $data['uploadError'] = $subir['error'];
                        $data['controlador'] = 'queja';
                        $data['contenido'] = 'queja/edit';
                        $data['titulo'] = 'Editar Queja';
                        $data['_view'] = 'queja/edit';
                        $this->load->view('templates/template_admin', $data);
                } else {
                    $archivo = $subir['archivo'];
                    if (is_null($archivo) ) {
                        $archivo = $this->input->post('imagen');
                    }

                    $params = array(
    					'titulo' => $this->input->post('titulo'),
    					'descripcion' => $this->input->post('descripcion'),
    					'imagen' => $archivo,
    					'id_condominio' => $this->input->post('id_condominio'),
    					'id_autor' => $this->input->post('id_autor'),
    					'fecha_registro' => $this->input->post('fecha_registro'),
    					'fecha_modificacion' => date("Y-m-d H:i:s"),
    					'estado' => $this->input->post('estado'),
                    );

                    $this->Queja_model->update_queja($id,$params);            
                    redirect('queja');
                }
            }
            else
            {
                $data['controlador'] = 'queja';
                $data['contenido'] = 'queja/edit';
                $data['titulo'] = 'Editar Queja';
                $data['_view'] = 'queja/edit';
                $this->load->view('templates/template_admin', $data);
            }
        }
        else
            show_error('The queja you are trying to edit does not exist.');
    } 

    /*
     * Deleting queja
     */
    function remove($id)
    {
        $queja = $this->Queja_model->get_queja($id);

        // check if the queja exists before trying to delete it
        if(isset($queja['id']))
        {
            $this->Queja_model->delete_queja($id);
            redirect('queja');
        }
        else
            show_error('The queja you are trying to delete does not exist.');
    }

    function detail($id)
    {   
        if(!($this->session->userdata('id'))) 
        {
            redirect(base_url()."login");
        };

        $breadcrumb = array(
            "Quejas" => "../",
            $id => ""
        );
        $data['breadcrumb'] = $breadcrumb;

        // check if the visita exists before trying to edit it
        $data['queja'] = $this->Queja_model->get_queja($id);
        
        if(isset($data['queja']['id']))
        {
           
            $data['comentarios'] = $this->Comentarioqueja_model->get_all_comentariosquejas_of_queja($id);


            $this->load->model('Usuario_model');
            $data['usuario'] = $this->Usuario_model->get_usuario($data['queja']['id_autor']);

            $data['controlador'] = 'queja';
            $data['contenido'] = 'queja/detail';
            $data['titulo'] = 'Detalle de Queja';
            $this->load->view('templates/template_admin', $data);            
        }        
        else
            show_error('The queja you are trying to view does not exist.');
    } 


    function cargar_archivo($file)
    {
        if ($file != NULL) {
            $str=rand(); 
            $result = sha1($str); 
            $archivo = null;
            $ext = pathinfo(convert_accented_characters($file), PATHINFO_EXTENSION);

            $config['upload_path'] = "./assets/uploads";
            $config['file_name'] = $result . $ext;
            $config['allowed_types'] = "jpg|png";
            $config['max_filename'] = 20;

            $this->load->library('upload', $config);

            $resultado = $this->upload->do_upload();

            $respuesta = array (
                "correcto" => $resultado,
                "error" => ($resultado ? NULL : $this->upload->display_errors()),
                "archivo" => ($resultado ? base_url('assets/uploads') . '/' . $this->upload->data('file_name') : NULL)
            );        
        } else {
            $respuesta = array (
                "correcto" => TRUE,
                "error" => NULL,
                "archivo" => NULL
            ); 
        }
        return $respuesta;
    }
    
}
