<?php		

//ini_set('display_errors',1);

session_start();


require_once ("../../config/Cado.php");
require_once ("../../config/Datos.php");

require_once ("../producto/cCatalogo.php");
$oCatalogo = new cCatalogo();
require_once("../producto/cProductomarcacodigo.php");
$oProductomarcacodigo = new cProductomarcacodigo();

require_once ("../formatos/formato.php");

if(isset($_SESSION['venta_catid'])){
	$num_rows=count($_SESSION['venta_catid']);
	if($num_rows==0)$num_rows="";
}else{
	$num_rows="";
}



if($_SESSION['puntoventa_tipope']==2){
	
	$app_igv_val = 1;
	$app_igv_sub = 1;
	$app_igv_igv = 1;
}

/* echo '---'.$app_igv_val;
echo '---'.$app_igv_sub;
echo '---'.$app_igv_igv; */

?>

<style>
	#tabla_venta_car td{
		vertical-align: middle;
		padding: 4px 4px !important;
	}
	#tabla_venta_car td.editable,#tabla_venta_car td.editable *{
		cursor: text !important;
		height: 100%; 
		border-bottom-color: #ccc;
		border-bottom-style: dashed; 
		border-bottom-width: 0.5px;
	}
	#tabla_venta_car td.editando{
		background-color: rgba(18, 180, 243, 0.05);
		outline: 2px solid #35A4F3;
	}
	#tabla_venta_car td input{
		height: 100%;
		width: 100%;
		box-sizing: border-box;
		display: inline-block;
		border: none;
		background: transparent;
	}
	#tabla_venta_car td input:focus{
		background: transparent;
		height: 100%;
		width: 100%;
		outline: none;
		border: none;
	}
	#tabla_venta_car td input[readonly]{
		background: transparent;
	}
</style> 

<?php 
//if($_POST['vista']=='cotizacion'){
?>	
	
	
	
<?php 
// }else {}
?>
<div class="col-lg-12 col-sm-12 col-12">
<div class="row">
<div class="col-lg-8 col-sm-12 col-12">
 <div class="table-responsive">
 
