<?php
class Proveedores extends CI_Controller{
	function __construct(){
		parent::__construct();
		$this->is_logged_in();
		$this->session_ = $this->session->userdata('userInfo');
		$this->permisos=$this->Generic_model->get('usuarios','permisos_usuario',array('id_usuario'=>$this->session_['userid']));
		$this->permisos=unserialize(base64_decode($this->permisos[0]->permisos_usuario));
		/*usuario*/
		$this->usuario=$this->Generic_model->get('usuarios','nombre_usuario as nombre,username_usuario as username, thumb_usuario as thumbnail',array('id_usuario'=>$this->session_['userid']));
		$this->usuario=$this->usuario[0];
	}
	/**/
	function index(){echo "Proveedores!";}
	/*------------------------- LISTA ----------------------*/
	function lista(){
		$UIData['user_info']=$this->usuario;
		$UIData['section_title']="Proveedores";
		if(!filter_var($this->permisos['proveedores']['proveedores-ver'],FILTER_VALIDATE_BOOLEAN)){
			$UIData['main_view']="error_noacceso_view";
		}else{
			$UIData['main_view']="proveedores_lista_view";
			$UIData['jsfiles']=array("miracle.proveedores");
			$UIData['plugins']=array(
				array(
					"nombre"=>"jquery_form",
					"js"=> array('jquery.form.min')
				),
				array(
					"nombre"=>"validate",
					"js"=> array('jquery.validate.min')
				),
				array(
					"nombre"=>"datapicker",
					"css"=>array('datepicker3'),
					"js"=>array('bootstrap-datepicker','locales/bootstrap-datepicker.es')
				),
				array(
					"nombre"=>"datatables",
					"css"=> array('dataTables.bootstrap','dataTables.responsive','dataTables.tableTools.min'),
					"js"=> array('jquery.dataTables','dataTables.bootstrap.min','dataTables.responsive','dataTables.tableTools.min')
				),
			);
		}
		$this->load->view('template', $UIData);
	}
		/*Cargar proveedores*/
		function cargar(){
			$search=array("nombre_proveedor"=>$this->input->get('search'));
			$orSearch=array("razonsocial_proveedor"=>$this->input->get('search'));
			$limits=array(12=>$this->input->get('offset'));
			echo json_encode($this->Generic_model->get('proveedores','id_proveedor as id, nombre_proveedor as nombre, razonsocial_proveedor as razon, telefono_proveedor as tel, logo_proveedor as logo','',array('nombre_proveedor'=>'ASC'),$search,'',$limits,'',$orSearch));			
		}
		/*Nuevo proveedor*/
		function nuevo(){
			$mode=$this->input->get('mode');
			if($mode=='edit'){
				$UIDataModal["title"]="Editar proveedor";
				if(!filter_var($this->permisos['proveedores']['proveedores-editar'],FILTER_VALIDATE_BOOLEAN)){
					$UIDataModal['content_view']="error_noacceso_view";
				}else{
					$UIDataModal['proveedor']=$this->Generic_model->get('proveedores','*',array('id_proveedor'=>$this->input->get('id')));
					$UIDataModal['contactos']=$this->Generic_model->get('contactos','nombre_contacto as nombre, tel1_contacto as tel, direccion_contacto as dir, correo_contacto as mail',array('id_proveedor'=>$this->input->get('id')));
					$UIDataModal["content_view"]="proveedores_nuevo_view";
					$UIDataModal["close_button"]=true;
					$UIDataModal["classes"]="modal-lg";
					$UIDataModal["id"]="nuevo-proveedor-modal";
				}
				$this->load->view('template_modal',$UIDataModal); 
			}else{
				$UIDataModal["title"]="Nuevo proveedor";
				if(!filter_var($this->permisos['proveedores']['proveedores-crear'],FILTER_VALIDATE_BOOLEAN)){
					$UIDataModal['content_view']="error_noacceso_view";
				}else{
					$UIDataModal["content_view"]="proveedores_nuevo_view";
					$UIDataModal["close_button"]=true;
					$UIDataModal["classes"]="modal-lg";
					$UIDataModal["id"]="nuevo-proveedor-modal";
				}
					$this->load->view('template_modal',$UIDataModal); 
			}
		}
			/*Guardar proveedor*/
			function guardarproveedor(){
				$logo="";
				$UploadConf['upload_path']='./upload_images/';
				$UploadConf['allowed_types']='gif|jpg|png';
				$UploadConf['file_name']="img-".substr(md5(uniqid(time(), true)), 16);
				$this->load->library('upload', $UploadConf);
				if($this->upload->do_upload('logo_proveedor')){
					$uploadData = $this->upload->data();
					$logo="upload_images/".$uploadData['orig_name'];
					$this->load->library('image_lib');
					$config['image_library']='gd2';
					$config['source_image']=$logo;
					$config['maintain_ratio']=TRUE;
					$config['height']= 95;
					$config['width']=170;
					$this->image_lib->initialize($config);
					$this->image_lib->resize();
				}
				$proveedorData=array(
					'nombre_proveedor'=>$this->input->post('nombre_proveedor'),
					'razonsocial_proveedor'=>$this->input->post('razonsocial_proveedor'),
					'giro_proveedor'=>$this->input->post('giro_proveedor'),
					'clasificacion_proveedor'=>$this->input->post('clasificacion_cliente'),
					'nit_proveedor'=>$this->input->post('nit_proveedor'),
					'ncr_proveedor'=>$this->input->post('ncr_proveedor'),
					'direccion_proveedor'=>$this->input->post('direccion_proveedor'),
					'telefono_proveedor'=>$this->input->post('telefono_proveedor'),
					'web_proveedor'=>$this->input->post('web_proveedor'),
					'email_proveedor'=>$this->input->post('email_proveedor'),
					'logo_proveedor'=>$logo
				);
				if($this->input->post('id_proveedor') && $logo==""){
					unset($proveedorData['logo_proveedor']);
				}
				if($this->input->post('id_proveedor')){
					if($this->Generic_model->update('proveedores',$proveedorData,'id_proveedor',$this->input->post('id_proveedor'))){
						$this->Generic_model->delete('contactos','id_proveedor',$this->input->post('id_proveedor'));
						$contactos=json_decode($this->input->post('contactos'));
						$contactosData=array();
						if(count($contactos)>0){
							foreach($contactos as $contacto){
								$contactosData[]=array(
									'id_proveedor'=>$this->input->post('id_proveedor'),
									'nombre_contacto'=>$contacto->nombre_contacto,
									'tel1_contacto'=>$contacto->tel1_contacto,
									'direccion_contacto'=>$contacto->direccion_contacto,
									'correo_contacto'=>$contacto->correo_contacto
								);
							}
							echo $this->Generic_model->savebatch('contactos',$contactosData);
						}else{
							echo true;
						}
					}
				}else{
					$proveedor=$this->Generic_model->save('proveedores',$proveedorData,true);
					if($proveedor>0){
						$contactos=json_decode($this->input->post('contactos'));
						$contactosData=array();
						if(count($contactos)>0){
							foreach($contactos as $contacto){
								$contactosData[]=array(
									'id_proveedor'=>$proveedor,
									'nombre_contacto'=>$contacto->nombre_contacto,
									'tel1_contacto'=>$contacto->tel1_contacto,
									'direccion_contacto'=>$contacto->direccion_contacto,
									'correo_contacto'=>$contacto->correo_contacto
								);
							}
							echo $this->Generic_model->savebatch('contactos',$contactosData);
						}else{
							echo true;
						}
					}
				}
			}
			/*Detalles proveedor*/
			function detalles(){
				$proveedor=$this->Generic_model->get('proveedores','*',array('id_proveedor'=>$this->input->get('id')));
				$UIDataModal['proveedor']=$proveedor[0];
				$UIDataModal['contactos']=$this->Generic_model->get('contactos','nombre_contacto as nombre, tel1_contacto as tel, direccion_contacto as dir, correo_contacto as mail',array('id_proveedor'=>$this->input->get('id')));
				$UIDataModal['permiso_editarproveedor']=filter_var($this->permisos['proveedores']['proveedores-editar'],FILTER_VALIDATE_BOOLEAN);
				$UIDataModal['permiso_eliminarproveedor']=filter_var($this->permisos['proveedores']['proveedores-eliminar'],FILTER_VALIDATE_BOOLEAN);
				$this->load->view('proveedores_detalles_view',$UIDataModal);
				
			}
			function eliminar(){
				if(filter_var($this->permisos['proveedores']['proveedores-eliminar'],FILTER_VALIDATE_BOOLEAN)){
					echo $this->Generic_model->delete('proveedores','id_proveedor',$this->input->get('id'));
				}
			}
	/*------------------------- CREDITOS ----------------------*/
	function creditos(){
		$UIData['user_info']=$this->usuario;
		$UIData['section_title']="Cuentas por pagar";
		if(!filter_var($this->permisos['cuentasxpagar']['cuentasxpagar-ver'],FILTER_VALIDATE_BOOLEAN)){
			$UIData['main_view']="error_noacceso_view";
		}else{
			$UIData['main_view']="proveedores_creditos_view";
			$UIData['jsfiles']=array("miracle.deudas");
			$UIData['plugins']=array(
				array(
					"nombre"=>"datatables",
					"css"=> array('dataTables.bootstrap','dataTables.responsive','dataTables.tableTools.min'),
					"js"=> array('jquery.dataTables','dataTables.bootstrap.min','dataTables.responsive','dataTables.tableTools.min')
				),
				array(
					"nombre"=>"jquery_form",
					"js"=> array('jquery.form.min')
				),
				array(
					"nombre"=>"datapicker",
					"css"=>array('datepicker3'),
					"js"=>array('bootstrap-datepicker','locales/bootstrap-datepicker.es')
				),
			);
		}
		$this->load->view('template', $UIData);
	}
		function cargardeudas(){
			echo json_encode($this->Generic_model->get('deudas','deudas.id_proveedor as id,proveedores.nombre_proveedor as nombre, proveedores.razonsocial_proveedor as razon','','','',array('proveedores'=>'proveedores.id_proveedor=deudas.id_proveedor'),'','deudas.id_proveedor'));
		}
		function detallesdeudasxcproveedor(){
			$proveedor=$this->Generic_model->get('proveedores','*',array('id_proveedor'=>$this->input->get('id')));
			$deudas=$this->Generic_model->get('deudas','*',array('id_proveedor'=>$this->input->get('id')));
			$saldo=0;
			if(count($deudas)>0){
				foreach($deudas as $deuda){
					$saldo+=$deuda->saldo_deuda;
				}
			}
			$UIDataModal['proveedor']=$proveedor[0];
			$UIDataModal['deudas']=$deudas;
			$UIDataModal['saldo']=$saldo;	
			/*Permisos*/
			$UIDataModal['permiso_eliminarctaxpagar']=filter_var($this->permisos['cuentasxpagar']['cuentasxpagar-eliminar'],FILTER_VALIDATE_BOOLEAN);			
			$UIDataModal['permiso_exportarxpagar']=filter_var($this->permisos['cuentasxpagar']['cuentasxpagar-exportar'],FILTER_VALIDATE_BOOLEAN);			
			
			$this->load->view('proveedores_deudas_detalles_view',$UIDataModal);
		}
			function deudasdetalles(){
				if(!filter_var($this->permisos['cuentasxpagar']['cuentasxpagar-ver'],FILTER_VALIDATE_BOOLEAN)){
					$UIData['main_view']="error_noacceso_view";
					$UIData['structure_only']=true;
					$UIData['section_title']="Reporte de cr&eacute;ditos";
					$this->load->view('template', $UIData);
				}else{
					$UIDataModal["content_view"]="proveedores_deudas_deudasdetalles_view";
					$UIDataModal["title"] = "Dedatalle de credito";
					$UIDataModal["close_button"] = true;
					$UIDataModal["classes"] = "modal-lg";
					$UIDataModal["id"] = "deudas-detalles-modal";
					$deuda=$this->Generic_model->get('deudas','*',array('id_deuda'=>$this->input->get('id')),'','',array("proveedores"=>"proveedores.id_proveedor= deudas.id_proveedor"));
					$UIDataModal['deuda']=$deuda[0];		
					/*Permisos*/
					$UIDataModal['permiso_exportarxpagar']=filter_var($this->permisos['cuentasxpagar']['cuentasxpagar-exportar'],FILTER_VALIDATE_BOOLEAN);			
					$this->load->view('template_modal',$UIDataModal);
				}
			}
			
