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

class Altas extends CI_Controller {
	
	//Constructor
	function __construct(){
		parent::__construct();

		$this->load->helper('rh/my_xajax_altas_helper');
		$this->load->model('rh/Model_altas','ma');
		$this->load->library('rh/Altas_lib');

		$this->form_validation->set_message('required','Debe ingresar un valor para %s');
		$this->form_validation->set_message('norep','Existe otro registro con el mismo %s');
		$this->form_validation->set_message('emailok','Correo inválido');
		$this->form_validation->set_message('combo_check','Selecciona un(a) %s');

		/*****Parametros para el correcto funcionamiento de XAJAX*****/
		//mostrar ventana de depuracion
		$this->xajax->configure('debug',FALSE);
		//Registro de funciones XAJAX
        $this->xajax->register(XAJAX_FUNCTION,array('seleccion',&$this,'seleccion'));
        $this->xajax->register(XAJAX_FUNCTION,array('cargar_sucursal',&$this,'cargar_sucursal'));
        //Para procesar las peticiones
        $this->xajax->processRequest();
        //mandamos el script a la pagina      
        $this->xajax->configure('javascript URI',base_url());  
        $this->data['xajax_js'] = $this->xajax->getJavascript(base_url());
	}

	public function index(){
		$data['contenido'] = 'rh/altas/index';
		$data['query'] = $this->ma->all();
		$this->load->view('template',$data);
	}

	public function search(){
		$data['contenido'] = 'rh/altas/index';
		$valor = $this->input->post('txt_buscar');
		$data['query'] = $this->ma->all_filtered($valor);
		$this->load->view('template',$data);
	}

	public function create(){
		$this->data['contenido'] = 'rh/altas/create';
		$this->data['query'] = $this->ma->tipo_usuarios();
		$this->data["articulos"] = $this->ma->articulos($this->session->userdata('pk_cat_personal'));
		$this->load->view('template',$this->data);
	}

	public function insert(){
		$this->form_validation->set_rules('nombre','Nombre','trim|required');
		$this->form_validation->set_rules('apat','Ap. Paterno','trim|required');
		$this->form_validation->set_rules('amat','Ap. Materno','trim|required');
		$this->form_validation->set_rules('txt_calle','Calle','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_num_int','N° Int','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_num_ext','N° Ext','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_cp','C.P.','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_colonia','Colonia','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_localidad','Localidad','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_municipio','Municipio','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_ciudad','Ciudad','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_estado','Estado','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_pais','País','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_telefono','Teléfono','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_correo','Correo','trim|required|callback_emailok');
		$this->form_validation->set_rules('usuario','Usuario','trim|required|callback_norep[usuario]');
		$this->form_validation->set_rules('pass','Contraseña','trim|required');
		$this->form_validation->set_rules('fk_cat_tipo_usuario','Tipo Usuario','callback_combo_check[fk_cat_tipo_usuario]');
		$this->form_validation->set_rules('fk_cat_articulo_maestro','Artículo Maestro','callback_combo_check[fk_cat_articulo_maestro]');
		$this->form_validation->set_rules('rbtn_opc','Esta Persona esta liga a a una:','required');
		if($this->input->post('rbtn_opc') == 'empresa')
			$this->form_validation->set_rules('fk_cat_empresa','Empresa','callback_combo_check[fk_cat_empresa]');
		else{
			$this->form_validation->set_rules('fk_cat_empresa','Empresa','callback_combo_check[fk_cat_empresa]');
			$this->form_validation->set_rules('fk_cat_sucursal','Sucursal','callback_combo_check[fk_cat_sucursal]');
		}
		if($this->form_validation->run() == FALSE){
			$this->create();
		}
		else{
			$registro = array(
				"calle" => $this->input->post("txt_calle"),
				"num_int" => $this->input->post("txt_num_int"),
				"num_ext" => $this->input->post("txt_num_ext"),
				"cp" => $this->input->post("txt_cp"),
				"colonia" => $this->input->post("txt_colonia"),
				"localidad" => $this->input->post("txt_localidad"),
				"municipio" => $this->input->post("txt_municipio"),
				"ciudad" => $this->input->post("txt_ciudad"),
				"estado" => $this->input->post("txt_estado"),
				"pais" => $this->input->post("txt_pais"),
				"telefono" => $this->input->post("txt_telefono"),
				"correo" => $this->input->post("txt_correo")
			);
			//primero insertamos en cat_general para que regrese el pk insertado
			$pk = $this->ma->insert_cat_general($registro);
			//despues en la tabla correspondiente (cat_personal)
			$pertenece_a = ($this->input->post('rbtn_opc') == 'empresa') ? 'e_'.$this->input->post('fk_cat_empresa') : 's_'.$this->input->post('fk_cat_sucursal');
			$registro = array(
				"nombre" => $this->input->post("nombre"),
				"apat" => $this->input->post("apat"),
				"amat" => $this->input->post("amat"),
				"usuario" => $this->input->post("usuario"),
				"pass" => md5($this->input->post("pass")),
				"empleado_de" => $pertenece_a,
				"articulo_maestro" => $this->input->post('fk_cat_articulo_maestro'),
				"fk_cat_generales" => $pk,
				"fk_cat_tipo_usuario" => $this->input->post("fk_cat_tipo_usuario")
			);
			$this->ma->insert($registro);
			redirect('rh/altas/index');
		}
	}