<div class="col-lg-12 col-md-12 col-12">	
	<input name="hdd_ven_numite" id="hdd_ven_numite" type="hidden" value="<?php echo $num_rows?>">


	<table id="tabla_venta_car" class="table table-bordered table-striped">
		<thead>
			<tr>
				<th>CÓDIGO</th>
			<!--	<th nowrap style="width:50px;" >ESTADO</th>
			-->	
				<th nowrap >ARTÍCULO</th>
				<th nowrap >LABORATORIO</th>
				<th nowrap >EMPAQUE</th>
				<th align="right">CAN</th>
				<th align="right" style="background-color:#3B71CA;color:#fff" >P. UNI.</th>		
				<th align="right" >P. TOTAL</th>
				<th width="25">&nbsp;</th>
			</tr>
		</thead>		 

		<tbody>
			<?php 
			
			$total = 0;
			if($num_rows>0){
				$banrojo = true;
				foreach($_SESSION['venta_catid'] as $indice=>$cantidad) {

				
			$dts1=$oCatalogo->mostrarUno($_SESSION['venta_catid'][$indice],$_SESSION['venta_marid'][$indice]);
			$dt1 = mysqli_fetch_array($dts1);
			
			$pro_des =  $dt1['tb_producto_des'];
			$emp_fac =  $dt1['tb_empaque_fac'];
			$preven =  $dt1['tb_productomarca_preven'];
			$prevenf =  $dt1['tb_productomarca_prevenf'];
			
			$cantidad=$_SESSION['venta_can'][$indice];
			$can=$_SESSION['venta_can'][$indice];

			list($cane,$canf) = explode('F',$can);
		
			//echo $cane.'-' ; 
			//echo $canf.'-' ; 
			
			if($cane!=="" && $canf==""){ 
				
				$can = $cane;
			}else if($cane=="" && $canf!==""){ 
				
				$can = $canf;
			}
			else if($cane!=="" && $canf!==""){ 
				$cane = $cane*$emp_fac;
				$can = $cane + $canf;
			}
			
		
			//echo 'can'.$can ; 

			
			$pre_uni=$_SESSION['venta_preven'][$indice];
			$des_uni=$_SESSION['venta_des'][$indice];
			//$pronom=$_SESSION['venta_pronom'][$indice];
			$pronom=$dt1['tb_producto_nom'];
			
			$valor_uni = $pre_uni / $app_igv_sub;
			$valor_uni = $valor_uni;
			$igv_uni = $valor_uni * $app_igv_igv;
				
if($_SESSION['puntoventa_tipope']==2){
    $igv_uni = 0;
}
			//	echo $valor_uni;
			//		echo $igv_uni;
					
			$val_tot = $valor_uni * $can;		
			$igv_tot = $igv_uni * $can;		
			$pre_tot = $val_tot + $igv_tot;
			
			$total_val	+=$val_tot;			
			$total_igv	+=$igv_tot;			
			$total	+=$pre_tot;			
			
			
			$can_tot += $can;
			$valuni_de = number_format($valor_uni,2);
			$igvuni_de = $valuni_de * $app_igv_igv;
			
			$valtot_de = $valuni_de * $can;		
			$igvtot_de = $igvuni_de * $can;		
			$pretot_de = $valtot_de + $igvtot_de;		
			
			
			$valuni_sun += $valuni_de;
			$igvuni_sun += $igvuni_de;
			$valtot_sun += $valtot_de;
			$igvtot_sun += $igvtot_de;
			$pretot_sun += $pretot_de;


			$dif_val = $total_val - $valtot_sun;
			$dif_igv = $total_igv - $igvtot_sun;
			$dif_tot = $total - $pretot_sun;
			
			/* 
			$rscod = $oProductomarcacodigo->mostrarUno($dt1['tb_catalogo_id'],'1');
			$dtcod = mysqli_fetch_array($rscod);
			
			$codpri = $dtcod['tb_productomarcacodigo_cod']; */
				
			if($_SESSION['venta_est'][$indice]=='1'){
				$color = '';
			}else if($_SESSION['venta_est'][$indice]=='2'){
				$color="text-red";
			}	
			
			if($pre_tot<=0){
				$banrojo = false;
			}
		
		//echo $pro_des;
		
			?>
			
			<tr  >
						<td ><?php echo $dt1['tb_producto_codint']; ?></td>
				
						<td nowrap style="font-size:10pt; font-weight:bold;cursor:pointer;" <?php if($pro_des!="") echo 'title="'.$pro_des.'"'; ?>   " 
						data-toggle="tooltip" data-placement="top" ><?php echo $pronom; ?></td>
						<td style="font-weight:bold" nowrap ><?php echo $dt1['tb_marca_nom']?></td>
						<td style="font-weight:bold" nowrap ><?php echo $dt1['tb_empaque_nom']?></td>
						
			
			<td align="right" width="50" class="editable" style="font-size:9pt; font-weight:bold">
				<input type="text" value="<?php echo $cantidad ?>" data-can="<?php echo $cantidad ?>"  data-cantidad="<?php echo $can ?>" 
				data-original="<?php echo $cantidad ?>" readonly data-cat_id="<?php echo $dt1['tb_catalogo_id'] ?>"
				data-tipdes="<?php echo $tipdes ?>" data-est="<?php echo $_SESSION['venta_est'][$indice];?>" 
				data-mar_id ="<?php echo $dt1['tb_marca_id'] ?>" class="" style="text-align: right;font-size:1rem;">
			</td>
			
		<?php  if ($_SESSION['usuariogrupo_id']=='1' || $_SESSION['usuariogrupo_id']=='2'){  ?>
			<td align="right" width="80"  class="editable" style="font-size:9pt; font-weight:bold; <?php if($pre_tot<=0){ echo 'background-color:#B71C1C;color:#fff ';}else {echo 'border: 2px solid #3B71CA; '; } ?>">
				<?php //echo formato_money($pre_uni) ?>
				
				<input type="text" value="<?php echo formato_money4($pre_uni) ?>" 
				data-preven="<?php echo formato_money($pre_uni) ?>"  data-tip = "preuni"
				data-original="<?php echo formato_money($pre_uni) ?>" 
				data-tipdes="<?php echo $tipdes ?>" 
				data-est="<?php echo $_SESSION['venta_est'][$indice];?>"
				data-mar_id ="<?php echo $dt1['tb_marca_id'] ?>" readonly 
				data-cat_id="<?php echo $dt1['tb_catalogo_id'] ?>" class="<?php if($pre_tot<=0){echo 'text-white';}else{ echo 'text-dark'; } ?>"  style="text-align: right;font-size:1rem;">
						
			</td>
			
			<?php }else{
			?>
			
			<td align="right" nowrap ><?php echo formato_money4($pre_uni)?></td>
			
			<?php 
		}?>
		
	<?php  if ($_SESSION['usuariogrupo_id']=='1' || $_SESSION['usuariogrupo_id']=='2'){  ?>
			<td align="right" width="100" class="editable" style="font-size:12pt; font-weight:bold;<?php if($pre_tot<=0) echo 'background-color:#B71C1C;color:#fff '; ?>">
							<input type="text" value="<?php echo formato_money($pre_tot) ; ?>" 
							data-original="<?php echo formato_money($pre_tot) ?>" 
							data-cantidad="<?php echo $can ?>" data-tip = "pretot" 
							data-cat_id="<?php echo $dt1['tb_catalogo_id'] ?>" 
							data-mar_id ="<?php echo $dt1['tb_marca_id'] ?>"
							data-est="<?php echo $_SESSION['venta_est'][$indice];?>"
							data-des="<?php echo formato_money($des_uni) ?>"
							readonly  class="<?php if($pre_tot<=0){echo 'text-white';}else{ echo 'text-dark'; } ?>" 
							style="text-align: right;font-size:1rem;">
			</td>
				<?php }else{
			?>
			
			<td align="right" nowrap ><?php echo formato_money($pre_tot)?></td>
			
			<?php 
		}?>
						
						<td align="center" nowrap="nowrap"> 
						<!--	<span  title="Editar" class="btn btn-primary btn-sm btn_editar" ><i class="fa fa-pencil"></i></span>
							-->
							<span data-indice ="<?php echo $indice; ?>"  style="cursor:pointer" class="btn btn-danger btn-sm btn_eliminar" ><i class="fa fa-times"></i></span> 		
						<!--	<span class="btn btn-primary btn-sm" id="demo-ajax_<?php echo $dt1['tb_catalogo_id'] ?>" ><i class="fa fa-info"></i></span> 	
						-->
						</td>				
					</tr>
			
			
			<?php
					mysqli_free_result($dts1);
				}
				
				
				//echo '--'.$app_igv_sub;
				$total_valorventa =$total/$app_igv_sub;
				//echo '--'.$total_valorventa;
				
				$total_igv	= $total_valorventa * $app_igv_igv;
				
				if($_SESSION['puntoventa_tipope']==2){
		        	$total_igv	= 0;
		        }
			
				
			}
			?>
		</tbody>
		
		
		<tr >
						<td colspan="1" ></td>
						<td colspan="" align="right" class=""><?php  ?></td>
						<td colspan="" align="right" class=""><?php  ?></td>
						<td colspan="" class=""><?php  ?></td>
						<td colspan="" align="right" class=""  ><?php ?></td>
						<td colspan="" align="right" class=""  ><?php ?></td>
						<td colspan="" align="right" class=""  ><?php echo formato_money($total); ?></td>
						<td colspan="" class="" ></td>
						
						
		</tr>	
		
		<!--
		<tr >
						<td colspan="1" >SUNAT</td>
						<td colspan="3" class="bg-red">ERROR MAXIMO DE CALCULO PERMITIDO POR SUNAT  - 1.00 SOL</td>
						<td colspan="" align="right" class=""><?php echo $can_tot; ?></td>
						<td colspan="" align="right" class=""><?php echo formato_money($valuni_sun); ?></td>
						<td colspan="" class=""><?php echo ''; ?></td>
						<td colspan="" align="right" class=""  ><?php echo formato_money($valtot_sun); ?></td>
						<td colspan="" align="right" class=""  ><?php echo formato_money($igvtot_sun); ?></td>
						<td colspan="" align="right" class=""  ><?php echo formato_money($pretot_sun); ?></td>
						<td colspan="" class="" ></td>
						
						
		</tr>				
		
		<tr >
						<td colspan="7" >DIFERENCIAS</td>
						<td colspan="" align="right" style="<?php if(abs($dif_val)>=1) echo 'background-color:#D50000;color:#fff; '; else echo 'background-color:#00838F;color:#fff; '; ?>"  ><?php echo number_format(abs($dif_val),4); ?></td>
						<td colspan="" align="right" style="<?php if(abs($dif_igv)>=1) echo 'background-color:#D50000;color:#fff; '; else echo 'background-color:#00838F;color:#fff; '; ?>" ><?php echo number_format(abs($dif_igv),4); ?></td>
						<td colspan="" align="right" style="<?php if(abs($dif_tot)>=1) echo 'background-color:#D50000;color:#fff; '; else echo 'background-color:#00838F;color:#fff; '; ?>"  ><?php echo number_format(abs($dif_tot),4);; ?></td>
						<td colspan="" class="" ></td>	
		</tr>	
