<?php
session_start();
require_once ("../../config/Cado.php");	
require_once ("../formatos/formato.php");
require_once ("../kardex/cKardex.php");
$oKardex = new cKardex();
require_once ("../producto/cCatalogo.php");
$oCatalogo = new cCatalogo();
require_once ("../modulo/cModulo.php");
$oModulo = new cModulo();
require_once("../stock/cStock.php");
$oStock = new cStock();
require_once("../documento/cDocumento.php");
$oDocumento = new cDocumento();


require_once("../formatos/mysql.php");
$oMysql = new cMysql();
$fec_ini='01-01-2014';
$fec_fin=$oMysql->DATE_ADD(fecha_mysql($_POST['txt_fil_notcre_fec1']),'-1','DAY');


$rs = $oKardex->mostrar_datos_producto($_POST['idcat_oculto'],$_POST['cmb_fil_mar_id']);
$dt = mysqli_fetch_array($rs);		
	
			$alm = $dt['tb_almacen_nom'];//establecimiento			
			$cod = $dt['tb_presentacion_codbar'];//codigo de la existencia			
			$cat = $dt['tb_categoria_nom'];//tipo
			$nom = $dt['tb_producto_nom'];//descripcion
			$cat_precos = $dt['tb_catalogo_precos'];//descripcion
			mysqli_free_result($rs);

	//catalogo

			$dts2=$oCatalogo->mostrarUno($_POST['idcat_oculto'],$_POST['cmb_fil_mar_id']);
			$dt2 = mysqli_fetch_array($dts2);
			$pre_id = $dt['tb_presentacion_id'];
			mysqli_free_result($dts2);
			
			//echo '--'.$pre_id;

			$dts3=$oStock->stock_por_presentacion($_POST['idcat_oculto'],$_POST['cmb_fil_mar_id'],$_POST['cmb_almacen']);
			$dt3 = mysqli_fetch_array($dts3);
			$sto_id = $dt3['tb_stock_id'];
			$stock_actual = $dt3['tb_stock_num'];
			mysqli_free_result($dts3);


$cantidad_total = mysqli_fetch_array($oKardex->sumatipokardex_por_presentacion($_POST['idcat_oculto'],$_POST['cmb_fil_mar_id'],
		$_POST['cmb_almacen'],fecha_mysql($fec_ini),fecha_mysql($fec_fin)))['total']*1; 




			$dts1 = $oKardex->mostrar_kardex_por_producto($_POST['idcat_oculto'],$_POST['cmb_fil_mar_id'],$_POST['cmb_almacen'],
			fecha_mysql($_POST['txt_fil_notcre_fec1']),fecha_mysql($_POST['txt_fil_notcre_fec2']));	
			$num_rows_1 = mysqli_num_rows($dts1);
			
			if($num_rows_1 > 0){
			}
			?>
			<script type="text/javascript">

				$(function() {
	//$.tablesorter.defaults.widgets = ['zebra'];
	//$("#tabla_kardex").tablesorter({});
}); 

</script>
<style>
	
	#div_tabla_kardex { margin: 0 0; border-collapse: collapse; width: 100%; }
	#div_tabla_kardex td, #div_tabla_kardex th { border-left: 1px solid #eee;border-bottom: 0px ; padding: 2px 3px; font-size:15px; }
	#div_tabla_kardex th { height:5px }
	#div_tabla_kardex td { height:5px }
