<?php 

//ini_set('display_errors',1);

session_start();
require_once ("../../config/Cado.php");
require_once ("../almacen/cAlmacen.php");
$oAlmacen = new cAlmacen();
require_once("../stock/cStock.php");
$oStock = new cStock();
require_once ("../producto/cCatalogo.php");
$oCatalogo = new cCatalogo(); 
require_once ("../venta/cVenta.php");
 $oVenta = new cVenta();
require_once ("cOrdencompra.php");
$oOrdencompra = new cOrdencompra();
require_once("../formatos/fechas.php");
require_once ("../formatos/formato.php");


$mesactual = date('m');

$y = date('Y');
$m = date('m');
$d = date('d');

$fecactual='01-'.$m.'-'.$y;
list($day,$mon,$year) = explode('-',$fecactual);


$fecantes=date('Y-m-d',mktime(0,0,0,$mon-2,$day,$year));
list($anioini1,$mesini1,$diaini1) = explode('-',$fecantes);

$fecantes=date('Y-m-d',mktime(0,0,0,$mon-1,$day,$year));
list($anioini2,$mesini2,$diaini2) = explode('-',$fecantes);

$fecantes=date('Y-m-d',mktime(0,0,0,$mon,$day,$year));
list($anioini3,$mesini3,$diaini3) = explode('-',$fecantes);



if(isset($_SESSION['ordencompra_can'])){
$num_rows=count($_SESSION['ordencompra_can']);
}else {
	$num_rows= 0 ;
}
// echo $num_rows.'--';




	$dts1=$oCatalogo->mostrarUno($_POST['cat_id'],$_POST['mar_id']);
	$dt1 = mysqli_fetch_array($dts1);
	$pro_codint = $dt1['tb_producto_codint'];
	$pro_nom = $dt1['tb_producto_nom'];
	$mar_nom = $dt1['tb_marca_nom'];
	$emp_fac = $dt1['tb_empaque_fac'];
	
	$dts=$oAlmacen->filtrar('');
	$num_rows= mysqli_num_rows($dts);

$dts1=$oOrdencompra->mostrar_compra($_POST['cat_id'],$_POST['mar_id']);
$num_rows1= mysqli_num_rows($dts1);




?>

	

	<div class="col-lg-12 col-md-12 col-xs-12 " style="">
				
				
					<div class="box-header">
						<h4 class="box-title">Ingrese cantidad a pedir</h4> 
					</div>
				<?php if($num_rows>0){?>
				<div class="col-lg-12 col-xs-12">
					<label id="btn_verproductoagregado" onclick="ordencompra_form('insertar','');" data-toggle="tooltip" data-placement="top" 
					title="Ver productos agregados" class="btn btn-sm btn-success"><i class="fa fa-eye"></i> GENERAR ORDEN</label>
				</div>
				<?php }?>
					
				<div class="row">
				    
				    		
<div class="col-lg-12 col-sm-12 col-12"> 
		<label style="color:#3B71CA;font-weight:bold;font-size:1rem;" >PRODUCTO:</label>
		<span style="color:#000;font-size:1.2rem;font-weight:bold;" >  <?php echo $pro_nom?> </span>
