<?php
ini_set('display_errors', 0);

require_once("../../common/lib.php");
require_once("../../common/define.php");

if(!isset($_SESSION['user'])){
    header("Location: login.php");
    exit();
}

$id = $_GET["id"];

$query = "SELECT * from pm_produitsachat as a where a.id=  ".$id ;
// echo $query ;
$result = @$db->query($query);
$cont = 0 ;
$outp = array();
if($result !== false){
	// $outp = $result->fetch();
	foreach($result as $row){
		
		$outp[$cont]["id"] = $row["id"];
		$outp[$cont]["unite"] = $row["unite"];
		$outp[$cont]["coulissage"] = $row["coulissage"];
		$outp[$cont]["ids_be"] = get_be($row["id"]);
		
		$cont++;	
	} 
	
	echo json_encode($outp);
	
}	


function get_be($id_product)
{
	global $db;
	$ids_be = "";
	$test_qte_be = 0 ;
	$query_be = "SELECT id_be FROM pm_be_product WHERE name = ".$id_product;
	
	$result_be = @$db->query($query_be);
	if($result_be !== false){
		foreach($result_be as $row_be){
			$test_qte_be = get_qte_be($id_product,$row_be["id_be"]) ;
			// echo  "test_qte_be ==> ".$test_qte_be."<br>";
			if($test_qte_be > 0){
				$ids_be .= $row_be["id_be"].",";
			}
		}
	}
	if($ids_be <> ""  ){
		return substr($ids_be, 0, -1);	
	}else{
		return "";
	}
}



function get_qte_be($id_product,$id_be)
{
	global $db;
	
	
	$id = $id_product;
	// $id_be = $id_be;

	$qte_sortie = 0 ;
	$qte_valide = 0 ;

	//====================== QTE utiliser
	$query_sorti = "SELECT SUM(qte) as all_qte FROM pm_bf_product WHERE id_be = ".$id_be." AND id_produits = ".$id;
	// echo $query_sorti;
	$result_sorti = @$db->query($query_sorti);
	if($result_sorti !== false){
	$outp_sorti = $result_sorti->fetch();
		$qte_sortie += $outp_sorti["all_qte"];
	}	
	//====================== BS
	
	$query_sorti = "SELECT SUM(qte) as all_qte FROM pm_br_product WHERE id_be = ".$id_be." AND name = ".$id;
	// echo $query_sorti;
	$result_sorti = @$db->query($query_sorti);
	if($result_sorti !== false){
	$outp_sorti = $result_sorti->fetch();
		$qte_sortie += $outp_sorti["all_qte"];
	}	
	//======================
	
	
	
	

		$cont = 0 ;
		$outp = array();



	if($id_be > 276 ){
		
		$query = "SELECT qte FROM pm_be_product WHERE id_be = ".$id_be." AND name = ".$id;
		$result = @$db->query($query);
		if($result !== false){
			// $outp = $result->fetch();
			foreach($result as $row){
				
				$qte_valide = $row["qte"] - $qte_sortie;
		
			} 	
		}
		
	}else{
		
	//====================== QTE ecart

	$query_e = "SELECT SUM(qte) as all_qte FROM pm_be_ecart WHERE id_be = ".$id_be." AND id_produit = ".$id;
	// echo $query_e;
	$result_e = @$db->query($query_e);
	if($result_e !== false){
	$outp_e = $result_e->fetch();
		// $qte_sortie += $outp_sorti["all_qte"];
		$qte_valide = $outp_e["all_qte"] - $qte_sortie;
	}	
	//======================	
		
	}



	return $qte_valide;

}	


?>