	public function edit($pk_cat_personal){
		$this->data['contenido'] = 'rh/altas/edit';
		$this->data['registro'] = $this->ma->find($pk_cat_personal);
		$this->data['query'] = $this->ma->tipo_usuarios();
		$this->data['pertenece_a'] = $this->ma->pertenece_a($this->data['registro']->empleado_de);
		$this->data["articulos"] = $this->ma->articulos($pk_cat_personal);
		$this->load->view('template',$this->data);

	}

	public function update(){
		$this->form_validation->set_rules('nombre','Nombre','trim|required');
		$this->form_validation->set_rules('apat','Ap. Paterno','trim|required');
		$this->form_validation->set_rules('amat','Ap. Materno','trim|required');
		$this->form_validation->set_rules('txt_calle','Calle','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_num_int','N° Int','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_num_ext','N° Ext','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_cp','C.P.','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_colonia','Colonia','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_localidad','Localidad','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_municipio','Municipio','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_ciudad','Ciudad','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_estado','Estado','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_pais','País','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_telefono','Teléfono','trim|required|alpha_numeric_dash_space');
		$this->form_validation->set_rules('txt_correo','Correo','trim|required|callback_emailok');
		$this->form_validation->set_rules('usuario','Usuario','trim|required|callback_norep[usuario]');
		$this->form_validation->set_rules('fk_cat_tipo_usuario','Tipo Usuario','callback_combo_check[fk_cat_tipo_usuario]');
		$this->form_validation->set_rules('fk_cat_articulo_maestro','Artículo Maestro','callback_combo_check[fk_cat_articulo_maestro]');
		$this->form_validation->set_rules('rbtn_opc','Esta Persona esta liga a a una:','required');
		if($this->input->post('rbtn_opc') == 'empresa')
			$this->form_validation->set_rules('fk_cat_empresa','Empresa','callback_combo_check[fk_cat_empresa]');
		else{
			$this->form_validation->set_rules('fk_cat_empresa','Empresa','callback_combo_check[fk_cat_empresa]');
			$this->form_validation->set_rules('fk_cat_sucursal','Sucursal','callback_combo_check[fk_cat_sucursal]');
		}
		if($this->form_validation->run() == FALSE){
			$this->edit($this->input->post('pk_cat_personal'));
		}
		else{
			$registro = array(
				"calle" => $this->input->post("txt_calle"),
				"num_int" => $this->input->post("txt_num_int"),
				"num_ext" => $this->input->post("txt_num_ext"),
				"cp" => $this->input->post("txt_cp"),
				"colonia" => $this->input->post("txt_colonia"),
				"localidad" => $this->input->post("txt_localidad"),
				"municipio" => $this->input->post("txt_municipio"),
				"ciudad" => $this->input->post("txt_ciudad"),
				"estado" => $this->input->post("txt_estado"),
				"pais" => $this->input->post("txt_pais"),
				"telefono" => $this->input->post("txt_telefono"),
				"correo" => $this->input->post("txt_correo"),
				"pk_cat_generales" => $this->input->post("fk_cat_generales")
			);
			//actualizamos la tabla cat_generales
			$this->ma->update($registro,'pk_cat_generales','cat_generales');
			//despues en la tabla correspondiente (cat_personal)
			$pertenece_a = ($this->input->post('rbtn_opc') == 'empresa') ? 'e_'.$this->input->post('fk_cat_empresa') : 's_'.$this->input->post('fk_cat_sucursal');
			$registro = array(
				"nombre" => $this->input->post("nombre"),
				"apat" => $this->input->post("apat"),
				"amat" => $this->input->post("amat"),
				"usuario" => $this->input->post("usuario"),
				"empleado_de" => $pertenece_a,
				"articulo_maestro" => $this->input->post('fk_cat_articulo_maestro'),
				"fk_cat_tipo_usuario" => $this->input->post("fk_cat_tipo_usuario"),
				"pk_cat_personal" => $this->input->post("pk_cat_personal")
			);
			$this->ma->update($registro,'pk_cat_personal','cat_personal');
			redirect('rh/altas/index');
		}
	}

	public function update_status($pk_cat_personal,$status){
		$status = ($status == 'A') ? 'B' : 'A';
		$this->ma->update_status($pk_cat_personal,$status);
		redirect('rh/altas/index');
	}

	public function emailok(){
		return $this->altas_lib->emailok($this->input->post('txt_correo'));
	}

	public function norep($value,$campo){
		return $this->altas_lib->norep($this->input->post(),$campo);
	}

	public function combo_check($value,$tabla){
		return $this->altas_lib->combo_check($this->input->post(),$tabla);
	}

	/*FUNCIONES XAJAX*/
	public function seleccion($value){
		$respuesta = new xajaxResponse();
	    //OBTENEMOS LOS DATOS DE LA TABLA CAT_EMPRESA
	    $datos = $this->ma->cat_empresa();
	    $respuesta->assign('div_mostrar','innerHTML',empresa($value,$datos));
	    $respuesta->script("$(function () {
        						$('.chosen-select').chosen({width: '100%'});
							});");
	    return $respuesta;
    }

    public function cargar_sucursal($pk_cat_empresa){
		$respuesta = new xajaxResponse();
		if($pk_cat_empresa == 'Seleccione')
			$respuesta->assign('div_mostrar','innerHTML',empty_msg('Seleciona una Empresa'));
		else{
		    //OBTENEMOS LOS DATOS DE LA TABLA CAT_SUCURSAL
	    	$datos = $this->ma->cat_sucursal($pk_cat_empresa);
	    	$respuesta->assign('div_sucursal','innerHTML',sucursal($datos));
	    	$respuesta->script("$(function () {
	        						$('.chosen-select').chosen({width: '100%'});
								});");
	    }
	    return $respuesta;
    }
	
}