</div>


				<div class="col-lg-4 col-xs-12">
								<label for="txt_ordcom_can">CANTIDAD:</label>
								<input type="text" name="txt_ordcom_can" autocomplete="off" id="txt_ordcom_can" style="text-align:right" value="<?php echo ''?>" class="form-control">									
				</div>
				
				<div class="col-lg-8 col-xs-12">
								<label for="txt_ordcom_precosuni">PRECIO COSTO UNI.:</label>
								<input type="text" name="txt_ordcom_precosuni" autocomplete="off" id="txt_ordcom_precosuni" style="text-align:right" value="<?php echo ''?>" class="form-control">									
				</div>
				</div>
				
				
				<div style="height:10px;" class="col-lg-12 col-xs-12"></div>
				
				
				
				
				<div class="table-responsive">
	
          <table id="tabla_compra" class="table">
            <thead>
              <tr>
					<th class="" >FECHA</th>
					<th>DOCUMENTO</th>                    
					
					<th>CANTIDAD</th>
					<th>VALOR UNITARIO</th>
					<th>PRECIO UNITARIO</th>
					<th>PROVEEDOR</th>
              </tr>
            </thead>
            <tbody>
			
				<?php 
				
				 if($num_rows1>0){
				while($dt1 = mysqli_fetch_array($dts1))
				 {
					 
					$val_uni = $dt1['tb_compradetalle_preuni'];
					$com_igvigv =$dt1['tb_compra_igvigv'];
		
					$igv_uni = $val_uni * $com_igvigv;
					$pre_uni=$val_uni+$igv_uni;
		
					 
				?>


					 <tr >
       
		
		<td class="" nowrap="nowrap"><?php echo mostrarFecha($dt1['tb_compra_fec'])?></td>
        <td NOWRAP ><?php echo $dt1['tb_documento_abr'].' - '.$dt1['tb_compra_numdoc']?></td>
        
        <td NOWRAP ><?php echo $dt1['tb_compradetalle_can']?></td>
        <td NOWRAP ><?php echo formato_money($val_uni) ?></td>
        <td NOWRAP ><?php echo formato_money($pre_uni) ?></td>
        <td NOWRAP ><?php echo $dt1['tb_proveedor_nom']?></td>
      </tr>
	  
	  
	  


				<?php				
					 
				 }
				}
				
				?>

			 </tbody>
			 </table>
			
