<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Geocolonias extends Admin_Controller {

	public function __construct()
	{
		parent::__construct();

		$this->load->model('man_espacial/geocolonias/geocolonias_model');
		$this->lang->load('geocolonias/geocolonias');

		/* Titulo de la pagina :: Common */
		$this->page_title->push(lang('menu_geocolonias'));
		$this->data['pagetitle'] = $this->page_title->show();

		//verificación de módulo para el reset de las variables de sessión utilizadas en la misma
		if ($_SESSION['id_modulo'] != 'GEOCOLONIAS') {

			$_SESSION['arraywhere_geocolonia'] 			= NULL;
			$_SESSION['arraywhere_geocolonia_busqueda'] = NULL;
			$_SESSION['id_modulo'] = 'GEOCOLONIAS';
		}
		
		/* Breadcrumbs :: Common */
		$this->breadcrumbs->unshift(1, lang('menu_geocolonias'), 'admin/geocolonias');
	}

	public function index()
	{
		if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
		{
			redirect('auth/login', 'refresh');
		}
		else
		{	
			if ($_POST) { 

				if ($_POST['dpto_cod']) 
				{
					$arraywhere['dpto_cod'] 		= $_POST['dpto_cod'];
					$arraywherebusq['dpto_cod like '] 		= '%'.$_POST['dpto_cod'].'%';
				}
				if ($_POST['dist_cod']) 
				{
					$arraywhere['dist_cod'] 		= $_POST['dist_cod'];
					$arraywherebusq['dist_cod like '] 		= '%'.$_POST['dist_cod'].'%';
				}
				if ($_POST['col_cod']) 
				{
					if (is_numeric($_POST['col_cod'])) {
						$arraywhere['col_cod'] 			= $_POST['col_cod'];
						$arraywherebusq['col_cod'] 			= $_POST['col_cod'];
					}
					
				}
				if ($_POST['id_codgeo']) 
				{
					$arraywhere['id_codgeo'] 		= $_POST['id_codgeo'];
					$arraywherebusq['id_codgeo like '] 		= '%'.$_POST['id_codgeo'].'%';
				}
				if ($_POST['col_desc']) 
				{
					$arraywhere['col_desc'] 		= $_POST['col_desc'];
					$arraywherebusq['lower(col_desc) like '] 		= '%'.strtolower($_POST['col_desc']).'%';
				}

				$_SESSION['arraywhere_geocolonia'] = $arraywhere;
				$_SESSION['arraywhere_geocolonia_busqueda'] = $arraywherebusq;

				redirect('man_espacial/geocolonias/geocolonias/index');				
			}

			// ----- Paginacion Generica 
			$mi_paginacion = $this->ion_auth->paginacion_generica(
				12, 						// resultados por por_pagina, 
				5, 							// segmento uri a leer, 
				5, 							// cantidad_enlaces,
				base_url(). 'man_espacial/geocolonias/geocolonias/index/',  // url completa de la pagina paginada
				'geocolonias',		// scheme y nombre de la tabla, para la consulta
				$_SESSION['arraywhere_geocolonia_busqueda']
				);

			$this->data['pagination'] 		= $mi_paginacion['pagination'];

			$this->data['geocolonias']	  	= $this->ion_auth_model->segmentador_paginas(
 				$mi_paginacion['per_page'], 	// resultados por pagina
 				5,								// segmento uri a leer
 				'geocolonias',					// el nombre de la tabla a consultar $nombre_tabla
 				$_SESSION['arraywhere_geocolonia_busqueda']
 				)->result();
			// ----- Fin paginacion

			/* Breadcrumbs */
			$this->data['breadcrumb'] = $this->breadcrumbs->show();

			/* Load Template */
            $this->template->admin_render('man_espacial/geocolonias/index', $this->data);
		}
	}


	public function create()
	{
		if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
		{
			redirect('auth', 'refresh');
		}

		/* Breadcrumbs */
		$this->breadcrumbs->unshift(2, lang('menu_geocolonias'), 'geocolonias/create');
		$this->data['breadcrumb'] = $this->breadcrumbs->show();

		/* Validate form input */
		$this->form_validation->set_rules('dpto_cod', '<b>Departamento</b>' , 'required');
		$this->form_validation->set_rules('dist_cod', '<b>Distrito</b>' , 'required');
		$this->form_validation->set_rules('col_cod', '<b>Colonia</b>' , 'required|is_numeric|max_length[3]');
		$this->form_validation->set_rules('col_desc','<b>Descripción Colonia</b>', 'required');

		if ($this->form_validation->run() == TRUE)
		{
			$arraycampos = array('dpto_cod' 	=> $_POST['dpto_cod'],
								 'dist_cod' 	=> $_POST['dist_cod'],
								 'id_codgeo' 	=> $_POST['id_codgeo'],
								 'col_cod' 		=> $_POST['col_cod'],
								 'col_desc' 	=> strtoupper($_POST['col_desc']),
								);

			$new_geocolonia_id = $this->geocolonias_model->create_geocolonia($arraycampos);
			if ($new_geocolonia_id)
			{
				$this->session->set_flashdata('message', $this->ion_auth->messages());

				redirect('man_espacial/geocolonias/geocolonias');
			}
		}
		else
		{
			$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

			$this->data['dpto_cod'] = array(
				'name'  => 'dpto_cod',
				'id'    => 'dpto_cod',
				'type'  => 'text',
				'class' => 'form-control',
				'value' => $this->form_validation->set_value('dpto_cod')
				);
			$this->data['dist_cod'] = array(
				'name'  => 'dist_cod',
				'id'    => 'dist_cod',
				'type'  => 'text',
				'class' => 'form-control',
				'value' => $this->form_validation->set_value('dist_cod')
				);
			$this->data['col_cod'] = array(
				'name'  => 'col_cod',
				'id'    => 'col_cod',
				'type'  => 'text',
				'class' => 'form-control',
				'value' => $this->form_validation->set_value('col_cod'),
				'maxlength' => 3
				);
			$this->data['id_codgeo'] = array(
				'name'  => 'id_codgeo',
				'id'    => 'id_codgeo',
				'type'  => 'text',
				'class' => 'form-control',
				'value' => $this->form_validation->set_value('id_codgeo'),
				'readonly' => true,
				);
			$this->data['col_desc'] = array(
				'name'  => 'col_desc',
				'id'    => 'col_desc',
				'type'  => 'text',
				'class' => 'form-control',
				'value' => $this->form_validation->set_value('col_desc'),
				'maxlength' => 100
				);

			$dptos[''] = 'Seleccione el departamento';
			$departamentos = $this->geocolonias_model->dropdown_data('departamentos')->result_array();
			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($departamentos as $dpto) {
				$dptos[$dpto['dpto']] = $dpto['dpto'].' - '.$dpto['dpto_desc'];
			}
			$this->data['departamentos'] = $dptos;
			//$this->data['departamentos_sel'] = $colonia->dpto_cod;

			$distritos = $this->geocolonias_model->dropdown_data('distritos')->result_array();
			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($distritos as $dist) {
				$dists[$dist['distrito']] = $dist['distrito'].' - '.$dist['dist_desc'];
			}
			$this->data['distritos'] = $dists;
			//$this->data['distritos_sel'] = $colonia->dist_cod;

			/* Load Template */
			$this->template->admin_render('man_espacial/geocolonias/create', $this->data);
		}
	}

	public function trae_distritos()
	{
		$dpto 	   = $_POST['dpto_cod'];

		$distritos = $this->geocolonias_model->dropdown_data('distritos',array('dpto' => $dpto), 'distrito')->result();

		echo '<option value="">Seleccione el distrito</option>';
		foreach ($distritos as $value) {
			echo '<option value="' . $value->distrito . '">' . $value->distrito . ' - ' . $value->dist_desc . '</option>';
		}

		//echo json_encode($distritos);
	}


	public function delete($gid)
	{
		$delete  = $this->geocolonias_model->eliminar_geocolonia($gid);
		
		redirect('man_espacial/geocolonias/geocolonias/index');
	}


	public function edit($gid)
	{

		if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin() OR ! $gid OR empty($gid))
		{
			redirect('auth', 'refresh');
		}

		/* Breadcrumbs */
		$this->breadcrumbs->unshift(2, lang('menu_geocolonias_edit'), 'geocolonias/edit');
		$this->data['breadcrumb'] = $this->breadcrumbs->show();



        /* Variables *///Trae de la base de datos la fila seleccionada
        $geocolonia = $this->geocolonias_model->view($gid)->row();

        /* Validate form input */
        $this->form_validation->set_rules('col_cod', $this->lang->line('edit_geocolonia_validation_name_label'), 'required|is_numeric|max_length[3]');
        
        $this->form_validation->set_rules('col_desc', $this->lang->line('edit_geocolonia_validation_name_label'), 'required');

        //Se produce cuando el usuario da click en el submit
        if (isset($_POST) && ! empty($_POST))
        {
        	if ($this->form_validation->run() == TRUE)
        	{

        		$arraycampos = array('dpto_cod' 	=> $_POST['dpto_cod'],
        							 'dist_cod' 	=> $_POST['dist_cod'],
        							 'col_cod' 		=> $_POST['col_cod'],
        							 'id_codgeo'	=> $_POST['id_codgeo'],
        							 'col_desc' 	=> strtoupper($_POST['col_desc'])
        							);
        		$geocolonia_update = $this->geocolonias_model->update_geocolonia($gid,$arraycampos);

        		if ($geocolonia_update)
        		{
					//una prueba de que trae los valores es reemplazando $this->lang->line('edit_geocolonia_saved') por $_POST('id') por ejemplo
        			$this->session->set_flashdata('message', $this->lang->line('geocolonia_update_successful'));
					redirect('man_espacial/geocolonias/geocolonias/edit/'.$gid.'/'.$_POST['departamento'].'/'.$_POST['dist'].'/'.$_POST['geocolonia_col_cod'].'/'); //VER OTRA MANERA DE ACTUALIZAR LA PAGINA, YA QUE AL REFRESCAR SOLO VUELVE A TOMAR LOS VALORES DE DPTO, DISTRITO Y COLONIA
				}
				else
				{
					$this->session->set_flashdata('message', $this->ion_auth->errors());
				}

				//aquí se designa a que pantalla irá al finalizar independientemente de que el proceso de actualización haya sido satisfactorio
				//redirect('man_espacial/geocolonias/geocolonias', 'refresh'); 
			}
		}

		$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
		$this->data['geocolonia']   = $geocolonia;

		//$readonly = $this->config->item('admin_group', 'ion_auth') === $geocolonia->col_desc ? 'readonly' : '';
		
		//creando campos
		$this->data['col_cod'] = array(
			'type'     => 'text',
			'name'     => 'col_cod',
			'id'       => 'col_cod',
			'value'    => $this->form_validation->set_value('col_cod', $geocolonia->col_cod),
			'data-src' => $geocolonia->col_cod,
			'class'    => 'form-control',
			'maxlength'    => 3
			);
		$this->data['id_codgeo'] = array(
			'type'     => 'text',
			'name'     => 'id_codgeo',
			'id'       => 'id_codgeo',
			'value'    => $this->form_validation->set_value('id_codgeo', $geocolonia->id_codgeo),
			'data-src' => $geocolonia->id_codgeo,
			'class'    => 'form-control',
			'readonly' => TRUE
			);
		$this->data['col_desc'] = array(
			'type'     => 'text',
			'name'     => 'col_desc',
			'id'       => 'col_desc',
			'value'    => $this->form_validation->set_value('col_desc', $geocolonia->col_desc),
			'data-src' => $geocolonia->col_desc,
			'class'    => 'form-control'
			);

		$dptos[''] = 'Seleccione el departamento';
		$dpto = $this->geocolonias_model->dropdown_data('departamentos')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($dpto as $dp) {
			$dptos[$dp['dpto']] = $dp['dpto'] . ' - ' . $dp['dpto_desc'];
		}
		$this->data['dpto'] = $dptos;
		$this->data['dpto_sel'] = $geocolonia->dpto_cod;

		$distritos = $this->geocolonias_model->dropdown_data('distritos',array('dpto' => $geocolonia->dpto_cod, 'distrito' => $geocolonia->dist_cod), 'distrito')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($distritos as $dist) {
			$dists[$dist['distrito']] = $dist['distrito'].' - '.$dist['dist_desc'];
		}
		if (isset($dists)) {
			$this->data['distritos'] = $dists;
		}else{
			$this->data['distritos'] = NULL;
		}
		$this->data['distritos_sel'] = $geocolonia->dist_cod;
		
		/* Load Template */
		$this->template->admin_render('man_espacial/geocolonias/edit', $this->data);
	}
}