-->

	</table>
	
	<?php 
	if($num_rows=="" or $num_rows==0)
		echo 'Ningún producto agregado. <input type="hidden" id="evaluar_cantidad_items_venta" value="'.$cantidad_productos.'">';
	if($num_rows==1)
		echo $num_rows.' producto agregado. <input type="hidden" id="evaluar_cantidad_items_venta" value="'.$cantidad_productos.'">';
	if($num_rows>=2)
		echo $num_rows.' productos agregados. <input type="hidden" id="evaluar_cantidad_items_venta" value="'.$cantidad_productos.'">';
		//echo 'Diferencia '.abs($dif);
	
	/* echo '<br />'.$oferta_menu; */
	?>

</div>
</div>		
</div>		


<input name="txt_ven_valven" type="hidden"class="form-control form-control-lg" id="txt_ven_valven" style="text-align:right;font-weight: bold;" value="<?php echo formato_money($total_valorventa)?>"  > 		

<input name="txt_ven_igv" type="hidden" class="form-control form-control-lg" id="txt_ven_igv" style="text-align:right;font-weight: bold;" value="<?php echo formato_money($total_igv)?>"   > 

<input name="txt_ven_tot" type="hidden" class="form-control form-control-lg" id="txt_ven_tot" style="color:#D50000;text-align:right;font-weight: bold;" value="<?php echo formato_money($total)?>" > 



