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

class Expedientes extends Admin_Controller {

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

		$this->load->model('expedientes/expedientes_model');
		$this->lang->load('expedientes/expedientes_lang');

		/* Titulo de la pagina :: Common */
		$this->page_title->push(lang('menu_expedientes'));
		$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'] != 'EXPEDIENTES') {

			$_SESSION['arraywhere_expedientes'] 		 = NULL;
			$_SESSION['arraywhere_expedientes_busqueda'] = NULL;
			$_SESSION['id_modulo'] = 'EXPEDIENTES';
		}
		
		/* Breadcrumbs :: Common */
		$this->breadcrumbs->unshift(1, lang('menu_expedientes'), 'expedientes/expedientes');
	}

	public function index()
	{
		if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
		{
			redirect('auth/login', 'refresh');
		}
		else
		{	
			if ($_POST) { 
				
				if ($_POST['expe_id_expediente']) 
				{
					$arraywhere['expe_id_expediente'] 					= $_POST['expe_id_expediente'];
					$arraywherebusq['expe_id_expediente like '] 		= '%'.$_POST['expe_id_expediente'].'%';
				}

				if ($_POST['expe_gestion']) 
				{
					if (is_numeric($_POST['expe_gestion'])) {
						$arraywhere['expe_gestion'] 					= $_POST['expe_gestion'];
						$arraywherebusq['expe_gestion'] 				= $_POST['expe_gestion'];
					}
				}

				if ($_POST['depe_descripcion']) 
				{
					$arraywhere['depe_descripcion'] 					= $_POST['depe_descripcion'];
					$arraywherebusq['lower(depe_descripcion) like '] 	= '%'.strtolower($_POST['depe_descripcion']).'%';
				}

				if ($_POST['des_tipo_ref']) 
				{
					$arraywhere['des_tipo_ref'] 					= $_POST['des_tipo_ref'];
					$arraywherebusq['lower(des_tipo_ref) like '] 	= '%'.strtolower($_POST['des_tipo_ref']).'%';
				}

				if ($_POST['expe_proyecto']) 
				{
					$arraywhere['expe_proyecto'] 						= $_POST['expe_proyecto'];
					$arraywherebusq['lower(expe_proyecto) like '] 		= '%'.strtolower($_POST['expe_proyecto']).'%';
				}

				if ($_POST['expe_proponente']) 
				{
					$arraywhere['expe_proponente'] 						= $_POST['expe_proponente'];
					$arraywherebusq['lower(expe_proponente) like ']		= '%'.strtolower($_POST['expe_proponente']).'%';
				}

				if ($_POST['expe_dpto_desc']) 
				{
					$arraywhere['expe_dpto_desc'] 						= $_POST['expe_dpto_desc'];
					$arraywherebusq['lower(expe_dpto_desc) like ']		= '%'.strtolower($_POST['expe_dpto_desc']).'%';
				}

				if ($_POST['expe_dist_desc']) 
				{
					$arraywhere['expe_dist_desc'] 						= $_POST['expe_dist_desc'];
					$arraywherebusq['lower(expe_dist_desc) like ']		= '%'.strtolower($_POST['expe_dist_desc']).'%';
				}

				if ($_POST['expe_consultor_nom']) 
				{
					$arraywhere['expe_consultor_nom'] 					= $_POST['expe_consultor_nom'];
					$arraywherebusq['lower(expe_consultor_nom) like ']	= '%'.strtolower($_POST['expe_consultor_nom']).'%';
				}

				if ($_POST['expe_entrada']) 
				{
					$arraywhere['expe_entrada'] 						= $_POST['expe_entrada'];
					$arraywherebusq['expe_entrada']						= $_POST['expe_entrada'];
				}

				if ($_POST['expe_salida']) 
				{
					$arraywhere['expe_salida'] 							= $_POST['expe_salida'];
					$arraywherebusq['expe_salida']						= $_POST['expe_salida'];
				}

				if ($_POST['expe_secuencia']) 
				{
					$arraywhere['expe_secuencia'] 						= $_POST['expe_secuencia'];
					$arraywherebusq['expe_secuencia']					= $_POST['expe_secuencia'];
				}

				$_SESSION['arraywhere_expedientes'] = $arraywhere;
				$_SESSION['arraywhere_expedientes_busqueda'] = $arraywherebusq;

				redirect('expedientes/expedientes/index/');				
			}

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

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

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

			
			foreach ($this->data['expedientes'] as $key => $value) {
				$i = 0;
				foreach ($value as $k => $val) {
					$i = $i + 1;
					if ($i == 1) {

						$cant_pol = $this->expedientes_model->f_existe_grafico_expe_id($value->expe_id);
						$exp['existe_poligono'] = $cant_pol;


						if (grupo_usuario(17) or grupo_usuario(27)) {
							$exp['grupo_usuario'] = 'C';	
						}else{
							$exp['grupo_usuario'] = 'N';
						}
					}
					$exp[$k] = $val;
				}
				$exps[] = (object)$exp;
			}

			if (isset($exps)) {
				$this->data['expedientes'] = $exps;
			}else{
				$this->data['expedientes'] = NULL;
			}
			
			//emite un mensaje si es que se eliminó un expediente
			if (isset($_SESSION['last_exp_delete'])) {
				$this->session->set_flashdata('message', $_SESSION['last_exp_delete']);
				unset($_SESSION['last_exp_delete']);
			}

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

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

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

	public function reset_busqueda()
	{
		$_SESSION['arraywhere_expedientes'] 			= NULL;
		$_SESSION['arraywhere_expedientes_busqueda'] 	= NULL;
		
		redirect('expedientes/expedientes/index/');				
	}

	public function ver_exp($expe_id)
	{
		if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
		{
			redirect('auth/login', 'refresh');
		}
		else
		{	
			/* Breadcrumbs */
	        $this->breadcrumbs->unshift(2, 'Información Expediente', 'admin/groups/profile');
	        $this->data['breadcrumb'] = $this->breadcrumbs->show();

			$this->data['expe_info']  = $this->expedientes_model->view('exp', array('expe_id' => $expe_id))->result();
	        
			/* Load Template */
            $this->template->admin_render('expedientes/ver_expediente', $this->data);
		}
	}

	public function expe_mantenimiento($expe_id)
	{
		if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
		{
			redirect('auth/login', 'refresh');
		}
		else
		{	
			/* Breadcrumbs */
	        $this->breadcrumbs->unshift(2, 'Mantenimiento', 'expedientes/expedientes');
	        $this->data['breadcrumb'] = $this->breadcrumbs->show();

	        $exp_datos = $this->expedientes_model->view('exp', array('expe_id' => $expe_id))->row();

	        $expe_id_expediente = $exp_datos->expe_id_expediente;
	        $expe_gestion		= $exp_datos->expe_gestion;



			$expe_info  = $this->expedientes_model->view('exp', array('expe_id_expediente' => $expe_id_expediente,'expe_gestion' => $expe_gestion))->result_array();

			$expe_info[0]["expe_tipo_ref_desc"] = $this->expedientes_model->dropdown_data('conceptos', array('tipoconcepto' => 'TIPO_REF', 'concepto' => $expe_info[0]["expe_tipo_ref"]))->row()->nombre;

			$expe_info[0]["expe_estado_desc"] = $this->expedientes_model->dropdown_data('conceptos', array('tipoconcepto' => 'EXPE_ESTADO', 'concepto' => $expe_info[0]["expe_estado"]))->row()->nombre;


			/************* CANTIDAD DATOS GRAFICOS ****************/
			$datos_graficos[0]['SEAM_POLIGONO']		= $this->expedientes_model->contador_registros('SEAM_POLIGONO', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_UACTUAL']		= $this->expedientes_model->contador_registros('SEAM_UACTUAL', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_UALTER']		= $this->expedientes_model->contador_registros('SEAM_UALTER', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_U86']			= $this->expedientes_model->contador_registros('SEAM_U86', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_U04']			= $this->expedientes_model->contador_registros('SEAM_U04', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_TSUELO']		= $this->expedientes_model->contador_registros('SEAM_TSUELO', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_FINCAS']		= $this->expedientes_model->contador_registros('SEAM_FINCAS', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_CAP_SUELO']	= $this->expedientes_model->contador_registros('SEAM_CAP_SUELO', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_CLA_ECO']		= $this->expedientes_model->contador_registros('SEAM_CLA_ECO', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_COMP_DEF']		= $this->expedientes_model->contador_registros('SEAM_COMP_DEF', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_DEF_BOS']		= $this->expedientes_model->contador_registros('SEAM_DEF_BOS', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			$datos_graficos[0]['SEAM_PROP_CERT']	= $this->expedientes_model->contador_registros('SEAM_PROP_CERT', array('exp' => $expe_id_expediente, 'gest' => $expe_gestion));
			/************* FIN CANTIDAD DATOS GRAFICOS ****************/

			$this->data['expe_info'] 		= $expe_info;
 
			$this->data['datos_graficos'] 	= $datos_graficos;

			$this->data['expe_id_expediente'] = array(
				'type'     => 'hidden',
				'name'     => 'expe_id_expediente',
				'id'       => 'expe_id_expediente',
				'value'    => $expe_id_expediente
			);

			$this->data['expe_gestion'] = array(
				'type'     => 'hidden',
				'name'     => 'expe_gestion',
				'id'       => 'expe_gestion',
				'value'    => $expe_gestion
			);

			$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
	        
			/* Load Template */
            $this->template->admin_render('expedientes/Mantenimiento', $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('expedientes_create'), 'geocolonias/create');
		$this->data['breadcrumb'] = $this->breadcrumbs->show();

		/* Validate form input */
		$this->form_validation->set_rules('expe_id_expediente', '<b>Id Expediente</b>' , 'required');
		$this->form_validation->set_rules('expe_gestion', 		'<b>Gestion</b>' , 		 'required');
		$this->form_validation->set_rules('expe_id_dependencia','<b>Id Dependencia</b>' ,'required');
		$this->form_validation->set_rules('expe_tipo_ref', 		'<b>Tipo Ref.</b>' , 	 'required');
		//$this->form_validation->set_rules('expe_id_geomatica', 	'<b>ID Geomática</b>' ,  'required');
		
		if ($this->form_validation->run() == TRUE)
		{
			//show_error(2);
        	if ($_POST['expe_id_expediente']){
        		$arraycampos['expe_id_expediente'] 		= $_POST['expe_id_expediente'];
        	}

			if ($_POST['expe_gestion']){
				$arraycampos['expe_gestion'] 			= $_POST['expe_gestion'];
			}

			if ($_POST['expe_tipo_ref'] || $_POST['expe_tipo_ref'] == 0){

				$arraycampos['expe_tipo_ref'] 			= $_POST['expe_tipo_ref'];
			}

			if ($_POST['expe_id_dependencia']){

				$arraycampos['expe_id_dependencia'] 	= $_POST['expe_id_dependencia'];
			}


			if ($_POST['expe_id_expediente_ref']){
				$arraycampos['expe_id_expediente_ref'] 	= $_POST['expe_id_expediente_ref'];
				$cnt = $this->expedientes_model->contador_registros ('exp', array('expe_id_expediente' => $_POST['expe_id_expediente'], 'expe_gestion' => $_POST['expe_gestion'], 'expe_id_dependencia' => $_POST['expe_id_dependencia']));
				if ($cnt>0) {
					$sq = $this->expedientes_model->valor_maximo('exp', 'expe_secuencia', array('expe_id_expediente' => $_POST['expe_id_expediente'], 'expe_gestion' => $_POST['expe_gestion'], 'expe_id_dependencia' => $_POST['expe_id_dependencia']));
					if ($sq>=0) {
						$arraycampos['expe_secuencia'] 		= $sq+1;
					}else{
						$arraycampos['expe_secuencia'] 		= $sq+1;
					}
				}else{
					$arraycampos['expe_secuencia'] 		= 0;
				}
			}else{
				$arraycampos['expe_secuencia'] 		= 0;
			}


			if ($_POST['expe_id_ref']){
				$arraycampos['expe_id_ref'] 	= $_POST['expe_id_ref'];
			}

			if ($_POST['expe_doc_proponente']){
				$arraycampos['expe_doc_proponente'] 	= $_POST['expe_doc_proponente'];
			}

			if ($_POST['expe_proponente']){
				$arraycampos['expe_proponente'] 		= strtoupper($_POST['expe_proponente']);
			}

			$sq = $this->expedientes_model->obtener_nextval('seam.exp_expe_id_geomatica');
			
			$arraycampos['expe_id_geomatica'] 			= $sq;
			
			if ($_POST['expe_tipo_proyecto']){
				$arraycampos['expe_tipo_proyecto'] 		= $_POST['expe_tipo_proyecto'];
			}
			if ($_POST['expe_proyecto']){
				$arraycampos['expe_proyecto'] 			= strtoupper($_POST['expe_proyecto']);
			}
			if ($_POST['expe_id_departamento']){
				$arraycampos['expe_id_departamento'] 	= $_POST['expe_id_departamento'];
			}
			if ($_POST['expe_id_distrito']){
				$arraycampos['expe_id_distrito'] 		= $_POST['expe_id_distrito'];
			}
			if ($_POST['expe_id_consultor']){
				$arraycampos['expe_id_consultor'] 		= strtoupper($_POST['expe_id_consultor']);
			}
			if ($_POST['expe_consultor_nom']){
				$arraycampos['expe_consultor_nom'] 		= strtoupper($_POST['expe_consultor_nom']);
			}
			if ($_POST['expe_entrada']){
				$arraycampos['expe_entrada'] 			= $_POST['expe_entrada'];
			}			

			$arraycampos['expe_usureg'] 				= $this->session->userdata('username');

			$arraycampos['expe_usuario'] 				= $this->session->userdata('username');
			
			$arraycampos['expe_fechareg'] 				= date("Y").'-'.date("m").'-'.date("d");
			
			if ($_POST['expe_observacion']){
				$arraycampos['expe_observacion'] 		= strtoupper($_POST['expe_observacion']);
			}
			if ($_POST['expe_tecnico']){
				$arraycampos['expe_tecnico'] 			= $_POST['expe_tecnico'];
			}
			if ($_POST['expe_fproceso_geo']){
				$arraycampos['expe_fproceso_geo'] 		= $_POST['expe_fproceso_geo'];
			}
			if ($_POST['expe_nota']){
				$arraycampos['expe_nota'] 				= $_POST['expe_nota'];
			}
			if ($_POST['expe_director']){
				$arraycampos['expe_director'] 			= strtoupper($_POST['expe_director']);
			}
			if ($_POST['expe_salida']){
				$arraycampos['expe_salida'] 			= $_POST['expe_salida'];
			}
			if ($_POST['expe_provdg']){
				$arraycampos['expe_provdg'] 			= $_POST['expe_provdg'];
			}
			/*
			if ($_POST['expe_fecha_licencia']){
				$arraycampos['expe_fecha_licencia'] 	= $_POST['expe_fecha_licencia'];
			}			
			if ($_POST['expe_nro_licencia']){
				$arraycampos['expe_nro_licencia'] 		= $_POST['expe_nro_licencia'];
			}			
			if ($_POST['expe_usuario']){
				$arraycampos['expe_usuario'] 			= strtoupper($_POST['expe_usuario']);
			}
			if ($_POST['expe_nro_archivo']){
				$arraycampos['expe_nro_archivo'] 		= $_POST['expe_nro_archivo'];
			}			
			if ($_POST['expe_fecha_cierre']){
				$arraycampos['expe_fecha_cierre'] 		= $_POST['expe_fecha_cierre'];
			}
			*/
			if ($_POST['expe_bloqueo']){
				$arraycampos['expe_bloqueo'] 			= $_POST['expe_bloqueo'];
			}
			if ($_POST['expe_estado']){
				$arraycampos['expe_estado'] 			= $_POST['expe_estado'];
			}
			if ($_POST['expe_sup_legal']){
				$arraycampos['expe_sup_legal'] 			= $_POST['expe_sup_legal'];
			}


			$accion = 0;	
			if (isset($_POST['accion'])){
				$accion = intval($_POST['accion']);
			}else{
				$accion = 0;	
			}

			$expe_create = $this->expedientes_model->crear_expediente($arraycampos);

        	if ($expe_create)
        	{

				if($accion===1){ /// ACCION PARA OBSERVAR 						

        			$this->session->set_flashdata('message', '¡Expediente <b>'.$_POST['expe_id_expediente'].'</b>, Gestión <b>'.$_POST['expe_gestion'].'</b> creado exitósamente!');
					redirect('expedientes/mantenimiento/expe_mantenimiento/'.$expe_create);

				} else {

        			$this->session->set_flashdata('message', '¡Expediente <b>'.$_POST['expe_id_expediente'].'</b>, Gestión <b>'.$_POST['expe_gestion'].'</b> creado exitósamente!');
					redirect('expedientes/expedientes/edit_expe/'.$expe_create);
				}
			}
			else 
			{
				$this->session->set_flashdata('message', $this->ion_auth->errors());
			}
		}
		else
		{
			$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));

			$this->data['expe_id'] = array(
				'type'     => 'text',
				'name'     => 'expe_id',
				'id'       => 'expe_id',
				'value'    => $this->form_validation->set_value('expe_id'),
				'class'    => 'form-control',
				'maxlength'=> '10',
				'readonly' => TRUE
			);				
			$this->data['expe_id_expediente'] = array(
				'type'     => 'text',
				'name'     => 'expe_id_expediente',
				'id'       => 'expe_id_expediente',
				'value'    => $this->form_validation->set_value('expe_id_expediente'),
				'class'    => 'form-control',
				'maxlength'=> '10'
			);
			$this->data['expe_gestion'] = array(
				'type'     => 'number',
				'name'     => 'expe_gestion',
				'id'       => 'expe_gestion',
				'value'    => $this->form_validation->set_value('expe_gestion'),
				'class'    => 'form-control',
				'onkeyup'  => 'limit_dig(this.id,4)'
			);
			$this->data['expe_secuencia'] = array(
				'type'     => 'text',
				'name'     => 'expe_secuencia',
				'id'       => 'expe_secuencia',
				'value'    => $this->form_validation->set_value('expe_secuencia'),
				'class'    => 'form-control',
				'readonly' => TRUE
			);
			$this->data['expe_id_ref'] = array(
				'type'     => 'text',
				'name'     => 'expe_id_ref',
				'id'       => 'expe_id_ref',
				'value'    => $this->form_validation->set_value('expe_id_ref'),
				'class'    => 'form-control',
				'maxlength'=> '10',
				'readonly' => TRUE
			);	
			$this->data['expe_id_expediente_ref'] = array(
				'type'     => 'number',
				'name'     => 'expe_id_expediente_ref',
				'id'       => 'expe_id_expediente_ref',
				'value'    => $this->form_validation->set_value('expe_id_expediente_ref'),
				'class'    => 'form-control',
				'onkeyup'  => 'limit_dig(this.id,10)'
			);
			$this->data['expe_doc_proponente'] = array(
				'type'     => 'text',
				'name'     => 'expe_doc_proponente',
				'id'       => 'expe_doc_proponente',
				'value'    => $this->form_validation->set_value('expe_doc_proponente'),
				'class'    => 'form-control',
				'maxlength'=> '20'
			);
			$this->data['expe_proponente'] = array(
				'type'     => 'text',
				'name'     => 'expe_proponente',
				'id'       => 'expe_proponente',
				'value'    => $this->form_validation->set_value('expe_proponente'),
				'class'    => 'form-control',
				'maxlength'=> '100'
			);
			$this->data['expe_id_geomatica'] = array(
				'type'     => 'number',
				'name'     => 'expe_id_geomatica',
				'id'       => 'expe_id_geomatica',
				'value'    => $this->form_validation->set_value('expe_id_geomatica'),
				'class'    => 'form-control',
				'onkeyup'  => 'limit_dig(this.id,20)',
				'readonly' => TRUE
			);
			$this->data['expe_proyecto'] = array(
				'type'     => 'text',
				'name'     => 'expe_proyecto',
				'id'       => 'expe_proyecto',
				'rows'     => '1',
				'value'    => $this->form_validation->set_value('expe_proyecto'),
				'class'    => 'form-control',
				'maxlength'=> '255'
			);
			$this->data['expe_id_consultor'] = array(
				'type'     => 'text',
				'name'     => 'expe_id_consultor',
				'id'       => 'expe_id_consultor',
				'value'    => $this->form_validation->set_value('expe_id_consultor'),
				'class'    => 'form-control',
				'list'	   => 'expe_id_consultor_list',
				'maxlength'=> '10'
			);
			$this->data['expe_consultor_nom'] = array(
				'type'     => 'text',
				'name'     => 'expe_consultor_nom',
				'id'       => 'expe_consultor_nom',
				'value'    => $this->form_validation->set_value('expe_consultor_nom'),
				'class'    => 'form-control',
				'maxlength'=> '100'
			);
			$this->data['expe_entrada'] = array(
				'type'     => 'text',
				'name'     => 'expe_entrada',
				'id'       => 'expe_entrada',
				'value'    => $this->form_validation->set_value('expe_entrada'),
				'class'    => 'form-control'
			);
			$this->data['expe_usureg'] = array(
				'type'     => 'text',
				'name'     => 'expe_usureg',
				'id'       => 'expe_usureg',
				'value'    => $this->form_validation->set_value('expe_usureg'),
				'class'    => 'form-control',
				'readonly' => TRUE
			);
			$this->data['expe_usuario'] = array(
				'type'     => 'text',
				'name'     => 'expe_usuario',
				'id'       => 'expe_usuario',
				'value'    => $this->form_validation->set_value('expe_usuario'),
				'class'    => 'form-control',
				'readonly' => true
			);			
			$this->data['expe_fechareg'] = array(
				'type'     => 'text',
				'name'     => 'expe_fechareg',
				'id'       => 'expe_fechareg',
				'value'    => $this->form_validation->set_value('expe_fechareg'),
				'class'    => 'form-control',
				'readonly' => TRUE
			);
			$this->data['expe_observacion'] = array(
				'type'     => 'text',
				'name'     => 'expe_observacion',
				'id'       => 'expe_observacion', 
				'style'	   => 'height: 60px',
				'value'    => $this->form_validation->set_value('expe_observacion'),
				'class'    => 'form-control'
			);
			$this->data['expe_tecnico'] = array(
				'type'     => 'text',
				'name'     => 'expe_tecnico',
				'id'       => 'expe_tecnico',
				'value'    => $this->form_validation->set_value('expe_tecnico'),
				'class'    => 'form-control',
				'readonly' => TRUE
			);
			$this->data['expe_fproceso_geo'] = array(
				'type'     => 'text',
				'name'     => 'expe_fproceso_geo',
				'id'       => 'expe_fproceso_geo',
				'value'    => $this->form_validation->set_value('expe_fproceso_geo'),
				'class'    => 'form-control',
				'readonly' => TRUE
			);
			$this->data['expe_nota'] = array(
				'type'     => 'text',
				'name'     => 'expe_nota',
				'id'       => 'expe_nota',
				'value'    => $this->form_validation->set_value('expe_nota'),
				'class'    => 'form-control',
				'readonly' => TRUE
			);
			$this->data['expe_director'] = array(
				'type'     => 'text',
				'name'     => 'expe_director',
				'id'       => 'expe_director',
				'value'    => $this->form_validation->set_value('expe_director'),
				'class'    => 'form-control',
				'readonly' => true
			);
			$this->data['expe_salida'] = array(
				'type'     => 'text',
				'name'     => 'expe_salida',
				'id'       => 'expe_salida',
				'value'    => $this->form_validation->set_value('expe_salida'),
				'class'    => 'form-control',
				'readonly' => true
			);
			$this->data['expe_provdg'] = array(
				'type'     => 'text',
				'name'     => 'expe_provdg',
				'id'       => 'expe_provdg',
				'value'    => $this->form_validation->set_value('expe_provdg'),
				'class'    => 'form-control',
				'readonly' => true
			);
			$this->data['expe_sup_legal'] = array(
				'type'     => 'text',
				'name'     => 'expe_sup_legal',
				'id'       => 'expe_sup_legal',
				'value'    => $this->form_validation->set_value('expe_sup_legal'),
				'class'    => 'form-control',
				//'title'    => 'El formato de ser 0000,0000',
				//'pattern'  => '^[0-9]+([,][0-9]+)'

			);
			/*
			$this->data['expe_fecha_licencia'] = array(
				'type'     => 'text',
				'name'     => 'expe_fecha_licencia',
				'id'       => 'expe_fecha_licencia',
				'value'    => $this->form_validation->set_value('expe_fecha_licencia'),
				'class'    => 'form-control',
				'readonly' => true
			);
			$this->data['expe_nro_licencia'] = array(
				'type'     => 'text',
				'name'     => 'expe_nro_licencia',
				'id'       => 'expe_nro_licencia',
				'value'    => $this->form_validation->set_value('expe_nro_licencia'),
				'class'    => 'form-control',
				'readonly' => true
			);			
			$this->data['expe_usuario'] = array(
				'type'     => 'text',
				'name'     => 'expe_usuario',
				'id'       => 'expe_usuario',
				'value'    => $this->form_validation->set_value('expe_usuario'),
				'class'    => 'form-control',
				'readonly' => true
			);
			$this->data['expe_nro_archivo'] = array(
				'type'     => 'text',
				'name'     => 'expe_nro_archivo',
				'id'       => 'expe_nro_archivo',
				'value'    => $this->form_validation->set_value('expe_nro_archivo'),
				'class'    => 'form-control',
				'readonly' => true
			);			
			$this->data['expe_fecha_cierre'] = array(
				'type'     => 'text',
				'name'     => 'expe_fecha_cierre',
				'id'       => 'expe_fecha_cierre',
				'value'    => $this->form_validation->set_value('expe_fecha_cierre'),
				'class'    => 'form-control',
				'readonly' => true
			);
			*/
			$this->data['expe_estado'] = array(
				'type'     => 'text',
				'name'     => 'expe_estado',
				'id'       => 'expe_estado',
				'value'    => $this->form_validation->set_value('expe_estado'),
				'class'    => 'form-control',
				'readonly' => true
			);

			$dependencias[''] = 'Seleccione la dependencia';
			$dependencia = $this->expedientes_model->dropdown_data('dependencias')->result_array();
			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($dependencia as $dep) {
				$dependencias[$dep['depe_id']] = $dep['depe_codigo'].' - '.$dep['depe_nombre_abreviado'];
			}
			$this->data['expe_id_dependencia'] = $dependencias;
			
			$dptos[''] = 'Seleccione el departamento';
			$departamentos = $this->expedientes_model->dropdown_data('departamentos','','dpto_id_departamento')->result_array();

			$tecs[''] = 'Seleccione el técnico';
			$tecnico = $this->expedientes_model->dropdown_data('v_tecnicos')->result_array();
			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($tecnico as $tec) {
				$tecs[$tec['username']] = $tec['first_name'].' '.$tec['last_name'];
			}
			$this->data['expe_tecnico'] = $tecs;

			$dptos[''] = 'Seleccione el departamento';
			$departamentos = $this->expedientes_model->dropdown_data('departamentos','','dpto_id_departamento')->result_array();

			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($departamentos as $dpto) {
				$dptos[$dpto['dpto_id_departamento']] = $dpto['dpto_id_departamento'].' - '.$dpto['dpto_descripcion'];
			}
			$this->data['departamentos'] = $dptos;

			$tipoproyectos[''] = 'Tipo de proyecto';
			$tipoproyecto = $this->expedientes_model->dropdown_data('tipo_proyecto','','tpro_tipo_proy')->result_array();
			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($tipoproyecto as $tp) {
				$tipoproyectos[$tp['tpro_tipo_proy']] = $tp['tpro_tipo_proy'].' - '.$tp['tpro_nombre_tipo_proy'];
			}
			$this->data['tipoproyecto'] = $tipoproyectos;

			$consultor = $this->expedientes_model->dropdown_data('consultores','','cstr_codigo_ctca')->result_array();
			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($consultor as $cs) {
				$consultors[$cs['cstr_codigo_ctca']] = $cs['cstr_nombre_consultor'];
			}
			$this->data['consultor'] = $consultors;

			$tiporefs[''] = 'Tipo Ref.';
			$tiporef = $this->expedientes_model->dropdown_data('conceptos',array('tipoconcepto' => 'TIPO_REF'),'concepto')->result_array();
			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($tiporef as $tr) {
				$tiporefs[$tr['concepto']] = $tr['concepto'].' - '.$tr['nombre'];
			}
			$this->data['tipo_ref'] = $tiporefs;

			$bloqueos[''] = 'Bloqueo';
			$bloqueo = $this->expedientes_model->dropdown_data('conceptos',array('tipoconcepto' => 'EXPE_BLOQUEO'),'concepto')->result_array();
			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($bloqueo as $bl) {
				$bloqueos[$bl['concepto']] = $bl['concepto'].' - '.$bl['nombre'];
			}
			$this->data['expe_bloqueo'] = $bloqueos;
			
			/* Load Template */
			$this->template->admin_render('expedientes/create_expe', $this->data);
		}
	}

	public function edit_expe($expe_id)
	{

		if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin() OR ! $expe_id OR empty($expe_id))
		{
			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
        $expediente = $this->expedientes_model->view('exp', array('expe_id' => $expe_id))->row();

        $this->data['expe_id'] = $expe_id;

        /* Validate form input */
        $this->form_validation->set_rules('expe_id_expediente', '<b>Id Expediente</b>' , 'required');
		$this->form_validation->set_rules('expe_gestion', 		'<b>Gestion</b>' , 		 'required');
		$this->form_validation->set_rules('expe_id_dependencia', '<b>Id Dependencia</b>' ,'required');
		$this->form_validation->set_rules('expe_tipo_ref', 		'<b>Tipo Ref.</b>' , 	 'required');
		//$this->form_validation->set_rules('expe_id_geomatica', 	'<b>ID Geomática</b>' ,  'required');

		//Se produce cuando el usuario da click en el submit
        if (isset($_POST) && ! empty($_POST))
        {
        	if ($this->form_validation->run() == TRUE)
        	{
				if ($_POST['expe_id']){
					$arraycampos['expe_id'] 			= $_POST['expe_id'];
				}

        		if ($_POST['expe_id_expediente']){
	        		$arraycampos['expe_id_expediente'] 		= $_POST['expe_id_expediente'];
	        	}

				if ($_POST['expe_gestion']){
					$arraycampos['expe_gestion'] 			= $_POST['expe_gestion'];
				}

				if ($_POST['expe_tipo_ref']){
					$arraycampos['expe_tipo_ref'] 			= $_POST['expe_tipo_ref'];
				}

				if ($_POST['expe_id_expediente_ref']){
					$arraycampos['expe_id_expediente_ref'] 	= $_POST['expe_id_expediente_ref'];
				}else{
					$arraycampos['expe_id_expediente_ref'] 	= NULL;
				}

				if ($_POST['expe_id_ref']){
					$arraycampos['expe_id_ref'] 	= $_POST['expe_id_ref'];
				}

				if ($_POST['expe_doc_proponente']){
					$arraycampos['expe_doc_proponente'] 	= $_POST['expe_doc_proponente'];
				}else{
					$arraycampos['expe_doc_proponente'] 	= NULL;
				}

				if ($_POST['expe_proponente']){
					$arraycampos['expe_proponente'] 		= strtoupper($_POST['expe_proponente']);
				}else{
					$arraycampos['expe_proponente'] 		= NULL;
				}
				
				if ($_POST['expe_id_geomatica']){
					$arraycampos['expe_id_geomatica'] 		= $_POST['expe_id_geomatica'];
				}
				
				if ($_POST['expe_tipo_proyecto']){
					$arraycampos['expe_tipo_proyecto'] 		= $_POST['expe_tipo_proyecto'];
				}
				
				if ($_POST['expe_proyecto']){
					$arraycampos['expe_proyecto'] 			= strtoupper($_POST['expe_proyecto']);
				}else{
					$arraycampos['expe_proyecto'] 			= NULL;
				}
				
				if ($_POST['expe_id_departamento']){
					$arraycampos['expe_id_departamento'] 	= $_POST['expe_id_departamento'];
				}
				
				if ($_POST['expe_id_distrito']){
					$arraycampos['expe_id_distrito'] 		= $_POST['expe_id_distrito'];
				}
				
				if ($_POST['expe_id_consultor']){
					$arraycampos['expe_id_consultor'] 		= strtoupper($_POST['expe_id_consultor']);
				}else{
					$arraycampos['expe_id_consultor'] 		= NULL;
				}
				
				if ($_POST['expe_consultor_nom']){
					$arraycampos['expe_consultor_nom'] 		= strtoupper($_POST['expe_consultor_nom']);
				}else{
					$arraycampos['expe_consultor_nom'] 		= NULL;
				}
				
				if ($_POST['expe_entrada']){
					$arraycampos['expe_entrada'] 			= $_POST['expe_entrada'];
				}

				if ($_POST['expe_observacion']){
					$arraycampos['expe_observacion'] 		= strtoupper($_POST['expe_observacion']);
				}else{
					$arraycampos['expe_observacion'] 		= NULL;
				}
				
				if ($_POST['expe_tecnico']){
					$arraycampos['expe_tecnico'] 			= $_POST['expe_tecnico'];
				}
				
				if ($_POST['expe_fproceso_geo']){
					$arraycampos['expe_fproceso_geo'] 		= $_POST['expe_fproceso_geo'];
				}
				
				if ($_POST['expe_nota']){
					$arraycampos['expe_nota'] 				= $_POST['expe_nota'];
				}
				
				if ($_POST['expe_director']){
					$arraycampos['expe_director'] 			= $_POST['expe_director'];
				}
				
				if ($_POST['expe_salida']){
					$arraycampos['expe_salida'] 			= $_POST['expe_salida'];
				}
				
				if ($_POST['expe_provdg']){
					$arraycampos['expe_provdg'] 			= $_POST['expe_provdg'];
				}
				else{
					$arraycampos['expe_provdg'] 			= NULL;
				}
				if ($_POST['expe_usureg']){
					$arraycampos['expe_usureg'] 			= strtoupper($_POST['expe_usureg']);
				}
				if ($_POST['expe_usuario']){
					$arraycampos['expe_usuario'] 			= strtoupper($_POST['expe_usuario']);
				}

				/*
				if ($_POST['expe_fecha_licencia']){
					$arraycampos['expe_fecha_licencia'] 	= $_POST['expe_fecha_licencia'];
				}
				
				if ($_POST['expe_nro_licencia']){
					$arraycampos['expe_nro_licencia'] 		= $_POST['expe_nro_licencia'];
				}
				
				if ($_POST['expe_nro_archivo']){
					$arraycampos['expe_nro_archivo'] 		= $_POST['expe_nro_archivo'];
				}
				
				if ($_POST['expe_fecha_cierre']){
					$arraycampos['expe_fecha_cierre'] 		= $_POST['expe_fecha_cierre'];
				}

				*/
				
				if ($_POST['expe_bloqueo']){
					$arraycampos['expe_bloqueo'] 			= $_POST['expe_bloqueo'];
				}
				/*
				if ($_POST['expe_estado']){
					$arraycampos['expe_estado'] 			= $_POST['expe_estado'];
				}
				*/

				if ($_POST['expe_id_dependencia']){
					$arraycampos['expe_id_dependencia'] 	= $_POST['expe_id_dependencia'];
				}

				if ($_POST['expe_sup_legal']){
					$arraycampos['expe_sup_legal'] 			= $_POST['expe_sup_legal'];
				}

				$accion = 0;	
				if (isset($_POST['accion'])){
					$accion = intval($_POST['accion']);
				}else{
					$accion = 0;	
				}
				


				$unique_exp = $this->expedientes_model->view('exp',array('expe_id_expediente' => $_POST['expe_id_expediente'],
																		'expe_tipo_ref' 	 => $_POST['expe_tipo_ref'],
																		'expe_gestion' 		 => $_POST['expe_gestion'],
																		)
															)->num_rows();


				/*if ($unique_exp > 0) {
					$this->session->set_flashdata('message', 'Ya existe un expediente con el mismo expediente, tipo ref., e ID Geomática');
					redirect('expedientes/expedientes/edit_expe/'.$expe_id);
				}*/

						//echo $accion;
						//show_error(1);	


				$actualizar_expediente = $this->expedientes_model->actualizar_expediente($expe_id,$arraycampos);

				///////////////////////////////////////////////////////////
				///////////////////// ACCIONES POST ///////////////////////
				///////////////////////////////////////////////////////////

				if($accion===2){ /// ACCION PARA OBSERVAR 						

					$resul  = $this->expedientes_model->actualizar_expediente($expe_id, array('expe_estado' => 'O'));

				}else{
					if($accion===3){ /// ACCION PARA HABILITAR

						$resul  = $this->expedientes_model->actualizar_expediente($expe_id, array('expe_estado' => 'A'));

					}else{
						if($accion===4){ /// ACCION PARA DAR SALIDA

							$i_exp = $this->expedientes_model->obtener_valor_campo('exp', 'expe_id_expediente' , array('expe_id' => $expe_id ));

							$i_gest = $this->expedientes_model->obtener_valor_campo('exp', 'expe_gestion' , array('expe_id' => $expe_id ));
							
							$i_user = $this->session->userdata('username');
							//echo $i_user;
							//show_error(1);

							if (!is_null($i_exp) AND $i_gest > 0) {
								if (grupo_usuario(18)) {

									//if ($expe_provdg == NULL) {
									if (is_null($expe_provdg)) {
										$provdg = 0;
									}else{
										$provdg = $expe_provdg;
									}

									if ($provdg == 0) {
										$i_max = $this->expedientes_model->campo_valor_maximo('exp', 'expe_provdg' , array('expe_director' => $i_user ));

										$i_max = $i_max+1;

										$str 	= date_default_timezone_get();
										$fecha  = date("d/m/Y", strtotime($str));

										$salida = $this->expedientes_model->actualizar_expediente($expe_id, array(
											'expe_provdg'   => $i_max, 
											'expe_director' => $this->session->userdata('username'),
											'expe_salida'   => $fecha,
											'expe_estado'   => 'P'));

										if ($salida) {
											$this->session->set_flashdata('message', '¡Se DIÓ SALIDA exitósamente!');
											redirect('expedientes/expedientes/edit_expe/'.$expe_id);
										}else{
											$this->session->set_flashdata('message', '¡No se pudo DAR SALIDA!');
											redirect('expedientes/expedientes/edit_expe/'.$expe_id);
										}
									}else{
										$this->session->set_flashdata('message', '¡Campo PROV. DG sin dato!');
										redirect('expedientes/expedientes/edit_expe/'.$expe_id);
									}
								}else{
									$this->session->set_flashdata('message', 'NO TIENE PRIVILEGIOS PARA ESTA ACCIÓN');
									redirect('expedientes/expedientes/edit_expe/'.$expe_id);
								}
							}else{
								redirect('expedientes/expedientes/edit_expe/'.$expe_id);
							}

						}else{
							
						}
					}
				}
				
        		//if ($resul) 
        		if ($actualizar_expediente) 
        		{
					//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('expedientes_update_successful'));
					redirect('expedientes/expedientes/edit_expe/'.$expe_id);
				}
				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['expe_id'] = array(
			'type'     => 'text',
			'name'     => 'expe_id',
			'id'       => 'expe_id',
			'value'    => $this->form_validation->set_value('expe_id', $expediente->expe_id),
			'class'    => 'form-control',
			'maxlength'=> '10',
			'readonly' => TRUE
		);			
		$this->data['expe_id_expediente'] = array(
			'type'     => 'text',
			'name'     => 'expe_id_expediente',
			'id'       => 'expe_id_expediente',
			'value'    => $this->form_validation->set_value('expe_id_expediente', $expediente->expe_id_expediente),
			'class'    => 'form-control',
			'maxlength'=> '10'
		);
		$this->data['expe_gestion'] = array(
			'type'     => 'text',
			'name'     => 'expe_gestion',
			'id'       => 'expe_gestion',
			'value'    => $this->form_validation->set_value('expe_gestion', $expediente->expe_gestion),
			'class'    => 'form-control',
			'onkeyup'  => 'limit_dig(this.id,4)'
		);
		$this->data['expe_tipo_ref'] = array(
			'type'     => 'text',
			'name'     => 'expe_tipo_ref',
			'id'       => 'expe_tipo_ref',
			'value'    => $this->form_validation->set_value('expe_tipo_ref', $expediente->expe_tipo_ref),
			'class'    => 'form-control'
		);

		$this->data['expe_id_ref'] = array(
			'type'     => 'text',
			'name'     => 'expe_id_ref',
			'id'       => 'expe_id_ref',
			'value'    => $this->form_validation->set_value('expe_id_ref', $expediente->expe_id_ref),
			'class'    => 'form-control',
			'maxlength'=> '10',
			'readonly' => TRUE
		);	
		$this->data['expe_id_expediente_ref'] = array(
			'type'     => 'number',
			'name'     => 'expe_id_expediente_ref',
			'id'       => 'expe_id_expediente_ref',
			'value'    => $this->form_validation->set_value('expe_id_expediente_ref', $expediente->expe_id_expediente_ref),
			'class'    => 'form-control',
			'onkeyup'  => 'limit_dig(this.id,10)'
		);

		$this->data['expe_doc_proponente'] = array(
			'type'     => 'text',
			'name'     => 'expe_doc_proponente',
			'id'       => 'expe_doc_proponente',
			'value'    => $this->form_validation->set_value('expe_ci_proponente', $expediente->expe_doc_proponente),
			'class'    => 'form-control',
			'maxlength'=> '20'
		);
		$this->data['expe_proponente'] = array(
			'type'     => 'text',
			'name'     => 'expe_proponente',
			'id'       => 'expe_proponente',
			'value'    => $this->form_validation->set_value('expe_proponente', $expediente->expe_proponente),
			'class'    => 'form-control',
			'maxlength'=> '100'
		);
		$this->data['expe_id_geomatica'] = array(
			'type'     => 'hidden',
			'name'     => 'expe_id_geomatica',
			'id'       => 'expe_id_geomatica',
			'value'    => $this->form_validation->set_value('expe_id_geomatica', $expediente->expe_id_geomatica),
			'class'    => 'form-control',
			'onkeyup'  => 'limit_dig(this.id,20)',
			'readonly' => true
		);
		$this->data['expe_proyecto'] = array(
			'type'     => 'text',
			'name'     => 'expe_proyecto',
			'id'       => 'expe_proyecto',
			'rows'     => '1',
			'value'    => $this->form_validation->set_value('expe_proyecto', $expediente->expe_proyecto),
			'class'    => 'form-control',
			'maxlength'=> '255'
		);
		$this->data['expe_id_consultor'] = array(
			'type'     => 'text',
			'name'     => 'expe_id_consultor',
			'id'       => 'expe_id_consultor',
			'value'    => $this->form_validation->set_value('expe_id_consultor', $expediente->expe_id_consultor),
			'class'    => 'form-control',
			'list'	   => 'expe_id_consultor_list',
			'maxlength'=> '10'
		);
		$this->data['expe_consultor_nom'] = array(
			'type'     => 'text',
			'name'     => 'expe_consultor_nom',
			'id'       => 'expe_consultor_nom',
			'value'    => $this->form_validation->set_value('expe_consultor_nom', $expediente->expe_consultor_nom),
			'class'    => 'form-control',
			'maxlength'=> '100'
		);
		$this->data['expe_entrada'] = array(
			'type'     => 'text',
			'name'     => 'expe_entrada',
			'id'       => 'expe_entrada',
			'value'    => $this->form_validation->set_value('expe_entrada', $expediente->expe_entrada),
			'class'    => 'form-control'
		);
		$this->data['expe_usureg'] = array(
			'type'     => 'text',
			'name'     => 'expe_usureg',
			'id'       => 'expe_usureg',
			'value'    => $this->form_validation->set_value('expe_usureg', $expediente->expe_usureg),
			'class'    => 'form-control',
			'readonly' => true
		);	
		$this->data['expe_usuario'] = array(
			'type'     => 'text',
			'name'     => 'expe_usuario',
			'id'       => 'expe_usuario',
			'value'    => $this->form_validation->set_value('expe_usuario', $expediente->expe_usuario),
			'class'    => 'form-control',
			'readonly' => true
		);				
		$date = new DateTime($expediente->expe_fechareg);
		$newdate = utf8_decode($date->format('d-m-Y'));
		$this->data['expe_fechareg'] = array(
			'type'     => 'text',
			'name'     => 'expe_fechareg',
			'id'       => 'expe_fechareg',
			'value'    => $this->form_validation->set_value('expe_fechareg', $newdate),
			'class'    => 'form-control',
			'readonly' => true
		);
		$this->data['expe_secuencia'] = array(
				'type'     => 'text',
				'name'     => 'expe_secuencia',
				'id'       => 'expe_secuencia',
				'value'    => $this->form_validation->set_value('expe_secuencia', $expediente->expe_secuencia),
				'class'    => 'form-control',
				'readonly' => TRUE
			);
		$this->data['expe_observacion'] = array(
			'type'     => 'text',
			'name'     => 'expe_observacion',
			'id'       => 'expe_observacion', 
			'style'	   => 'height: 60px',
			'value'    => $this->form_validation->set_value('expe_observacion', $expediente->expe_observacion),
			'class'    => 'form-control'
		);
		$this->data['expe_tecnico'] = array(
			'type'     => 'text',
			'name'     => 'expe_tecnico',
			'id'       => 'expe_tecnico',
			'value'    => $this->form_validation->set_value('expe_tecnico', $expediente->expe_tecnico),
			'class'    => 'form-control',
			//'readonly' => TRUE
		);
		$this->data['expe_fproceso_geo'] = array(
			'type'     => 'text',
			'name'     => 'expe_fproceso_geo',
			'id'       => 'expe_fproceso_geo',
			'value'    => $this->form_validation->set_value('expe_fproceso_geo', $expediente->expe_fproceso_geo),
			'class'    => 'form-control',
			'readonly' => TRUE
		);
		$this->data['expe_nota'] = array(
			'type'     => 'text',
			'name'     => 'expe_nota',
			'id'       => 'expe_nota',
			'value'    => $this->form_validation->set_value('expe_nota', $expediente->expe_nota),
			'class'    => 'form-control',
			//'readonly' => TRUE
		);
		$this->data['expe_director'] = array(
			'type'     => 'text',
			'name'     => 'expe_director',
			'id'       => 'expe_director',
			'value'    => $this->form_validation->set_value('expe_director', $expediente->expe_director),
			'class'    => 'form-control',
			'readonly' => true
		);
		$this->data['expe_salida'] = array(
			'type'     => 'text',
			'name'     => 'expe_salida',
			'id'       => 'expe_salida',
			'value'    => $this->form_validation->set_value('expe_salida', date("d/m/Y", strtotime($expediente->expe_salida))),
			'class'    => 'form-control',
			'readonly' => true
		);
		$this->data['expe_provdg'] = array(
			'type'     => 'text',
			'name'     => 'expe_provdg',
			'id'       => 'expe_provdg',
			'value'    => $this->form_validation->set_value('expe_provdg', $expediente->expe_provdg),
			'class'    => 'form-control',
			'readonly' => true
		);
		$this->data['expe_sup_legal'] = array(
			'type'     => 'text',
			'name'     => 'expe_sup_legal',
			'id'       => 'expe_sup_legal',
			'value'    => $this->form_validation->set_value('expe_sup_legal', $expediente->expe_sup_legal),
			'class'    => 'form-control',
			//'readonly' => true
		);
		/*
		$this->data['expe_fecha_licencia'] = array(
			'type'     => 'hidden',
			'name'     => 'expe_fecha_licencia',
			'id'       => 'expe_fecha_licencia',
			'value'    => $this->form_validation->set_value('expe_fecha_licencia', $expediente->expe_fecha_licencia),
			'class'    => 'form-control',
			'readonly' => true
		);
		$this->data['expe_nro_licencia'] = array(
			'type'     => 'hidden',
			'name'     => 'expe_nro_licencia',
			'id'       => 'expe_nro_licencia',
			'value'    => $this->form_validation->set_value('expe_nro_licencia', $expediente->expe_nro_licencia),
			'class'    => 'form-control',
			'readonly' => true
		);
		$this->data['expe_usuario'] = array(
			'type'     => 'text',
			'name'     => 'expe_usuario',
			'id'       => 'expe_usuario',
			'value'    => $this->form_validation->set_value('expe_usuario', $expediente->expe_usuario),
			'class'    => 'form-control',
			'readonly' => true
		);
		$this->data['expe_nro_archivo'] = array(
			'type'     => 'hidden',
			'name'     => 'expe_nro_archivo',
			'id'       => 'expe_nro_archivo',
			'value'    => $this->form_validation->set_value('expe_nro_archivo', $expediente->expe_nro_archivo),
			'class'    => 'form-control',
			'readonly' => true
		);		
		$this->data['expe_fecha_cierre'] = array(
			'type'     => 'hidden',
			'name'     => 'expe_fecha_cierre',
			'id'       => 'expe_fecha_cierre',
			'value'    => $this->form_validation->set_value('expe_fecha_cierre', $expediente->expe_fecha_cierre),
			'class'    => 'form-control',
			'readonly' => true
		);
		*/
		$this->data['expe_estado'] = array(
			'type'     => 'text',
			'name'     => 'expe_estado',
			'id'       => 'expe_estado',
			'value'    => $this->form_validation->set_value('expe_estado', $expediente->expe_estado),
			'class'    => 'form-control col-xs-2',
			'readonly' => true
		);
		if ($this->expedientes_model->dropdown_data('conceptos',array('tipoconcepto' => 'EXPE_ESTADO', 'concepto' =>$expediente->expe_estado))->row()) {
			$expe_estado = $this->expedientes_model->dropdown_data('conceptos',array('tipoconcepto' => 'EXPE_ESTADO', 'concepto' =>$expediente->expe_estado))->row()->nombre;
		}else{
			$expe_estado = NULL;
		}
		
		$this->data['estado_descrip'] = array(
			'type'     => 'text',
			'name'     => 'estado_descrip',
			'id'       => 'estado_descrip',
			'value'    => $expe_estado,
			'class'    => 'form-control col-xs-5',
			'readonly' => true
		);

		$dependencias[''] = 'Seleccione la dependencia';
		$dependencia = $this->expedientes_model->dropdown_data('dependencias')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($dependencia as $dep) {
			$dependencias[$dep['depe_id']] = $dep['depe_codigo'].' - '.$dep['depe_nombre_abreviado'];
		}
		$this->data['expe_id_dependencia'] = $dependencias;
		$this->data['expe_id_dependencia_sel'] = $expediente->expe_id_dependencia;
		
		$tecs[''] = 'Seleccione el técnico';
		$tecnico = $this->expedientes_model->dropdown_data('v_tecnicos')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($tecnico as $tec) {
			$tecs[$tec['username']] = $tec['first_name'].' '.$tec['last_name'];
		}
		$this->data['expe_tecnico'] = $tecs;
		$this->data['expe_tecnico_sel'] = $expediente->expe_tecnico;

		$dptos[''] = 'Seleccione el departamento';
		$departamentos = $this->expedientes_model->dropdown_data('departamentos','','dpto_id_departamento')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($departamentos as $dpto) {
			$dptos[$dpto['dpto_id_departamento']] = $dpto['dpto_id_departamento'].' - '.$dpto['dpto_descripcion'];
		}
		$this->data['departamentos'] = $dptos;
		$this->data['departamentos_sel'] = $expediente->expe_id_departamento;

		$dists[''] = 'Seleccione el distrito';
		$dist = $this->expedientes_model->dropdown_data('distritos',array('dist_id_departamento' => $expediente->expe_id_departamento),
																 'dist_id_ciudad'
																)->result_array();

		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($dist as $dt) {
			$dists[$dt['dist_id_ciudad']] = $dt['dist_id_ciudad'].' - '.$dt['dist_descripcion'];
		}
		$this->data['distritos'] = $dists;
		$this->data['distritos_sel'] = $expediente->expe_id_distrito;



		$expes[''] = 'Seleccione Expediente';
		$expe = $this->expedientes_model->dropdown_data('exp',array('expe_id_expediente' => $expediente->expe_id_expediente_ref),
																 'expe_id'
																)->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($expe as $ex) {
			$expes[$ex['expe_id']] = $ex['expe_id_expediente'].'-'.$ex['expe_gestion'].'-'.$ex['expe_id_dependencia'].'-'.$ex['expe_secuencia'];
			//echo $ex['expe_id'].' '.$expes[$ex['expe_id']];			
		}
		//show_error(1);		
		$this->data['expe'] = $expes;
		$this->data['expe_sel'] = $expediente->expe_id_ref;



		$tipoproyectos[''] = 'Tipo de proyecto';
		$tipoproyecto = $this->expedientes_model->dropdown_data('tipo_proyecto','','tpro_tipo_proy')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($tipoproyecto as $tp) {
			$tipoproyectos[$tp['tpro_tipo_proy']] = $tp['tpro_tipo_proy'].' - '.$tp['tpro_nombre_tipo_proy'];
		}
		$this->data['tipoproyecto'] = $tipoproyectos;
		$this->data['tipoproyecto_sel'] = $expediente->expe_tipo_proyecto;

		$consultor = $this->expedientes_model->dropdown_data('consultores','','cstr_codigo_ctca')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($consultor as $cs) {
			$consultors[$cs['cstr_codigo_ctca']] = $cs['cstr_nombre_consultor'];
		}
		$this->data['consultor'] = $consultors;

		$tiporefs[''] = 'Tipo Ref.';
		$tiporef = $this->expedientes_model->dropdown_data('conceptos',array('tipoconcepto' => 'TIPO_REF'),'concepto')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($tiporef as $tr) {
			$tiporefs[$tr['concepto']] = $tr['concepto'].' - '.$tr['nombre'];
		}
		$this->data['tipo_ref'] = $tiporefs;
		$this->data['tipo_ref_sel'] = $expediente->expe_tipo_ref;

		$bloqueos[''] = 'Bloqueo';
		$bloqueo = $this->expedientes_model->dropdown_data('conceptos',array('tipoconcepto' => 'EXPE_BLOQUEO'),'concepto')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($bloqueo as $bl) {
			$bloqueos[$bl['concepto']] = $bl['concepto'].' - '.$bl['nombre'];
		}
		$this->data['expe_bloqueo'] = $bloqueos;
		$this->data['expe_bloqueo_sel'] = $expediente->expe_bloqueo;

		/*$estados[''] = 'Estado';
		$estado = $this->expedientes_model->dropdown_data('conceptos',array('tipoconcepto' => 'EXPE_ESTADO'),'concepto')->result_array();
		//inserta en un array asociativo para poder utilizarlo en el form_dropdown
		foreach ($estado as $es) {
			$estados[$es['concepto']] = $es['concepto'].' - '.$es['nombre'];
		}
		$this->data['expe_estado'] = $estados;
		$this->data['expe_estado_sel'] = $expediente->expe_estado;*/
		
		/* Load Template */
		$this->template->admin_render('expedientes/edit_expe', $this->data);
	}
  
	public function tiene_salida()
	{
		$expe_id = $_POST['expe_id'];

		$expe = $this->expedientes_model->view('exp', array('expe_id' => $expe_id, 'expe_estado' => 'P'))->row();

		if ($expe) {
			echo 'SI';
		}else{
			echo 'NO';
		}
	}

	public function existe_grafico()
	{
		$id_expediente 	= $_POST['id_expediente'];
		$gestion 		= $_POST['gestion'];

		$expe = $this->expedientes_model->existe_grafico($id_expediente, $gestion)->row()->f_existe_grafico;
		
		echo $expe;
	}
  

	public function existe_grafico_expe_id()
	{
		$expe_id 	= $_POST['expe_id'];

		$expe = $this->expedientes_model->existe_grafico_expe_id($expe_id)->row()->f_existe_grafico_expe_id;
		
		echo $expe;
	}


	public function existe_exp()
	{
		$exp 		= $_POST['exp'];
		$gestion 	= $_POST['gest'];

		$expe = $this->expedientes_model->dropdown_data('exp', array('expe_id_expediente' => $exp, 'expe_gestion' => $gestion))->num_rows();

		if ($expe > 0) {
			echo 'SI';
		}else{
			echo 'NO';
		}
	}

	public function existe_exp_uk()
	{
		$exp 		= $_POST['exp'];
		$gestion 	= $_POST['gest'];
		$dep 	= $_POST['dep'];

		$expe = $this->expedientes_model->dropdown_data('exp', array('expe_id_expediente' => $exp, 
			                                                          'expe_gestion' => $gestion,
			                                                          'expe_id_dependencia' => $dep
			                                                          ))->num_rows();

		if ($expe > 0) {
			echo 'SI';
		}else{
			echo 'NO';
		}
	}


	public function reingreso_exp()
	{
		$exp 	= $_POST['exp'];
		$gest 	= $_POST['gest'];

		$expe_id = $this->expedientes_model->dropdown_data('exp', array('expe_id_expediente' => $exp, 'expe_gestion' => $gest))->row()->expe_id;

		echo $expe_id;

		//$reingreso  = $this->expedientes_model->actualizar_expediente($expe_id, array('expe_id_expediente_ref' => $exp, 'expe_id' => ));

		
		//redirect('expedientes/expedientes/edit_expe/'.$expe_id);
	}

	public function dar_salida_expe($expe_id, $expe_id_expediente, $expe_gestion, $expe_provdg = NULL)
	{

		$i_exp 		= $expe_id_expediente;
		$i_gest 	= $expe_gestion;


					$i_user = $this->session->userdata('username');
					//echo $i_user;
					//show_error(1);



		if (!is_null($i_exp) AND $i_gest > 0) {
			if (grupo_usuario(18)) {


				//if ($expe_provdg == NULL) {
				if (is_null($expe_provdg)) {
					$provdg = 0;
				}else{
					$provdg = $expe_provdg;
				}

				if ($provdg == 0) {
					$i_max = $this->expedientes_model->campo_valor_maximo('exp', 'expe_provdg' , array('expe_director' => $i_user ));

					$i_max = $i_max+1;

					$str 	= date_default_timezone_get();
					$fecha  = date("d/m/Y", strtotime($str));

					$salida = $this->expedientes_model->actualizar_expediente($expe_id, array('expe_provdg'   => $i_max, 
																					 		  'expe_director' => $this->session->userdata('username'),
																					 		  'expe_salida'   => $fecha,
																					 		  'expe_estado'   => 'P'));
					if ($salida) {
						$this->session->set_flashdata('message', '¡Se DIÓ SALIDA exitósamente!');
						redirect('expedientes/expedientes/edit_expe/'.$expe_id);
					}else{
						$this->session->set_flashdata('message', '¡No se pudo DAR SALIDA!');
						redirect('expedientes/expedientes/edit_expe/'.$expe_id);
					}
				}else{
					$this->session->set_flashdata('message', '¡Campo PROV. DG sin dato!');
					redirect('expedientes/expedientes/edit_expe/'.$expe_id);
				}
			}else{
				$this->session->set_flashdata('message', 'NO TIENE PRIVILEGIOS PARA ESTA ACCIÓN');
				redirect('expedientes/expedientes/edit_expe/'.$expe_id);
			}
		}else{
			redirect('expedientes/expedientes/edit_expe/'.$expe_id);
		}
	}

	public function anular_salida_expe($expe_id) 
	{

		//echo($expe_id);
		$expe = $this->expedientes_model->dropdown_data('exp', array('expe_id' => $expe_id))->result();


		//echo '<option value="">Seleccione el distrito</option>';

		foreach ($expe as $value) {
			$i_exp 		 = $value->expe_id_expediente;
			$i_gest 	 = $value->expe_gestion;
			$i_provdg = $value->expe_provdg;
		}

		if (!is_null($i_exp) AND $i_gest > 0) {
			if (grupo_usuario(18)) {

				if ($i_provdg == NULL) {
					$provdg = 0;
				}else{
					$provdg = $i_provdg;
				}

				if ($provdg != 0) {
					
					$salida = $this->expedientes_model->actualizar_expediente($expe_id, array('expe_provdg'   => NULL, 
																					 		  'expe_director' => '',
																					 		  'expe_salida'   => NULL,
																					 		  'expe_estado'   => 'A'));
					if ($salida) {
						$this->session->set_flashdata('message', '¡Se ANULÓ LA SALIDA exitósamente!');
						redirect('expedientes/expedientes/edit_expe/'.$expe_id);
					}else{
						$this->session->set_flashdata('message', '¡No se pudo ANULAR SALIDA!');
						//redirect('expedientes/expedientes/edit_expe/'.$expe_id);
						redirect('expedientes/expedientes/index/');				
					}
				}
			}else{
				$this->session->set_flashdata('message', 'NO TIENE PRIVILEGIOS PARA ESTA ACCIÓN');
				//redirect('expedientes/expedientes/index/'.$expe_id);
				redirect('expedientes/expedientes/index/');				
			}
		}else{
			//redirect('expedientes/expedientes/index/'.$expe_id);
			redirect('expedientes/expedientes/index/');				
		}
	}


	public function call_bat()
	{
		$cmd = system('cmd /c C:/espacio_trabajo/importar_shape_seam.bat');
	}


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

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

		/* Validate form input */
		$this->form_validation->set_rules('col_cod', 'lang:geocolonia_col_cod' , 'required');
		$this->form_validation->set_rules('col_desc','lang:geocolonia_col_desc', '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')
				);
			$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')
				);

			$dptos[''] = 'Seleccione el departamento';
			$departamentos = $this->expedientes_model->dropdown_data('departamentos','','dpto_id_departamento')->result_array();
			//inserta en un array asociativo para poder utilizarlo en el form_dropdown
			foreach ($departamentos as $dpto) {
				$dptos[$dpto['dpto_id_departamento']] = $dpto['dpto_id_departamento'].' - '.$dpto['dpto_descripcion'];
			}
			$this->data['departamentos'] = $dptos;
			
			///* Load Template */
			$this->template->admin_render('expedientes/form_expediente', $this->data);
		}
	}

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

		$distritos = $this->expedientes_model->dropdown_data('distritos',array('dist_id_departamento' => $dpto), 'dist_id_ciudad')->result();

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

		//echo json_encode($distritos);
	}

	public function trae_expe_ref()
	{
		$expe 	   = $_POST['expe_id_expediente_ref'];

		$expes = $this->expedientes_model->dropdown_data('exp',array('expe_id_expediente_ref' => $expe), 'expe_id')->result();

		echo '<option value="">Seleccione Expediente</option>';
		foreach ($expes as $value) {

			$expes[$ex['expe_id']] = $ex['expe_id_expediente'].'-'.$ex['expe_gestion'].'-'.$ex['expe_id_dependencia'].'-'.$ex['expe_secuencia'];

			echo '<option value="' . $value->expe_id . '">' . $value->expe_id_expediente . '-' . $value->expe_gestion . '-' . $value->expe_id_dependencia . '-' . $value->expe_secuencia .  '</option>';
		}

		//echo json_encode($distritos);
	}

	public function delete()
	{
		$delete  = $this->expedientes_model->eliminar_expediente($_POST['expe_id']);
		//$this->session->set_flashdata('message', '¡El expediente <b>'.$_POST['exp'].'</b>, gestión <b>'.$_POST['gest'].'</b> se eliminó correctamente!');

		$_SESSION['last_exp_delete'] = '¡El expediente <b>'.$_POST['exp'].'</b>, gestión <b>'.$_POST['gest'].'</b> se eliminó correctamente!';

		echo 'SI';
		//redirect('expedientes/expedientes/index');
	}

	public function verparcela ($expe_id , $expe_gest) {

        	$i_jameuge = "http://201.217.59.143:8065/seampg/index.html?exp=" . $expe_id;
        	$i_jameuge = $i_jameuge . "&gest=" . $expe_gest;

			redirect($i_jameuge);
	}

	public function verparcela_expe_id ($expe_id ) {

        	$i_jameuge = "http://201.217.59.143:8065/seampg/index.html?expe_id=" . $expe_id;

			redirect($i_jameuge);
	}

}