</div>
				
				
				
							
				<div style="height:10px;" class="col-lg-12 col-xs-12"></div>
				
				
				
				
				<div style="height:10px;" class="col-lg-12 col-xs-12"></div>
				
					 
					 
					 <div class="col-lg-12 col-sm-12 col-12"> 			
		
		<table id="tabla_producto" class="table">
						
						<tr>
									<td>SUCURSAL</td>
									<td>STOCK</td>
									 <?php
		   for($i=1;$i<=3;$i++){
			 
			 if($i==1){
				 $mes = $mesini1; 
			 }
			 else if($i==2){
				 $mes = $mesini2; 
			 }
			 else if($i==3){
				 $mes = $mesini3; 
			 }	 
			 
			?>
			<th><?php echo nombre_mes($mes);?></th>
			<?php 			
		  }
		  
		  ?>
						</tr>
								
								
								
						
						<?php  if($num_rows>=1){
							 while($dt = mysqli_fetch_array($dts)){
								 
								 
								//$stock = mysqli_fetch_array($oStock->stock_por_presentacion($_POST['cat_id'],$_POST['mar_id'],$dt['tb_almacen_id']))['tb_stock_num']*1; 
							
								$stockkardex = mysqli_fetch_array($oStock->sumatipokardex_por_presentacion($_POST['cat_id'],$_POST['mar_id'],$dt['tb_almacen_id']))['total']*1; 
								
								$dtssto = $oStock->stock_por_presentacion($_POST['cat_id'],$_POST['mar_id'],$dt['tb_almacen_id']);
								$dtsto = mysqli_fetch_array($dtssto);
								$stock = $dtsto['tb_stock_num']*1; 
								$stock_id = $dtsto['tb_stock_id']; 
							
							if($stockkardex>0){
							if($stockkardex!=$stock){
								$oStock->modificar($stock_id,$stockkardex);
						    	$stock =$stockkardex; 
								// echo '1-';
							}
							}
							
								
							
							
							
							
							$stocktotal+=$stock;
							
							$can = $stock / $emp_fac;
							$canf = 0;
							$cane = 0;
							//echo $emp_fac.'--';
							if($stock<$emp_fac){
								$cane = $cane;
								$canf = $stock;
							}else{
								list($cane,$canf) = explode('.',$can);
							}
							
							
							if($cane>0 && $canf>0){
								$canemp = $cane * $emp_fac;
								$canf = $stock - $canemp;
								$stock = $cane.'F'.$canf;
							}else if($cane>0 && $canf==""){
								$stock = $cane;
							}else if($cane=="" && $canf>0){
								
								$stock = 'F'.$canf;
							}else if($cane=="0" && $canf>0){
								
								$stock = 'F'.$canf;
							}
							
							
							
							
							
						//	echo $dt['tb_puntoventa_id'].'--';
							
							
							?>
							
								<tr style="<?php if($_POST["alm_id"] == $dt['tb_almacen_id']) echo 'border: 1px solid red;background-color:#1565C0;color:#fff;'; ?>">
									<td><?php echo $dt['tb_almacen_nom'];?></td>
									<td>
									<h4><?php echo $stock;?></h4>
									<?php 
									if($stockkardex<0){
										?>
										<span style="color:red;"><?php echo $stockkardex; ?></span>
										<?php
									}
									?>
									
									</td>
									
									<?php
					 for($i=1;$i<=3;$i++){
						  
						  $fec1 = '01-'.$i.'-'.$y;
						  $fec2 = '31-'.$i.'-'.$y;
						  
						   if($i==1){
							   
							    $fec1 = '01-'.$mesini1.'-'.$anioini1;
								$fec2 = '31-'.$mesini1.'-'.$anioini1;
							 }
							 else if($i==2){
								  $fec1 = '01-'.$mesini2.'-'.$anioini2;
								$fec2 = '31-'.$mesini2.'-'.$anioini2;
							 }
							 else if($i==3){
								 $fec1 = '01-'.$mesini3.'-'.$anioini3;
								$fec2 = '31-'.$mesini3.'-'.$anioini3;
							 }
						  //echo fecha_mysql($fec1);
						  
						  $i = $i * 1;
						$dtsv = $oVenta->ventas_rotacion($_POST['cat_id'],$_POST['mar_id'],fecha_mysql($fec1),fecha_mysql($fec2),$dt['tb_puntoventa_id']);
						$dtv = mysqli_fetch_array($dtsv);
						$canven = $dtv['can'];
						
						//echo $canven.'--';
						
						$stockvendido[$i] += $canven;
						
							$can = $canven / $emp_fac;
							$canf = 0;
							$cane = 0;
							//echo $emp_fac.'--';
							if($canven<$emp_fac){
								$cane = $cane;
								$canf = $canven;
							}else{
								list($cane,$canf) = explode('.',$can);
							}
							
							
							if($cane>0 && $canf>0){
								$canemp = $cane * $emp_fac;
								$canf = $canven - $canemp;
								$canven = $cane.'F'.$canf;
							}else if($cane>0 && $canf==""){
								$canven = $cane;
							}else if($cane=="" && $canf>0){
								
								$canven = 'F'.$canf;
							}else if($cane=="0" && $canf>0){
								
								$canven = 'F'.$canf;
							}


						
						  
						?>
						<th><?php echo $canven;?></th>
						<?php 			
					  }
					  
					  ?>
									
							
								</tr>
							
							<?php 
							 }
							 
							 	 
							 $cantot = $stocktotal / $emp_fac;
							$canf = 0;
							$cane = 0;
							//echo $emp_fac.'--';
							if($stocktotal<$emp_fac){
								$cane = $cane;
								$canf = $stocktotal;
							}else{
								list($cane,$canf) = explode('.',$cantot);
							}
							
							
							if($cane>0 && $canf>0){
								$canemp = $cane * $emp_fac;
								$canf = $stocktotal - $canemp;
								$stocktotal = $cane.'F'.$canf;
							}else if($cane>0 && $canf==""){
								$stocktotal = $cane;
							}else if($cane=="" && $canf>0){
								
								$stocktotal = 'F'.$canf;
							}else if($cane=="0" && $canf>0){
								
								$stocktotal = 'F'.$canf;
							}
							
							?>
							
							<tr>
									<td style="color:#DC4C64" >TOTAL:</td>
									<td style="color:#14A44D" ><h4><?php echo $stocktotal;?></h4></td>
									<?php
									  for($i=1;$i<=3;$i++){
										  $i = $i*1;
											$stocktotalven = $stockvendido[$i];
											
											 $cantot = $stocktotalven / $emp_fac;
											$canf = 0;
											$cane = 0;
											//echo $emp_fac.'--';
											if($stocktotalven<$emp_fac){
												$cane = $cane;
												$canf = $stocktotalven;
											}else{
												list($cane,$canf) = explode('.',$cantot);
											}
											
											
											if($cane>0 && $canf>0){
												$canemp = $cane * $emp_fac;
												$canf = $stocktotalven - $canemp;
												$stocktotalven = $cane.'F'.$canf;
											}else if($cane>0 && $canf==""){
												$stocktotalven = $cane;
											}else if($cane=="" && $canf>0){
												
												$stocktotalven = 'F'.$canf;
											}else if($cane=="0" && $canf>0){
												
												$stocktotalven = 'F'.$canf;
											}
							
							 
							 
										
										
										?>
										<th><?php echo $stocktotalven;?></th>
										<?php 			
									  }
									  
									  ?>
								</tr>
							
							
							
							<?php
							
						}else{
						?>
						<tr>
							<td>SIN ALMACENES</td>
						</tr>
						<?php
						}?>
						
							
		</table>
		
