<?php
class Clientes 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 "Clientes!";}
	/*------------------------- LISTA ----------------------*/
	function lista(){
		$UIData['user_info']=$this->usuario;
		$UIData['section_title']	= "Clientes";
		if(!filter_var($this->permisos['clientes']['clientes-ver'],FILTER_VALIDATE_BOOLEAN)){
			$UIData['main_view']="error_noacceso_view";
		}else{
			$UIData['main_view']	= "clientes_lista_view";
			$UIData['jsfiles']=array("miracle.clientes");
			$UIData['plugins']=array(
				array(
					"nombre"=>"jquery_form",
					"js"=> array('jquery.form.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);
	}
		function listamini(){
			$UIDataModal["title"]= "Clientes";
			$UIDataModal["classes"] = "modal-md";
			if(!filter_var($this->permisos['clientes']['clientes-ver'],FILTER_VALIDATE_BOOLEAN)){
				$UIDataModal['content_view']="error_noacceso_view";
			}else{
				$UIDataModal['content_view']="clientes_lista_mini_view";
				$UIDataModal["field"]=$this->input->get("field");
				$UIDataModal["idfield"]=$this->input->get("idfield");
				$UIDataModal["duifield"]=$this->input->get("duifield");
				$UIDataModal["nitfield"]=$this->input->get("nitfield");
				$UIDataModal["nrcfield"]=$this->input->get("nrcfield");
				$UIDataModal["sender"]=$this->input->get("sender");
			}
			$this->load->view('template_modal',$UIDataModal); 
		}
		/*Cargar cliente*/
		function cargar(){
			$search=array("nombre_cliente"=>$this->input->get('search'));
			$orSearch=array("razonsocial_cliente"=>$this->input->get('search'));
			$limits=array(12=>$this->input->get('offset'));
			echo json_encode($this->Generic_model->get('clientes','id_cliente as id, nombre_cliente as nombre, razonsocial_cliente as razon, telefono1_cliente as tel,clasificacion_cliente as clasificacion,credito_cliente as credito,dui_cliente as dui,nit_cliente as nit,ncr_cliente as nrc','',array('nombre_cliente'=>'ASC'),$search,'',$limits,'',$orSearch));
		}
		function cargarhtml(){
			$search=array("nombre_cliente"=>$this->input->get('search'));
			$orSearch=array("razonsocial_cliente"=>$this->input->get('search'),"ncr_cliente"=>$this->input->get('search'));
			$limits=array(20=>$this->input->get('offset'));
			$clientes=$this->Generic_model->get('clientes','id_cliente as id, nombre_cliente as nombre, razonsocial_cliente as razon, telefono1_cliente as tel,clasificacion_cliente as clasificacion,credito_cliente as credito,dui_cliente as dui,nit_cliente as nit,ncr_cliente as nrc','',array('nombre_cliente'=>'ASC'),$search,'',$limits,'',$orSearch);
			if(count($clientes)>0){
				foreach($clientes as $cliente){
					echo "<tr id='cliente-".$cliente->id."' data-clasificacion='".$cliente->clasificacion."' data-credito='".$cliente->credito."' data-dui='".$cliente->dui."' data-nit='".$cliente->nit."' data-nrc='".$cliente->nrc."' style='"."height:65px;"."'><td><h4 class='noselecttext'>".$cliente->nombre."</h4><small class='noselecttext'>".$cliente->razon."</small></td><td class='contact-type noselecttext'><i class='fa fa-list-alt'></i></td><td class='noselecttext'> ".$cliente->nrc."</td></tr>"; 
				}
			}
		}
		/*Nuevo cliente*/
		function nuevo(){
			$mode=$this->input->get('mode');
			if($mode=='edit'){
				$UIDataModal["title"]="Editar cliente";
				if(!filter_var($this->permisos['clientes']['clientes-editar'],FILTER_VALIDATE_BOOLEAN)){
					$UIDataModal['content_view']="error_noacceso_view";
				}else{
					$UIDataModal['cliente']=$this->Generic_model->get('clientes','*',array('id_cliente'=>$this->input->get('id')));
					$UIDataModal["content_view"]="clientes_nuevo_view";
					$UIDataModal["close_button"] = true;
					$UIDataModal["classes"] = "modal-lg";
					$UIDataModal["id"] = "nuevo-cliente-modal";
				}
				$this->load->view('template_modal',$UIDataModal); 
			}else{
				$UIDataModal["title"]="Nuevo cliente";
				if(!filter_var($this->permisos['clientes']['clientes-crear'],FILTER_VALIDATE_BOOLEAN)){
					$UIDataModal['content_view']="error_noacceso_view";
				}else{
					$UIDataModal["content_view"]="clientes_nuevo_view";
					$UIDataModal["close_button"] = true;
					$UIDataModal["classes"] = "modal-lg";
					$UIDataModal["id"] = "nuevo-cliente-modal";
				}
				$this->load->view('template_modal',$UIDataModal); 
			}
		}
			/*Guardar cliente*/
			function guardarcliente(){
				$clienteData=array(
					'nombre_cliente'=>$this->input->post('nombre_cliente'),
					'dui_cliente'=>$this->input->post('dui_cliente'),
					'razonsocial_cliente'=>$this->input->post('razonsocial_cliente'),
					'giro_cliente'=>$this->input->post('giro_cliente'),
					'clasificacion_cliente'=>$this->input->post('clasificacion_cliente'),
					'nit_cliente'=>$this->input->post('nit_cliente'),
					'ncr_cliente'=>$this->input->post('ncr_cliente'),
					'telefono1_cliente'=>$this->input->post('telefono1_cliente'),
					'telefono2_cliente'=>$this->input->post('telefono2_cliente'),
					'telefono3_cliente'=>$this->input->post('telefono3_cliente'),
					'correo_cliente'=>$this->input->post('correo_cliente'),
					'direccion_cliente'=>$this->input->post('direccion_cliente')
				);
				if($this->input->post('id_cliente')){
					echo $this->Generic_model->update('clientes',$clienteData,'id_cliente',$this->input->post('id_cliente'));
				}else{
					echo $this->Generic_model->save('clientes',$clienteData);
				}
			}
		/*Detalles del cliente*/
		function detalles(){
			$cliente=$this->Generic_model->get('clientes','*',array('id_cliente'=>$this->input->get('id')));
			$UIDataModal['cliente']=$cliente[0];
			$UIDataModal['permiso_editarcliente']=filter_var($this->permisos['clientes']['clientes-editar'],FILTER_VALIDATE_BOOLEAN);
			$UIDataModal['permiso_editarEliminar']=filter_var($this->permisos['clientes']['clientes-eliminar'],FILTER_VALIDATE_BOOLEAN);
			$this->load->view('clientes_detalles_view',$UIDataModal);
		}
		/*Eliminar cliente*/
		function eliminar(){
			if(filter_var($this->permisos['clientes']['clientes-eliminar'],FILTER_VALIDATE_BOOLEAN)){
				echo $this->Generic_model->delete('clientes','id_cliente',$this->input->get('id'));
			}
		}
	/*Ingresar documentos de un cliente*/
	function ingresardocumentos(){
		$UIDataModal["content_view"]="clientes_documentos_ingresar_view";
		$UIDataModal["title"] = "Documentos de cliente";
		$UIDataModal["close_button"] = true;
		$UIDataModal["classes"] = "modal-sm";
		$UIDataModal["id"] = "clientes-documentos-ingresar-modal";
		$UIDataModal["field"]=$this->input->get('field');
		$UIDataModal["button"]=$this->input->get('button');
		$UIDataModal["dui"]=$this->input->get('dui');
		$UIDataModal["nit"]=$this->input->get('nit');
		$UIDataModal["nrc"]=$this->input->get('nrc');
		$UIDataModal["focus"]=$this->input->get('focus');
		$this->load->view('template_modal',$UIDataModal);
	}
	/*------------------------- CREDITOS ----------------------*/
	function creditos(){
		$UIData['user_info']=$this->usuario;
		$UIData['section_title']="Cuentas por cobrar";
		if(!filter_var($this->permisos['cuentasxcobrar']['cuentasxcobrar-ver'],FILTER_VALIDATE_BOOLEAN)){
			$UIData['main_view']="error_noacceso_view";
		}else{
			$UIData['main_view']="clientes_creditos_view";
			$UIData['jsfiles']=array("miracle.creditos");
			$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"=>"chosen",
					"css"=> array('chosen'),
					"js"=> array('chosen.jquery')
				),
				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);
	}
		/*cargar*/
		function cargarcreditos(){
			$search=array("nombre_cliente"=>$this->input->get('search'));
			$limits=array(12=>$this->input->get('offset'));
			//echo json_encode($this->Generic_model->get('clientes','id_cliente as id, nombre_cliente as nombre, razonsocial_cliente as razon',array('credito_cliente'=>1),array('nombre_cliente'=>'ASC'),$search,'',$limits));
			$clientes = $this->Generic_model->get('clientes','id_cliente as id, nombre_cliente as nombre, razonsocial_cliente as razon',array('credito_cliente'=>1),array('nombre_cliente'=>'ASC'),$search,'',$limits);
			
			if(count($clientes) > 0):
				foreach($clientes as $cliente):
					$creditos=$this->Generic_model->get('creditos','*',array('id_cliente'=>$cliente->id));
					$saldo=0;
					if(count($creditos)>0){
						foreach($creditos as $credito){
							$saldo+=$credito->saldo_credito;
						}
					}
				
					$clientes_saldo[] = array(
						"id" => $cliente->id,
						"nombre" => $cliente->nombre,
						"razon" => $cliente->razon,
						"saldo" => number_format($saldo,2)
					);
				endforeach;
				
				
			endif;
			
			echo json_encode ($clientes_saldo);
		}
		/*------ Nuevo credito ------*/
		function nuevocredito(){
			$UIDataModal["title"] = "Autorizar cr&eacute;dito";
			if($this->input->get('mode')=="edit"){
				if(!filter_var($this->permisos['cuentasxcobrar']['cuentasxcobrar-modificar'],FILTER_VALIDATE_BOOLEAN)){
					$UIDataModal['content_view']="error_noacceso_view";
				}else{
					$UIDataModal["close_button"] = true;
					$UIDataModal["classes"] = "";
					$UIDataModal["id"] = "nuevo-credito-modal";
					$UIDataModal["clientes"]=$this->Generic_model->get('clientes','id_cliente as id, nombre_cliente as nombre, razonsocial_cliente as razon, limite_credito_cliente as limite',array('id_cliente'=>$this->input->get('id')));
					$UIDataModal["saldo"]=$this->input->get('saldo');
					$UIDataModal["content_view"] =  "clientes_creditos_nuevo_view";
				}
			}else{
				if(!filter_var($this->permisos['cuentasxcobrar']['cuentasxcobrar-autorizar'],FILTER_VALIDATE_BOOLEAN)){
					$UIDataModal['content_view']="error_noacceso_view";
				}else{
					$UIDataModal["close_button"] = true;
					$UIDataModal["classes"] = "";
					$UIDataModal["id"] = "nuevo-credito-modal";
					$UIDataModal["clientes"] = $this->Generic_model->get('clientes','id_cliente as id, nombre_cliente as nombre, razonsocial_cliente as razon',array('credito_cliente !='=>1),array('nombre_cliente'=>'ASC'));
					$UIDataModal["content_view"] =  "clientes_creditos_nuevo_view";
				}
			}
			$this->load->view('template_modal',$UIDataModal); 
		}
		/*guardarcredito*/
		function guardarcredito(){
			$creditoData=array(
				"credito_cliente"=>1,
				"limite_credito_cliente"=>$this->input->post('limite_credito_cliente')
				);
			echo $this->Generic_model->update('clientes',$creditoData,'id_cliente',$this->input->post('id_cliente'));
		}
		/*detalles creditos*/
		function detallescreditoxcliente(){
			$cliente=$this->Generic_model->get('clientes','*',array('id_cliente'=>$this->input->get('id')));
			$creditos=$this->Generic_model->get('creditos','*',array('id_cliente'=>$this->input->get('id'),'estado_credito <'=>'2'));
			$saldo=0;
			if(count($creditos)>0){
				foreach($creditos as $credito){
					$saldo+=$credito->saldo_credito;
				}
			}
			$UIDataModal['cliente']=$cliente[0];
			$UIDataModal['creditos']=$creditos;			
			$UIDataModal['saldo']=$saldo;	
			/*Permisos*/
			$UIDataModal['permiso_eliminarctaxcobrar']=filter_var($this->permisos['cuentasxcobrar']['cuentasxcobrar-eliminar'],FILTER_VALIDATE_BOOLEAN);
			$UIDataModal['permiso_modificarxcobrar']=filter_var($this->permisos['cuentasxcobrar']['cuentasxcobrar-modificar'],FILTER_VALIDATE_BOOLEAN);
			$UIDataModal['permiso_exportarxcobrar']=filter_var($this->permisos['cuentasxcobrar']['cuentasxcobrar-exportar'],FILTER_VALIDATE_BOOLEAN);
			$this->load->view('clientes_creditos_detalles_view',$UIDataModal);
		}
			function creditosdetalles(){
				if(!filter_var($this->permisos['cuentasxcobrar']['cuentasxcobrar-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"]="clientes_creditos_creditosdetalles_view";
					$UIDataModal["title"] = "Dedatalle de credito";
					$UIDataModal["close_button"] = true;
					$UIDataModal["classes"] = "modal-lg";
					$UIDataModal["id"] = "credito-detalles-modal";
					$UIDataModal["saldototal"] = $this->input->get('saldototal');
					/*Permisos*/
					$UIDataModal['permiso_exportarxcobrar']=filter_var($this->permisos['cuentasxcobrar']['cuentasxcobrar-exportar'],FILTER_VALIDATE_BOOLEAN);
					
					$credito=$this->Generic_model->get('creditos','*',array('id_credito'=>$this->input->get('id')),'','',array("clientes"=>"clientes.id_cliente = creditos.id_cliente"));
					$UIDataModal['credito']=$credito[0];
					$this->load->view('template_modal',$UIDataModal);
				}	
			}
			function guardar_transaccion(){
				$fecha = gmdate('Y-m-d H:i:s', strtotime('- 6 hours'));
				
				$data = array(
					'id_credito' => $this->input->post('id_credito'),
					'fecha_transaccion' => $fecha,
					'ref_transaccion' => $this->input->post('ref_transaccion'),
					'tipo_transaccion' => $this->input->post('tipo_transaccion'),
					'monto_transaccion' => $this->input->post('monto_transaccion'),
					'saldo_transaccion' => $this->input->post('saldo_credito')
				);
				
				$this->Generic_model->save('transaccionesxcredito',$data);
				
				if($this->input->post('tipo_transaccion')==1){
					/*Impresión recibo*/
					$receiptData['fecha']=$fecha;
					$receiptData['cliente']=$this->input->post('nombre_cliente');
					$receiptData['monto']=$this->input->post('monto_transaccion');
					$receiptData['concepto']=$this->input->post('ref_transaccion');
					$this->load->view('impresos/transacciones_credito_recibo_view',$receiptData);
				}
				
				if($this->input->post('estado_credito') == 0){
					$fechaCredito = NULL;
				}else{
					$fechaCredito = date("Y-m-d");
				}
				
				$dataCredito = array(
					'estado_credito' => $this->input->post('estado_credito'),
					'monto_credito' => $this->input->post('nuevo_monto_credito'),
					'saldo_credito' => $this->input->post('saldo_credito'),
					'finalizacion_credito' => $fechaCredito,
				);
				
				$this->Generic_model->update('creditos',$dataCredito,'id_credito',$this->input->post('id_credito'));
			}
			function cargar_transacciones(){
				$this->load->library("ssp");
	
				$table = 'transaccionesxcredito';
				$primaryKey = 'id_transaccion';
				
				$columns = array(
					array(
						'db' => 'id_transaccion',
						'dt' => 'DT_RowId',
						'formatter' => function( $d, $row ) {
							return 'row_'.$d;
						}
					),
					array( 'db' => 'id_transaccion', 'dt' => 'id_transaccion' ),
					array(
						'db' => 'fecha_transaccion',
						'dt' => 'fecha_transaccion',
						'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_transaccion', 'dt' => 'tipo_transaccion' ),
					array( 'db' => 'ref_transaccion', 'dt' => 'ref_transaccion' ),
					array(
						'db' => 'monto_transaccion',
						'dt' => 'cargo_transaccion',
						'formatter' => function($d,$row){
							if($row[3] == "0"){
								return $d;
							}else{
								return "-";
							}
						}
					),
					array(
						'db' => 'monto_transaccion',
						'dt' => 'abono_transaccion',
						'formatter' => function($d,$row){
							if($row[3] == "1"){
								return $d;
							}else{
								return "-";
							}
						}
					),
					array( 'db' => 'saldo_transaccion', 'dt' => 'saldo_transaccion' ),
				);
				$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_credito = ".$this->input->post('idCredito');
				 
				echo json_encode(
					$this->ssp->simple( $this->input->post(), $sql_details, $table, $primaryKey, $columns, $joinQuery, $extraWhere)
				);
			}
		/*Eliminar credito*/
		function eliminarcredito(){
			if(filter_var($this->permisos['cuentasxcobrar']['cuentasxcobrar-eliminar'],FILTER_VALIDATE_BOOLEAN)){
				$creditoData=array(
					"credito_cliente"=>0,
					"limite_credito_cliente"=>NULL
					);
				if($this->Generic_model->update('clientes',$creditoData,'id_cliente',$this->input->get('id'))){
					echo $this->Generic_model->delete('creditos','id_cliente',$this->input->get('id'));
				};
			}
		}
		
		/**/
		function getcreditodisponible(){
			$infoCredito=$this->Generic_model->get('clientes','limite_credito_cliente as limite',array('id_cliente'=>$this->input->get('cliente')));
			$creditos=$this->Generic_model->get('creditos','*',array('id_cliente'=>$this->input->get('cliente')));
			$saldo=0;
			if(count($creditos)>0){
				foreach($creditos as $credito){
					$saldo+=$credito->saldo_credito;
				}
			}
			echo $infoCredito[0]->limite-$saldo;
		}
		function creditosxclientemin(){
			$creditos=$this->Generic_model->get('creditos','*',array('id_cliente'=>$this->input->get('cliente'),'estado_credito<'=>'2'));
			$id=$this->input->get("id");
			$saldo=0;
			$UIDataModal['creditos']=$creditos;
			$UIDataModal['id']=$id;
			$this->load->view('clientes_creditos_lista_min_view',$UIDataModal);
		}
		function creditosxclientedevmin(){
			$creditos=$this->Generic_model->get('creditos','*',array('id_cliente'=>$this->input->get('cliente')));
			$id=$this->input->get("id");
			$saldo=0;
			$UIDataModal['creditos']=$creditos;
			$UIDataModal['id']=$id;
			$this->load->view('clientes_creditos_lista_min_view',$UIDataModal);
		}
		function getventascreditoxcliente(){
			$ventasSel="ventas.id_venta as id,ventas.fecha_venta as fecha,ventas.cobro_venta as condicion,ventas.documento_venta as documento,ventas.num_documento_venta as numdoc";
			$ventasSel.=",ventas.subtotal_venta as subtotal,ventas.total_exento_venta as exento,ventas.total_nosujeto_venta as nosujeto,ventas.iva_venta as iva,ventas.percepcion_venta as percepcion,ventas.retencion_venta as retencion";
			$ventasSel.=",(ventas.subtotal_venta+total_exento_venta+total_nosujeto_venta) as netototal,(iva_venta-retencion_venta+percepcion_venta) as impuestos,(ventas.subtotal_venta+total_exento_venta+total_nosujeto_venta+iva_venta-retencion_venta+percepcion_venta) as total";
			$ventasSel.=",resoluciones_caja.serie_autorizada as serie,transaccionesxcredito.id_credito as credito,clientes.clasificacion_cliente as cliente_clasificacion";
			$ventasSel.=",ventas.id_vendedor as vendedor_id,usuarios.username_usuario as vendedor";
			$ventasWhere=array("ventas.id_cliente"=>$this->input->get("cliente"),"estado_cobro <"=>2,"estado_venta"=>1);
			$ventas=$this->Generic_model->get("ventas",$ventasSel,$ventasWhere,array("fecha_venta"=>"ASC"),'',array('resoluciones_caja'=>'resoluciones_caja.id_resolucion=ventas.id_resolucion, LEFT','transaccionesxcredito'=>'transaccionesxcredito.id_venta=ventas.id_venta, LEFT','usuarios'=>'usuarios.id_usuario=ventas.id_vendedor, LEFT','clientes'=>'clientes.id_cliente=ventas.id_cliente,LEFT'));
			if(count($ventas)>0){
				foreach($ventas as $venta){
					$doc="Desconocido";
					switch($venta->documento){
						case 0:$doc="Ninguno";break;
						case 1:$doc="Factura";break;
						case 2:$doc="Comprobante de Cr&eacute;dito Fiscal";break;
						case 3:$doc="Ticket";break;
						case 4:$doc="Nota de remisi&oacute;n";break;
						case 5:$doc="Nota de env&iacute;o";break;
					}
					$credito=($venta->credito==""?"N/A":$venta->credito);
					$productos=$this->Generic_model->get('salida_productos','salida_productos.id_salida as idsal,productos.id_producto as id,presentaciones.id_presentacion as id_pre,presentaciones.desc_presentacion as nombre,productos.tipo_venta as tipo,productos.producto_interno as interno,salida_productos.cant_salida as cant,(salida_productos.cant_salida*salida_productos.costo_salida) as total',array('id_venta'=>$venta->id),'','',array('presentaciones'=>'presentaciones.id_presentacion=salida_productos.id_presentacion','productos'=>'productos.id_producto=salida_productos.id_producto'));

					echo "<div class='panel panel-default' id='doc-".$venta->id."' data-condicion='".$venta->condicion."' data-credito='".$venta->credito."' data-doc='".$venta->documento."' data-vendedor='".$venta->vendedor_id."' data-numdoc='".$venta->numdoc."' data-total='".$venta->total."'>"; 
					echo "<div class='panel-heading clearfix'>";
					echo "<a aria-expanded='false' class='collapsed' data-toggle='collapse' data-parent='#pago-credito-creditosr' href='#documento-".$venta->id."' style='color:#333'>";
					echo "<div class='col-sm-7'><h5>".$doc.": ".$venta->serie." ".$venta->numdoc."</h5><span class='text-mutted'>".date("d-m-Y H:i:s", strtotime($venta->fecha))."<br><small><strong>Ref</strong>: V-".$venta->id."  -  <strong>Credito</strong>: ".$credito." <strong>Condici&oacute;n:</strong> ".($venta->condicion==1?'Cr&eacute;dito':'A cobro')."</small></div>";
					echo "<div class='col-sm-3'><h5> $".$venta->total."</h5><small>".$venta->vendedor	."</small></div></a>";
					echo "<div class='col-sm-2'><button class='btn btn-info agregar-documento-all-btn'><i class='fa fa-arrow-circle-right fa-2x'></i></button></div>";
					echo "</div>";
					echo "<div id='documento-".$venta->id."' class='panel-collapse collapse'  aria-expanded='false'>";
					echo "<table class='table documento-items'>";
					echo "<thead><tr><th>Cant.</th><th>Descripci&oacute;n</th><th>Total</th><th></th></tr>";
					echo "</thead><tbody>";
					if(count($productos)>0){
						foreach($productos as $producto){
							if((int)$venta->cliente_clasificacion==4 && (int)$producto->tipo==0){
								$producto->tipo=3;
							}
							$iva=0;
							if($venta->iva>0 && $producto->tipo==0){$iva=$venta->iva*($producto->total/$venta->subtotal);}
							$rentencion=0;
							if($venta->retencion>0 && $producto->tipo==0){$rentencion=$venta->retencion*($producto->total/$venta->subtotal);}
							$percepcion=0;
							if($venta->percepcion>0 && $producto->tipo==0){$percepcion=$venta->percepcion*($producto->total/$venta->subtotal);}
							echo "<tr data-salida='".$producto->idsal."' data-id='".$producto->id."' data-pre='".$producto->id_pre."' data-tipo='".$producto->tipo."' data-interno='".$producto->interno."'>";
							echo "<td class='item-cant-field' data-value='".$producto->cant."'>".$producto->cant."</td>";
							echo "<td class='item-desc-field' data-value='".$producto->nombre."'>".$producto->nombre."</td>";
							echo "<td class='item-total-field' data-iva='".$iva."' data-retencion='".$rentencion."' data-percepcion='".$percepcion."' data-value='".$producto->total."'>".$producto->total."</td>";
							echo "<td class='item-btn-field'><button style='display:none;' class='btn btn-xs btn-info agregar-documento-item-btn'><i class='fa fa-arrow-right '></i></button></td>";
							echo "</tr>";
						}
					}			
					echo "</tbody></table>";
					echo "<table class='doc-totales-wrapper'><tbody>";
					echo "<tr class='doc-totales-netos'><td class='col-md-10 text-right'>Total Neto $</td><td class='col-md-2 total-field' data-grabado='".$venta->subtotal."' data-exento='".$venta->exento."' data-nosujeto='".$venta->nosujeto."' data-value='".$venta->netototal."'>".$venta->netototal."</td></tr>";
					echo "<tr class='doc-totales-impuestos'><td class='col-md-10 text-right'>Impuestos $</td><td class='col-md-2 total-field' data-iva='".$venta->iva."' data-retencion='".$venta->retencion."' data-percepcion='".$venta->percepcion."' data-value='".$venta->impuestos."'>".$venta->impuestos."</td></tr>";
					echo "<tr class='doc-totales-total'><td class='col-md-10 text-right'>TOTAL $</td><td class='col-md-2 total-field' data-value='".$venta->total."'>".$venta->total."</td></tr>";
					echo "</tbody></table>";
					echo "</div></div>";
				}
			}else{
				echo "No hay resultados";
			}
		}
		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();
			}
		}
}
?>