<?php

ini_set('display_errors', 1);


define("ADMIN", true);
require_once("../../common/lib.php");
require_once("../../common/define.php");
define("TITLE_ELEMENT", 'Inventaire');
if(!isset($_SESSION['user'])){
    header("Location: ../login.php");
    exit();
}
require_once("../includes/fn_module.php"); ?>
<!DOCTYPE html>
<head>
    <?php include("../includes/inc_header_common.php"); ?>

</head>
<body>
    <div id="wrapper">
        <?php include("../includes/inc_top.php"); ?>
        <div id="page-wrapper">
            <div class="page-header">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-8">
                            <h1><i class="fa fa-cubes"></i> Mouvement de stock</h1>
                        </div>
                    </div>
                </div>
            </div>
            <div class="container-fluid">
                <div class="alert-container">
                    <div class="alert alert-success alert-dismissable"></div>
                    <div class="alert alert-warning alert-dismissable"></div>
                    <div class="alert alert-danger alert-dismissable"></div>
                </div>
                <div class="row">				
				
	<form method="GET" action="stock_search.php">				
<div class="table-responsive">
                                <table class="table table-bordered table-hover table-striped tablesorter" id="tablesorter">
                                    
                                    <thead>	
									<tr>
											<td class="text-center" colspan="5" style="background-color: #ffc000;color:#000"><b> Mouvement de stock du <? echo $_GET["date_in"];?> jusqu'au <? echo $_GET["date_out"];?> </b></td>
									</tr>										
<?php
									$prod = explode("_", $_GET["product"]);
									$id_product = $prod[1];
									
									if($prod[0] == "v"){ 
										$table = "pm_produits"; 
									}else{
										$table = "pm_produitsachat"; 										
									}
									$queryProd = "select * from ".$table." where id =".$prod[1]." order by id ASC";
									// echo $queryProd;
									$resultProd = @$db->query($queryProd);
									$row_Prod = $resultProd->fetch();
									
									if($row_Prod){
									
									$coulissage = $row_Prod["coulissage"];
?>		
									<tr>
											<td class="text-center" colspan="5" style="background-color: #dadada;color:#000;color:#00a1af;"><b><? echo $row_Prod["code_produit"];?> - <? echo $row_Prod["desingnation"];?> </b></td>
									</tr>		
<?									}	?>
														
										<tr>
											<th class="text-center"  ><b>Date</b></th>
											<th class="text-center"><b>Type</b></th>
											<th class="text-center"><b>Référence</b></th>
											<th class="text-center"><b>Quantité<br>Unitaire/Emballée</b></th>
											<th class="text-center"><b>Solde<br>(Quantité Unitaire/Emballée)</b></th>
										</tr>
									</thead>
									<tbody>
									    <?php
										if($db !== false){
											$mouvement = $_GET["mouvement"] ;
											global $solde ;
											
											if($mouvement == '0'){
												if($prod[0] == "v"){ 
													$do = array("pm_bf","pm_bl","pm_brv");	
												}else{
													$do = array("pm_be","pm_br","pm_bf");
												}	
												foreach ($do as &$value) {
													if($prod[0] == "v" && $value == "pm_bf"){ 
														listingLivraison($value,$id_product,$solde,$prod[0],$coulissage);
													}else{
														listing($value,$id_product,$solde,$prod[0],$coulissage);
													}
												}
											}else{
												if($prod[0] == "v" && $mouvement == "pm_bf"){ 
													listingLivraison($mouvement,$id_product,$solde,$prod[0],$coulissage);
												}else{
													listing($mouvement,$id_product,$solde,$prod[0],$coulissage);
												}
											}
										} 
										
										
										?>
									<tfoot>
										<tr>
												<td class="text-right" colspan="4" ><b >Solde le  <? echo $_GET["date_out"];?> </b></td>
												<td class="text-center" id='tot' ><? echo number_format($solde,1, '.',' '); ?></td>
										</tr>		                                                
									</tfoot>


                                    </tbody>
                                </table>
                            </div>
									

					
                </div>
            </div>
        </div>
    </div>
</body>
</html>

<?php
$_SESSION['msg_error'] = "";
$_SESSION['msg_success'] = "";
$_SESSION['msg_notice'] = ""; 

