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

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

		$this->load->helper('catalogos/my_xajax_altas_e_s');
		$this->load->model('catalogos/Model_altas_e_s','maes');
		$this->load->library('catalogos/Altas_e_s_lib');

		$this->form_validation->set_message('alpha_numeric_dash_space','El campo %s acepta únicamente letras, numeros y espacios');
		$this->form_validation->set_message('min_length','El campo %s No puede tener menos de %d caracteres');
		$this->form_validation->set_message('max_length','El campo %s No puede tener más de %d caracteres');
		$this->form_validation->set_message('required','Debe ingresar un valor para %s');
		$this->form_validation->set_message('norep','Ya existe un(a) %s con ese nombre');
		$this->form_validation->set_message('combo_check','Selecciona un %s');
		$this->form_validation->set_message('emailok','Correo inválido');

		/*****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('mostrar',&$this,'mostrar'));
        $this->xajax->register(XAJAX_FUNCTION,array('cargar_empresa',&$this,'cargar_empresa'));
        //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($value = ""){
		$this->data['contenido'] = 'catalogos/altas_e_s/index';
		$this->data[$value] = TRUE;
		$this->load->view('template',$this->data);
	}

	public function create_empresa(){
		$data['contenido'] = 'catalogos/altas_e_s/create_empresa';
		$this->load->view('template',$data);
	}

	public function create_sucursal(){
		$this->data['contenido'] = 'catalogos/altas_e_s/create_sucursal';
		$this->data['query'] = $this->maes->cargar_empresa();
		$this->load->view('template',$this->data);
	}

	//dentro del callback mandamos más parámetros dividiendolos por el simbolo '-' ya que callcak solo admite 2 parámetros.
	//Despúes, donde los utilizemos, ocuparemos la function LIST de php
	public function insert_empresa(){
		$this->form_validation->set_rules('razon_social','Razón Social','trim|required|alpha_numeric_dash_space|callback_norep[cat_empresa-razon_social]');
		$this->form_validation->set_rules('rfc','RFC','trim|required|alpha_numeric_dash_space|min_length[13]|max_length[16]|callback_norep[cat_empresa-rfc]');
		$this->form_validation->set_rules('contacto','Contacto','trim|required|alpha_numeric_dash_space');
		$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');
		if($this->form_validation->run() == FALSE)
			$this->create_empresa();
		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->maes->insert_cat_general($registro);
			//despues en la tabla correspondiente (cat_empresa)
			$registro = array(
				"rfc" => $this->input->post("rfc"),
				"razon_social" => $this->input->post("razon_social"),
				"contacto" => $this->input->post("contacto"),
				"fk_cat_generales" => $pk
			);
			$this->maes->insert($registro,"cat_empresa");
			redirect('catalogos/altas_e_s/index/empresa');
		}
	}

	public function insert_sucursal(){
		$this->form_validation->set_rules('nombre','Nombre','trim|required|alpha_numeric_dash_space|callback_norep[cat_sucursal-nombre]');
		$this->form_validation->set_rules('prefijo','Prefijo','trim|required|alpha_numeric_dash_space|max_length[5]|callback_norep[cat_sucursal-prefijo]');
		$this->form_validation->set_rules('fk_cat_empresa','Empresa','callback_combo_check[fk_cat_empresa]');
		$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');
		if($this->form_validation->run() == FALSE)
			$this->create_sucursal();
		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->maes->insert_cat_general($registro);
			//despues en la tabla correspondiente (cat_sucursal)
			$registro = array(
				"nombre" => $this->input->post("nombre"),
				"prefijo" => $this->input->post("prefijo"),
				"fk_cat_empresa" => $this->input->post("fk_cat_empresa"),
				"fk_cat_generales" => $pk
			);
			$this->maes->insert($registro,"cat_sucursal");
			redirect('catalogos/altas_e_s/index/sucursal');
		}
	}

	public function edit_empresa($pk_empresa){
		$data['contenido'] = 'catalogos/altas_e_s/edit_empresa';
		$data['registro'] = $this->maes->find_empresa($pk_empresa);
		$this->load->view('template',$data);
	}

	public function edit_sucursal($pk_sucursal){
		$data['contenido'] = 'catalogos/altas_e_s/edit_sucursal';
		$data['registro'] = $this->maes->find_sucursal($pk_sucursal);
		$this->load->view('template',$data);
	}

	public function update_empresa(){
		$this->form_validation->set_rules('razon_social','Razón Social','trim|required|alpha_numeric_dash_space|callback_norep[cat_empresa-razon_social]');
		$this->form_validation->set_rules('rfc','RFC','trim|required|alpha_numeric_dash_space|min_length[13]|max_length[16]|callback_norep[cat_empresa-rfc]');
		$this->form_validation->set_rules('contacto','Contacto','trim|required|alpha_numeric_dash_space');
		$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');
		if ($this->form_validation->run() == FALSE) 
			$this->edit_empresa($this->input->post('pk_cat_empresa'));
		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->maes->update($registro,'pk_cat_generales','cat_generales');
			//despues en la tabla correspondiente (cat_empresa)
			$registro = array(
				"rfc" => $this->input->post("rfc"),
				"razon_social" => $this->input->post("razon_social"),
				"contacto" => $this->input->post("contacto"),
				"pk_cat_empresa" => $this->input->post("pk_cat_empresa")
			);

			$this->maes->update($registro,'pk_cat_empresa','cat_empresa');
			redirect('catalogos/altas_e_s/index/empresa');
		}
	}

	public function update_sucursal(){
		$this->form_validation->set_rules('nombre','Nombre','trim|required|alpha_numeric_dash_space|callback_norep[cat_sucursal-nombre]');
		$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');
		if ($this->form_validation->run() == FALSE) 
			$this->edit_sucursal($this->input->post('pk_cat_sucursal'));
		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->maes->update($registro,'pk_cat_generales','cat_generales');
			//despues en la tabla correspondiente (cat_sucursal)
			$registro = array(
				"nombre" => $this->input->post("nombre"),
				"pk_cat_sucursal" => $this->input->post("pk_cat_sucursal")
			);
			$this->maes->update($registro,'pk_cat_sucursal','cat_sucursal');
			redirect('catalogos/altas_e_s/index/sucursal');
		}
	}

	public function update_status($pk,$status,$tabla){
		$status = ($status == 'A') ? 'B' : 'A';
		$this->maes->update_status($pk,$status,'pk_cat_'.$tabla,'cat_'.$tabla);
		redirect('catalogos/altas_e_s/index/'.$tabla);
	}

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

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

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

	/*FUNCIONES XAJAX*/
	public function seleccion($value){
		$respuesta = new xajaxResponse();
	    //OBTENEMOS LOS DATOS DE LA TABLA
	    if($value == 'empresa')
	    	$datos = $this->maes->all_empresa();
	    else
	    	$datos = $this->maes->all_sucursal();
	    $respuesta->Assign('div_mostrar','innerHTML',mostrar_seleccion($value,$datos));
	    $respuesta->script("$(document).ready(function () {
						        mostrarOpcionesTabla('dt_mostrar_seleccion',false,false,true);
						    });");
	    return $respuesta;
    }

    public function mostrar($tabla,$value){
		$respuesta = new xajaxResponse();
		//OBTENEMOS LOS DATOS DE LA TABLA
	    if($tabla == 'empresa')
	    	$datos = $this->maes->all_filtered_empresa($value);
	    else
	    	$datos = $this->maes->all_filtered_sucursal($value);
	    $respuesta->Assign('div_mostrar','innerHTML',mostrar_seleccion($tabla,$datos));
	    $respuesta->script("$('#txt_buscar').focus()");
		return $respuesta;
	}

	public function cargar_empresa($pk_cat_proveedor){
		$respuesta = new xajaxResponse();
		$datos = $this->maes->cargar_empresa($pk_cat_proveedor);
		$respuesta->Assign('div_cmb_marca','innerHTML',mostrar_marcas($datos,$pk_cat_proveedor));
		return $respuesta;
	}
    /*****************/
}