			function guardar_transaccion(){
				$fecha = gmdate('Y-m-d H:i:s', strtotime('- 6 hours'));
				
				$data = array(
					'id_deuda' => $this->input->post('id_deuda'),
					'fecha_transaccionxd' => $fecha,
					'ref_transaccionxd' => $this->input->post('ref_transaccionxd'),
					'tipo_transaccionxd' => $this->input->post('tipo_transaccionxd'),
					'monto_transaccionxd' => $this->input->post('monto_transaccionxd'),
					'saldo_transaccionxd' => $this->input->post('saldo_deuda')
				);
				
				$this->Generic_model->save('transaccionesxdeuda',$data);
				
				if($this->input->post('estado_deuda') == 0){
					$fechaDeuda = NULL;
				}else{
					$fechaDeuda = date("Y-m-d");
				}
				
				$dataDeuda = array(
					'estado_deuda' => $this->input->post('estado_deuda'),
					'monto_deuda' => $this->input->post('nuevo_monto_deuda'),
					'saldo_deuda' => $this->input->post('saldo_deuda'),
					'finalizacion_deuda' => $fechaDeuda,
				);
				
				$this->Generic_model->update('deudas',$dataDeuda,'id_deuda',$this->input->post('id_deuda'));
			}
			
			function cargar_transacciones(){
				$this->load->library("ssp");
	
				$table = 'transaccionesxdeuda';
				$primaryKey = 'id_transaccionxd';
				
				$columns = array(
					array(
						'db' => 'id_transaccionxd',
						'dt' => 'DT_RowId',
						'formatter' => function( $d, $row ) {
							return 'row_'.$d;
						}
					),
					array( 'db' => 'id_transaccionxd', 'dt' => 'id_transaccionxd' ),
					array(
						'db' => 'fecha_transaccionxd',
						'dt' => 'fecha_transaccionxd',
						'formatter' => function($d,$row){
							$dateConvert = explode('-',$d);
							$timeConvert = explode(' ',$dateConvert[2]);
							return $timeConvert[0].' de '.$this->TraducirMes($dateConvert[1]).' del '.$dateConvert[0].' a las '.$timeConvert[1];
						}
					),
					array( 'db' => 'tipo_transaccionxd', 'dt' => 'tipo_transaccionxd'),
					array( 'db' => 'ref_transaccionxd', 'dt' => 'ref_transaccionxd'),
					array(
						'db' => 'monto_transaccionxd',
						'dt' => 'cargo_transaccion',
						'formatter' => function($d,$row){
							if($row[3] == "0"){
								return $d;
							}else{
								return "-";
							}
						}
					),
					array(
						'db' => 'monto_transaccionxd',
						'dt' => 'abono_transaccion',
						'formatter' => function($d,$row){
							if($row[3] == "1"){
								return $d;
							}else{
								return "-";
							}
						}
					),
					array( 'db' => 'saldo_transaccionxd', 'dt' => 'saldo_transaccionxd' ),
				);
				$host =  explode(':',$this->db->hostname);
				$sql_details = array(
					'user' => $this->db->username,
					'pass' => $this->db->password,
					'db'   => $this->db->database,
					'host' => $host[0]
				);
				
				/*$joinQuery = "FROM `user` AS `u` JOIN `user_details` AS `ud` ON (`ud`.`user_id` = `u`.`id`)";
				$extraWhere = "`u`.`salary` >= 90000";*/
				$joinQuery = "";
				$extraWhere = "id_deuda = ".$this->input->post('idDeuda');
				 
				echo json_encode(
					$this->ssp->simple( $this->input->post(), $sql_details, $table, $primaryKey, $columns, $joinQuery, $extraWhere)
				);
			}
		function eliminardeuda(){
			if(filter_var($this->permisos['cuentasxpagar']['cuentasxpagar-eliminar'],FILTER_VALIDATE_BOOLEAN)){
				echo $this->Generic_model->delete('deudas','id_proveedor',$this->input->get('id'));
			}
		}
		function creditosxproveedormin(){
			$UIDataModal["content_view"]="proveedores_deudas_lista_min_view";
			$UIDataModal["title"] = "Seleccione un credito";
			$UIDataModal["close_button"] = true;
			$UIDataModal["classes"] = "modal-md";
			$UIDataModal["id"] = "proveedores-deudas-lista-min-modal";
			$UIDataModal['deudas']=$this->Generic_model->get('deudas','*',array('id_proveedor'=>$this->input->get('proveedor')));
			$this->load->view('template_modal',$UIDataModal);
		}
		function creditosxproveedordevmin(){
			$creditos=$this->Generic_model->get('deudas','*',array('id_proveedor'=>$this->input->get('proveedor')));
			$UIDataModal["content_view"]="proveedores_deudas_lista_mindev_view";
			$UIDataModal["title"] = "Seleccione un credito para abonar";
			$UIDataModal["close_button"] = true;
			$UIDataModal["classes"] = "modal-md";
			$UIDataModal["id"] = "proveedores-deudas-lista-min-modal";
			$UIDataModal['creditos']=$creditos;
			$this->load->view('template_modal',$UIDataModal);
		}
		function TraducirMes($month){
			switch($month){
				case '01':
						return $mes = 'Enero';
					break;
				case '02':
						return $mes = 'Febrero';
					break;
				case '03':
						return $mes = 'Marzo';
					break;
				case '04':
						return $mes = 'Abril';
					break;
				case '05':
						return $mes = 'Mayo';
					break;
				case '06':
						return $mes = 'Junio';
					break;
				case '07':
						return $mes = 'Julio';
					break;
				case '08':
						return $mes = 'Agosto';
					break;
				case '09':
						return $mes = 'Septiembre';
					break;
				case '10':
						return $mes = 'Octubre';
					break;
				case '11':
						return $mes = 'Noviembre';
					break;
				case '12':
						return $mes = 'Diciembre';
					break;
			}
		}
	function is_logged_in(){
		$session = $this->session->userdata('userInfo');
		$is_logged_in =$session['is_logged_in'];
		
		if(!isset($is_logged_in) || $is_logged_in !== true){
			redirect(base_url("login"));
			die();
		}
	}
}
?>