//================== Function ===============
function listing($mouv,$id_product,$solde,$type,$coulissage)
{
	global $db;
	global $solde;
											
											$mouvementP = str_replace("pm","id",$mouv) ;
											

											if($mouv <> '0'){
												if($mouv == 'pm_bf' || $mouv == 'pm_bl' || $mouv == 'pm_brv'){
													$dateS = str_replace("pm","date",$mouv);
												}else{
													$dateS = "date_entre";
												}
												if($_GET["date_in"] == $_GET["date_out"]){
													$query = "select * from ".$mouv." where ".$dateS." >= '".strtotime($_GET["date_in"])."' AND ".$dateS." <= '".strtotime($_GET["date_out"].' + 1 DAY')."' ORDER BY ".$dateS." ASC";
												}else{
												$query = "select * from ".$mouv." where ".$dateS." >= '".strtotime($_GET["date_in"])."' AND ".$dateS." <= '".strtotime($_GET["date_out"])."' ORDER BY ".$dateS." ASC";								
												}
												// echo $query."<br>" ;
												$result = @$db->query($query);
												if($result !== false){
													foreach($result as $row){	
														$queryP = "select SUM(qte) as sum from ".$mouv."_product where ".$mouvementP." = ".$row["id"];
														if($_GET["product"] <> '0'){
															if($mouv == 'pm_bf' || $mouv == 'pm_bl' || $mouv == 'pm_brv'){
																$queryP .= " AND id_produits = ".$id_product;
															}else{
																$queryP .= " AND name = ".$id_product;
															}
														}
														// echo $queryP.";<br>" ;
														$resultP = @$db->query($queryP);
														$row_p = $resultP->fetch();
														
														$sum = $row_p["sum"];
														if($sum === NULL) { $sum = 0; }
														if($type == "a"){
															if( $mouv == "pm_bf" || $mouv == "pm_br"){
																$sum = $sum *(-1);
															}
														}else{
															if( $mouv == "pm_bl" ){
																$sum = $sum *(-1);
															}															
														}
														
																												
														if($sum <> 0){
															$solde += $sum;
															
															$qte_embal = $sum / $coulissage ;
															$qte_embal_solde = $solde / $coulissage ;
															
															echo '<tr>
															<td class="text-center"><b id="'.$row[$dateS].'">'.date("d-m-Y",$row[$dateS]).'</b></td>
															<td class="text-center">'.get_type($mouv).'</td>
															<td class="text-center"><b>'.get_ref($mouv,$row["id"]).'</b></td>
															<td class="text-center"><input type="hidden" class="price" value="'.$sum.'" />'.number_format($sum,1, '.',' ').' / '.number_format($qte_embal,1, '.',' ').'</td>
															<td class="text-center total">'.number_format($solde,1, '.',' ').' / '.number_format($qte_embal_solde,1, '.',' ').'</td>
															</tr>';
														}														
														
													}	
												}
											}
}
//============================================
//============================================
function listingLivraison($mouv,$id_product,$solde,$type,$coulissage)
{
	global $db;
	global $solde;
											
											$mouvementP = str_replace("pm","id",$mouv) ;
											

											if($mouv <> '0'){
												if($mouv == 'pm_bf' || $mouv == 'pm_bl' || $mouv == 'pm_brv'){
													$dateS = str_replace("pm","date",$mouv);
												}else{
													$dateS = "date_entre";
												}
												if($_GET["date_in"] == $_GET["date_out"]){
													$query = "select * from ".$mouv." where ".$dateS." >= '".strtotime($_GET["date_in"])."' AND ".$dateS." <= '".strtotime($_GET["date_out"].' + 1 DAY')."' AND product= ".$id_product;
												}else{
												$query = "select * from ".$mouv." where ".$dateS." >= '".strtotime($_GET["date_in"])."' AND ".$dateS." <= '".strtotime($_GET["date_out"])."' AND product= ".$id_product;								
												}
												// echo $query ;
												$result = @$db->query($query);
												if($result !== false){
													foreach($result as $row){	
														
														$sum = $row["qte"];
														if($sum === NULL) { $sum = 0; }
														if($type == "a"){
															if( $mouv == "pm_bf" || $mouv == "pm_br"){
																$sum = $sum *(-1);
															}
														}else{
															if( $mouv == "pm_bl" ){
																$sum = $sum *(-1);
															}															
														}
														
																												
														if($sum <> 0){
															$solde += $sum;
															
															$qte_embal = $sum / $coulissage ;
															$qte_embal_solde = $solde / $coulissage ;
															
															echo '<tr>
															<td class="text-center"><b id="'.$row[$dateS].'">'.date("d-m-Y",$row[$dateS]).'</b></td>
															<td class="text-center">'.get_type($mouv).'</td>
															<td class="text-center"><b>'.get_ref($mouv,$row["id"]).'</b></td>
															<td class="text-center"><input type="hidden" class="price" value="'.$sum.'" />'.number_format($sum,1, '.',' ').' / '.number_format($qte_embal,1, '.',' ').'</td>
															<td class="text-center total">'.number_format($solde,1, '.',' ').' / '.number_format($qte_embal_solde,1, '.',' ').'</td>
															</tr>';
														}														
														
													}	
												}
											}
}
//============================================
//============================================

function get_type($type){
	switch ($type) {
		case "pm_be":
			$str = "Bon d'entrée";
			break;
		case "pm_br":
			$str = "Bon de retour - Achat";
			break;
		case "pm_bf":
			$str = "Bon de fabrication";
			break;
		case "pm_bl":
			$str = "Bon de livraison";
			break;
		case "pm_brv":
			$str = "Bon de retour - Vente";
			break;
	}

	return $str ;	
}
//====================
function get_ref($type,$ref){
	switch ($type) {
		case "pm_be":
			$str = "BE_00".$ref;
			break;
		case "pm_br":
			$str = "BR_00".$ref;
			break;
		case "pm_bf":
			$str = "BF_00".$ref;
			break;
		case "pm_bl":
			$str = "BL_00".$ref;
			break;
		case "pm_brv":
			$str = "BRV_00".$ref;
			break;
	}

	return $str ;	
}
?><script>	$( document ).ready(function() {				$( ".header" ).click(function() {			$(".total").html('-');			setTimeout(function(){ 				var total = 0;				$( ".price" ).each(function() {				 				  total += parseFloat($( this ).val()) ;				  $( this ).parent().next().html(total.toFixed(1));				});				$("#tot").html(total.toFixed(1));			}, 300);		});	});</script>