<input name="txt_ven_des" type="hidden" class="form-control form-control-lg" id="txt_ven_des" style="text-align:right;font-weight: bold;" value="<?php echo formato_money($des_tot)?>"   > 


<div class="col-lg-4 col-sm-12 col-12">
<div class="row">

<div class="col-lg-12 col-sm-12 col-12">
							<div class="row">

							<div class="col-lg-4 col-sm-4 col-4">
								<label>SUBTOTAL:</label>
								<input name="txt_ven_valven1" readonly type="text"class="form-control form-control-lg" id="txt_ven_valven1" style="text-align:right;font-weight: bold;" value="<?php echo formato_money($total_valorventa)?>"  > 							
							</div>
						
							<div class="col-lg-4 col-sm-4  col-4">
								<label>IGV:</label>
								<input name="txt_ven_igv1" readonly type="text" class="form-control form-control-lg" id="txt_ven_igv1" style="text-align:right;font-weight: bold;" value="<?php echo formato_money($total_igv)?>"   > 
							</div>
							<div class="col-lg-4 col-sm-4  col-6 d-none">
								<label>DSCT:</label>
								<input name="txt_ven_des1" readonly type="text" class="form-control form-control-lg" id="txt_ven_des1" style="text-align:right;font-weight: bold;" value="<?php echo formato_money($des_tot)?>"   > 
							</div>	
							<div class="col-lg-4 col-sm-4  col-4">
								<label>TOTAL:</label>
								<input name="txt_ven_tot1" readonly type="text" class="form-control form-control-lg" id="txt_ven_tot1" style="color:#D50000;text-align:right;font-weight: bold;" value="<?php echo formato_money($total)?>" > 
							</div>
							
							</div>
</div>

<div class="col-lg-12 col-sm-12 col-12  " style="height:10px;"></div>