</style>

	<div class="table-responsive">
	    
	    
	    
	    	<?php 
	if($cantidad_total>0){
	?>	
		<table id="div_tabla_kardex" class="table" >
		<tbody>
			<tr>
				<td nowrap="nowrap" style="font-size:2rem;" >SALDO ANTERIOR : </td>
				<td nowrap="nowrap" align="right" ><span style="font-size:2rem;" ><?php echo formato_money($cantidad_total)?></span></td>
			</tr>
		</tbody>
		<table>
		
		
		
	<?php	
	}
	
	?>

	    
	    
	    
	    
	<table id="div_tabla_kardex" class="table " >
		<thead>
			<tr class=" bg-green">
				<th colspan="5">DOCUMENTO</th>            
				<th colspan="2">TIPO DE OPERACI&Oacute;N</th>
				<th colspan="2">ENTRADAS</th>
				<th colspan="2">SALIDAS</th>
				<th colspan="2">SALDO FINAL</th>
			</tr>
			<tr class="bg-danger">
				<th>FECHA</th>
				<th>CÓDIGO</th>
				<th>TIPO DE DOCUMENTO</th>
				<th>NUMERO DE DOCUMENTO</th>
				<th>USUARIO</th>
				<th>OPERACION</th>
				<th>V. UNITARIO</th>
				<!--TIPO OPERACIÓN-->
				<th>CANTIDAD</th>
				<th>TOTAL</th>
				<th>CANTIDAD</th>
				<th>TOTAL</th>
				<th>CANTIDAD</th>
				<th>TOTAL</th>

			</tr>
		</thead>
		<tbody>
			<?php
			//$cantidad_total = 0;
			$precio_promedio = 0;
			$costo_total = 0;
			$cantidad_total_entradas = 0;
			$cantidad_total_salidas = 0;
			$costo_total_entradas = 0;
			$costo_total_salidas = 0;
			
			while($dt1 = mysqli_fetch_array($dts1)){

				$modulo ="";
				$mod_id = $dt1['tb_modulo_id'];
				$usu_nom = $dt1['tb_usuario_use'];
				$idm = $dt1['tb_kardex_idm'];
				$doc_nom = ""; 
				$doc_num = "";
				$pref = "";

				$dtsMod = $oModulo->mostrarUno($mod_id);
				$num_rows3= mysqli_num_rows($dtsMod);
				if($num_rows3>=1){
					while($dt3 = mysqli_fetch_array($dtsMod)) {
						$modulo = $dt3['tb_modulo_nom'];
					} 
					mysqli_free_result($dtsMod);
				}

				// echo $mod_id.'--';
  // echo $idm.'--';
				switch ($mod_id) {
					case 4:

					$dtsCom = $oDocumento->obtenerDocumento_compra($idm);
					$num_rows4= mysqli_num_rows($dtsCom);
					if($num_rows4>=1){
						while($dt4 = mysqli_fetch_array($dtsCom)) {
							$doc_nom = $dt4['tb_documento_nom']; 
							$doc_num = $dt4['tb_compra_numdoc'];
							$pref = $dt4['tb_proveedor_nom'];
						} 
						mysqli_free_result($dtsCom);
					}					
					break;
					case 5:
					$dtsTra = $oDocumento->obtenerDocumento_traspaso($idm);
					$num_rows5= mysqli_num_rows($dtsTra);
					if($num_rows5>=1){
						while($dt5 = mysqli_fetch_array($dtsTra)) {
							$doc_nom = 'TRASPASO'; 
							$doc_num = $dt5['tb_traspaso_numdoc'];
							$pref = $dt5['tb_cliente_nom'];
						} 
						mysqli_free_result($dtsTra);
					}
					break;
					case 3:
					$dtsVen = $oDocumento->obtenerDocumento_venta($idm);
					$num_rows5= mysqli_num_rows($dtsVen);
					if($num_rows5>=1){
						while($dt5 = mysqli_fetch_array($dtsVen)) {
							$doc_nom = $dt5['tb_documento_nom']; 
							$doc_num = $dt5['tb_venta_numdoc'];
							$pref = $dt5['tb_cliente_nom'];
						} 
						mysqli_free_result($dtsVen);
					}
					break;
					case 7:
					$dtsVen = $oDocumento->obtenerDocumento_notacredito($idm);
					$num_rows5= mysqli_num_rows($dtsVen);
					if($num_rows5>=1){
						while($dt5 = mysqli_fetch_array($dtsVen)) {
							$doc_nom = $dt5['tb_documento_nom']; 
							$doc_num = $dt5['tb_notacredito_numdoc'];
							$pref ='';
						} 
						mysqli_free_result($dtsVen);
					}
					break;
					
					case 6:
					$dtsAlm = $oDocumento->obtenerDocumento_notaalmacen($idm);
					$num_rows6= mysqli_num_rows($dtsAlm);
					if($num_rows6>=1){
						while($dt6 = mysqli_fetch_array($dtsAlm)) {
							$doc_nom = 'NOTA DE ALMACEN'; 
							$doc_num = $dt6['tb_notaalmacen_numdoc'];
							$pref ='';
						} 
						mysqli_free_result($dtsAlm);
					}
					break;
					
					case 18:
					
					$dtsDevcli = $oDocumento->obtenerDocumento_devolucioncliente($idm);
					$num_rows7= mysqli_num_rows($dtsDevcli);
					if($num_rows7>=1){
						while($dt7 = mysqli_fetch_array($dtsDevcli)) {
							$doc_nom = 'DEVOLUCION CLIENTE'; 
							$doc_num = $dt7['tb_devolucioncliente_numdoc'];
							$pref ='';
						} 
						mysqli_free_result($dtsDevcli);
					}
					break;
					default:
					$doc_nom = ""; 
					$doc_num = "";
					
					
					
				}

				$can = $dt1['tb_kardexdetalle_can']*1;						
						$tip = $dt1['tb_kardexdetalle_tip']; //Verificando si es Entrada o Salida (1: ENTRADA | 2: SALIDA)
						
						if($tip == 1){							
							$precos = $dt1['tb_kardexdetalle_cos'];
							
							$subtotal = $can*$precos;
							$cantidad_total += $can;
							$cantidad_total_entradas += $can;
							$costo_total_entradas += $subtotal;
							$tot_entra = $dt1['tb_kardexdetalle_cos'] * $can;
							$sal_total += $tot_entra;
							
							$valuni = $sal_total / $cantidad_total;
							
						}
				
					 if($tip == 2){							
                         	$precos = $dt1['tb_kardexdetalle_cos'];
                         	$subtotal = $can*$precos;
                         	$cantidad_total -= $can;
                         	$cantidad_total_salidas += $can;
                         	$costo_total_salidas += $subtotal;
							$valuni = $precos;
							$tot_sal = $can*$valuni;
							$sal_total = $cantidad_total * $valuni;
					}
				
				?>
				<tr>
					<td nowrap="nowrap" title="<?php echo 'Registrado: '.mostrarFechaHoraH($dt1['tb_kardex_reg'])?>"><?php echo mostrarFecha($dt1['tb_kardex_fec'])?></td>
					<td nowrap="nowrap"><?php echo $dt1['tb_kardex_id']?></td>
					<td nowrap ><?php echo $doc_nom ;?></td>
					
					<td nowrap="nowrap"  ><strong title="<?php echo $pref; ?>" data-toggle="tooltip" data-placement="top" style="cursor:pointer;"> <?php echo $doc_num; ?></strong></td>                	
					<td nowrap ><?php echo $usu_nom ;?></td>
					<td nowrap ><?php echo $modulo; if($tip == 1) echo ' ( S/ '.formato_money3($dt1['tb_kardexdetalle_cos']).')'; ?></td>
					<td nowrap ><?php if($valuni >0 ) echo 'S/ '.formato_money3($valuni); ?></td>
					
					<td nowrap align="right" nowrap="nowrap"><?php
							if($tip == 1) echo $can;
							 if($dt1['tb_tipoperacion_id']==1){/*
							 ?>
                             <a class="btn_act_stock" onClick="kardex_form('actualizar_saldo_inicial','<?php echo $dt1['tb_kardexdetalle_id']?>','<?php echo $dt['tb_almacen_id']?>','<?php echo $stock_id?>')">Actualizar</a>
                             <?php */}?>
                    </td>
					<td nowrap align="right"><?php if($tip == 1){if($tot_entra >0 ) echo 'S/ '.formato_money3($tot_entra);} ?></td>
                    
					<td nowrap align="right"><?php if($tip == 2)echo $can?></td>
                         	
                    <td nowrap align="right"><?php if($tip == 2){if($tot_sal >0 ) echo 'S/ '.formato_money3($tot_sal);} ?></td>
                    
					<td nowrap align="right"><?php echo $cantidad_total?></td>
                    <td nowrap align="right"><?php echo 'S/ '.formato_money3($sal_total);?></td>

                         </tr>                                                            
                         <?php
                     }
					 
                     mysqli_free_result($dts1);
                     ?>
                     <tr>
                     	<td colspan="6"><strong>TOTAL</strong></td>                    
                     	<td align="right"><strong class="text-orange" ><?php echo $cantidad_total_entradas?></strong></td>
						<td></td>
                     	<td align="right"><strong class="text-orange" ><?php echo $cantidad_total_salidas?></strong></td>
                     	<td></td>
						<td align="right"><strong class="text-red text-md"  id="xtotalx" ><?php echo $stock_final=$cantidad_total_entradas-$cantidad_total_salidas?></strong></td>
						<td></td>
					 </tr>
                 </tbody>
             </table>
             
             
             <?php 
	if($cantidad_total>0){
	?>	
		<table id="div_tabla_kardex" class="table" >
		<tbody>
			<tr>
				<td nowrap="nowrap" style="font-size:2rem;" >TOTAL : </td>
				<td nowrap="nowrap" align="right" ><span style="font-size:2rem;" ><?php echo formato_money($cantidad_total)?></span></td>
			</tr>
		</tbody>
		<table>
		
		
		
	<?php	
	}
	
	?>	 
			
			
	
	</div>
             <script>
             	calcularstockreferencial();             	
             </script>


         <?php
         //echo $stock_actual .'--'.$stock_final;
	//actualización automatica del stock resultante
         
      /*   	if($stock_actual!=$stock_final and $sto_id>0 and $stock_final>=0){
         		echo 'Se actualizo stock.';
         		$oStock->modificar(
         			$sto_id,
         			$stock_final
         			);
         }
         
         */
         ?>