</div>

					 		
				<div class="box-footer float-right">
					<button type="button" data-dismiss="modal" class="btn btn-default ">CANCELAR</button>
					<button type="button" class="btn btn-primary save_pedido">AGREGAR</button>
					
				</div>
				
				</div>
				
				


<script type="text/javascript">

function agregar_pedidocompra(act,can,precosuni,cat_id,mar_id,vista){
		
		
		
		$.ajax({
			type: "POST",
			url: "../ordencompra/agregar_producto.php",
			async:true,
			dataType: "json",                      
			data: ({
				action: act,
				cat_id : cat_id ,
				mar_id : mar_id ,
				can : can,
				precosuni:precosuni,
				vista:	'stockgeneral_form'
			}),
			beforeSend: function() {
				
			},
			success: function(data){
				
				if(data.dat.tipo=="can")
				{
					toastr["warning"](data.msj);
					
				}else if(data.dat.tipo=="agregado")
				{
					
					
					$("#btn_verproductoagregado").show();
					toastr["info"](data.msj);
				}
				else if(data.dat.tipo=="quitado")
				{
					
					toastr["info"](data.msj);
				}
				
				
			},
			complete: function(){
				if(vista=="agregar"){
					$("#txt_ordcom_can").val('');		
					$("#txt_ordcom_precosuni").val('');		
				}else if(vista=="quitar" || vista=="editar"){
					ordencompra_detalle_tabla();
				}	
			}
		});
	
	}

function ordencompra_form(act)
	{
	
	$('#div_ordencompra_form_dialog').modal('show');
	$.ajax({
		type: "POST",
		url: "../ordencompra/ordencompra_form.php",
		async:true,
		dataType: "html",                      
		data: ({
			action : act,
			vista : 'stockgeneral_form'
		}),
		beforeSend: function() {

			//var div = "<center> <br> <span class='spinner-border spinner-border-lg mr-2'></span> <span style='font-size:1.5rem;'>PROCESANDO PETICIÓN</span></center>";	
			//$('.div_ordencompradetalle_form').html(div);
        },
		success: function(html){
			$('.div_ordencompra_form').html(html);
		},
		complete: function(){			
		}
	});    
	}	

$(function() {
	
$("#txt_ordcom_can,#txt_ordcom_precosuni").keydown(function(e){
	if (e.which == 13){

		var can = $('#txt_ordcom_can').val();
		var precosuni = $('#txt_ordcom_precosuni').val();
		if(can==""){
			toastr["error"]("Agrege cantidad a pedir");
		}else if(precosuni==""){
			toastr["error"]("Agrege precio de costo");
		}else{
		agregar_pedidocompra('agregar',can,precosuni,'<?php echo $_POST['cat_id'] ?>','<?php echo $_POST['mar_id'] ?>','agregar');
		}
		return false;
	}
});


$(".save_pedido").click(function(){
	var can = $('#txt_ordcom_can').val();
		var precosuni = $('#txt_ordcom_precosuni').val();
		
		if(can==""){
			toastr["error"]("Agrege cantidad a pedir");
		}else if(precosuni==""){
			toastr["error"]("Agrege precio de costo");
		}else{
		agregar_pedidocompra('agregar',can,precosuni,'<?php echo $_POST['cat_id'] ?>','<?php echo $_POST['mar_id'] ?>','agregar');
		}
		return false;
});


});

		
	
</script>				
				
				
				