<div class="col-lg-12 col-sm-12 col-12  ">
						<div class="row">

							<div class="col-lg-6 col-sm-6 col-6 ">
								<label>Recibi:</label>
								<input name="txt_ven_recibi" type="text"class="form-control form-control-lg" autocomplete = "off" id="txt_ven_recibi" style="text-align:right;font-weight: bold;" value="<?php echo '' ?>"  > 							
							</div>
						
							<div class="col-lg-6 col-sm-6  col-6 ">
								<label>Vuelto</label>
								<input name="txt_ven_vuelto" readonly  type="text" placeholder="INGRESE MONTO VALIDO" class="form-control form-control-lg" id="txt_ven_vuelto" style="color:#F44336;text-align:right;font-weight: bold;" value="<?php echo '' ?>"   > 
							</div>
							
						</div>
</div>	


</div>	
</div>	
</div>	

</div>	
		



<script type="text/javascript" src="../cotizacion/NumberFormat.js"></script>

<script type="text/javascript" >


	$(function() {

	
	<?php 
	if($num_rows==0){
	?>
		$("#save_form").hide(100);
	<?php
	}else{
		if($banrojo==true){
	?>
		$("#save_form").show(100);
	<?php 
		}else if($banrojo==false){
	?>
		$("#save_form").hide(100);
	<?php 
		}
	}
	?>


	$('#txt_ven_recibi').keydown(function(ev) {
			if(ev.keyCode==13){ return false;}
		});
		
		
			$('#txt_ven_valven').keydown(function(ev) {
			if(ev.keyCode==13){ return false;}
		});
		
		
			$('#txt_ven_igv').keydown(function(ev) {
			if(ev.keyCode==13){ return false;}
		});
		
			$('#txt_ven_tot').keydown(function(ev) {
			if(ev.keyCode==13){ return false;}
		});
		
		
	$("#txt_ven_recibi").keyup(function() {
			
				calcular_vuelto($('#txt_ven_tot').val(), $(this).val());
				
			
		});


        tabla_totales();

		<?php if($num_rows > 0){ ?>
		$('#cmb_mone_id').attr('disabled','disabled');
		<?php }else{
		?>
		$('#cmb_mone_id').removeAttr("disabled");
		<?php	
		}?>

		var nFilas = $("#hdd_ven_numite").val();
  if(nFilas>0){
  	$('#tabcliente .nav-tabs a:last').tab('show'); 
  }
  $("#txt_importe_cliente").attr('placeholder',$("#txt_ven_tot").val())

	/* 	$("#txt_importe_cliente").keyup(function() {		
			calcular_vuelto();
		}); */

		
	/* $("#txt_ven_des").keyup(function(e){
				des = $("#txt_ven_des").val();
				
				totsindes = <?php echo $total; ?>;				

				if(des > totsindes){
					des = 0;
					$("#txt_ven_des").val(0);
					toastr["error"]('El descuento no puede ser mayor al total de la venta');
				}
					
				totcondes = totsindes - des;
				igv = (totcondes*0.18)/1.18;
				valven = totcondes/1.18;
				
				$("#txt_ven_tot").val(new NumberFormat(totcondes).toFormatted());
				$("#txt_ven_igv").val(new NumberFormat(igv).toFormatted());
				$("#txt_ven_valven").val(new NumberFormat(valven).toFormatted());
				$("#txt_ven_totsdes").val(new NumberFormat(totsindes).toFormatted());
				venpag_aut();
				
		});
 */

	// $("#txt_ven_des").keydown(function(e){
			// if (e.which == 13){
				// totsindes =<?php echo $total;  ?>;				
				// des = $("#txt_ven_des").val();
				
				// totcondes = totsindes - des;
				
				// $("#txt_ven_tot").val(totcondes.toFixed(2));
				// $("#txt_ven_totsdes").val(totsindes.toFixed(2));
				// venpag_aut();
				// return false;
				// }
		// });

	
		
		$('#tabla_venta_car td input').keydown(function(ev) {
			if(ev.keyCode == 13 && !$(this).attr('readonly')) {
			
			var cat_id = $(this).attr('data-cat_id');
			var mar_id = $(this).attr('data-mar_id');
			var cantidad = $(this).parent().parent().find('input[data-cantidad]').attr('data-cantidad');
			var can = $(this).parent().parent().find('input[data-cantidad]').val();
			var preven = $(this).parent().parent().find('input[data-preven]').val();
			var des = $(this).parent().parent().find('input[data-des]').val();
			var tipdes = $(this).attr('data-tipdes');
			var tip = $(this).attr('data-tip');
			var est = $(this).attr('data-est');
				
		
				
				
			if(tip=="des"){
					
				preuni =  $(this).parent().parent().find('input[data-preven]').val();
				agregar_producto('agregar', cat_id, can, preuni, mar_id,des);
			
			}else if(tip=="pretot"){
				
			var pretot = $(this).val();
			
			preuni = pretot.toString().replace(',','')/ cantidad ;	
			agregar_producto('agregar', cat_id, can,preuni,mar_id,des,'','',est);
			
			}else if(tip=="valtot"){
				
			// var valtot = $(this).val();
			// valuni =  new NumberFormat(valtot).toFormatted()/new NumberFormat(cantidad).toFormatted();
			
			//alert(valuni);
			
			// agregar_producto('agregar', cat_id, cantidad, new NumberFormat(valuni).toFormatted(), mar_id,des,'','',est);
			
			}else if(tip=="preuni"){
				
			var preuni = $(this).val();
			
				agregar_producto('agregar', cat_id, can,preuni,mar_id,des,'','',est);
			
			}else{
				agregar_producto('agregar', cat_id, can, preven,mar_id,des,'','',est);
			}	
				
				
				
				$(this).attr('readonly', 'true');
				$(this).parent().removeClass('editando');
				return false;
			}
		});

		$('#tabla_venta_car td input').parent().click(function(ev) {
			var $input = $(this).find('input');
			var $td = $input.parent().addClass('editando');
			$input.removeAttr('readonly').focus().select();
		});

		$('#tabla_venta_car td input').blur(function(event) {
			$(this).val($(this).attr('data-original'));
			$(this).attr('readonly', 'true');
			$(this).parent().removeClass('editando');
		});

		$('#tabla_venta_car td input').keydown(function(ev) {
			if(ev.keyCode==27){
				$(this).val($(this).attr('data-original'));
				$(this).attr('readonly', 'true');
				$(this).parent().removeClass('editando');
			}
		});

	/* 	$( ".btn_editar" ).click(function() { 
			var $input = $(this).parent().parent().find('input[data-cantidad]');
			var $td = $input.parent().addClass('editando');
			$input.removeAttr('readonly').focus().select();
		}); */

		$( ".btn_eliminar" ).click(function() { 
			
			var indice = $(this).attr('data-indice');
				
			if(confirm('¿Seguro de quitar el item?')){
				agregar_producto('quitar', indice);
			}
		});

		$( ".cmb_estado" ).change(function() { 
			
			var cat_id = $(this).attr('data-cat_id');
			var mar_id = $(this).attr('data-mar_id');
			var cantidad = $(this).attr("data-cantidad");
			var preven = $(this).attr("data-preven");
			var des = 0;
			var tipdes = $(this).attr('data-tipdes');
			var tip = $(this).attr('data-tip');
			var est = $(this).val();
			
			agregar_producto('agregar', cat_id, cantidad, preven,mar_id,des,'','',est);
			
			
			
		});


	$(".restablecer").click(function() { 
			venta_form();
		});

	}); 
	
	
	
function tabla_totales()
{

	$.ajax({
		type: "POST",
		url: "../compra/tabla_totales.php",
		async:true,
		dataType: "html", 
		data: ({
			vista: 'venta_form'
		}),                   
		beforeSend: function() {
				
	
			$('#div_tablatotales').addClass("ui-state-disabled");
        },
		success: function(html){
			$('#div_tablatotales').html(html);
		},
		complete: function(){			
			$('#div_tablatotales').removeClass("ui-state-disabled");
	
		}
	});     
}

function calcular_vuelto(total,recibi)
{

	$.ajax({
		type: "POST",
		url: "../venta/calcular_vuelto.php",
		async:true,
		dataType: "json", 
		data: ({
			total:total,
			importe:recibi,
			vista: 'venta_form'
		}),                   
		beforeSend: function() {

        },
		success: function(data){
			
			$('#txt_ven_vuelto').val(data.vuelto);
		},
		complete: function(){			
			
		}
	});     
}


</script>


