<?php

ini_set('display_errors', 1);
define("ADMIN", true);
require_once("../../../common/lib.php");
require_once("../../../common/define.php");
// define("TITLE_ELEMENT", 'Facture');
if(!isset($_SESSION['user'])){
    header("Location: /admin/login.php");
    exit();
}
require_once("../../includes/fn_module.php"); ?>


<?
	$id_facture = $_GET["id"];

	
			$query_fact = "select * from pm_facture_avoir_vente where id =".$id_facture ;
			// echo "====>".$query_fact;
			$result_fact = @$db->query($query_fact);
			if($result_fact !== false){
				$row_fact = $result_fact->fetch();
				$idd = $row_fact["idd"];
			}	
?>
<!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-bolt"></i> Générateur Facture : <span style="color:red;"><? echo $idd;?></span></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="#">				

	<div class="panel panel-default">
		<div class="panel-body">

<div class="col-lg-12">
   <div class="table-responsive">
      <table class="table table-bordered table-hover table-striped form-table" id="table_facture_achat_product">
         <thead>
            <tr>
               <th><b>Code article</b></th>
               <th><b>Désignation article</b></th>
               <th><b>Quantité</b></th>
               <th><b>P.U HT</b></th>
               <th><b>Total HT brute</b></th>
               <th><b>Remise(%)</b></th>
               <th><b>Montant remise HT</b></th>
               <th><b>Total HT Net</b></th>
               <th><b>Total TTC</b></th>               
            </tr>
         </thead>
         <tbody>
		 
		 <?
		 
			$qte_all 	 = 0;
			$prix_ht_all = 0;
			
			// $qur = "select * from pm_facture_avoir_vente where id =".$id_facture ;
			// echo "====>".$qur;
			// $result_qur = @$db->query($qur);
			// if($result_qur !== false){
				// $row_qur = $result_qur->fetch();
				// $ref_br = $row_qur["ref_br"];
			// }
			
			// $query_fact = "select * from pm_brv where id =".$ref_br ;
			$query_exist = "select COUNT(*) as cnt from pm_facture_avoir_vente_gen where id_facture =".$id_facture ;
			// echo $query_exist;
			$result_exist = @$db->query($query_exist);
			if($result_exist !== false){
				$row_exist = $result_exist->fetch();
				$exist = $row_exist["cnt"]; 
			}
			
			
			// If($exist > 0){
				// echo "===>".$exist ;
				// $query_fact = "select * from pm_facture_avoir_vente_gen where id_facture =".$id_facture ;
			// }else{
				$query_fact = "select * from pm_facture_avoir_vente where id =".$id_facture ;
			// }
			
			
			// echo "====>".$query_fact;
			$result_fact = @$db->query($query_fact);
			if($result_fact !== false){
				$row_fact = $result_fact->fetch();
				$ref_br = $row_fact["ref_br"];
				$array_br = explode(",", $ref_br);
				$count_bl = count($array_br);
				// echo "===>".$count_bl[0];
				//========= Recuperé les produits =====
				for ($x = 0; $x < $count_bl; $x++)
				{	
					// echo "====>".$count_bl[$x];
					$query_prod = "SELECT * FROM `pm_produits`as a , pm_brv_product as b WHERE a.id = b.id_produits AND b.id_brv = ".$array_br[$x] ;
					// echo "====>".$query_prod."<br>";
					$result_prod = @$db->query($query_prod);
					if($result_prod !== false){
						foreach($result_prod as $row_2){
							
						$qte     = 0;	
						$prix_ht = 0;	
						$remise  = 0;	
						$qte = $row_2["qte"];	
						$prix_ht = $row_2["prix_ht"];	
						$remise = $row_2["remise"];
						//=====================
						$prix_ht_bl = $row_2["prix_ht"];	
						$remise_bl = $row_2["remise"];	
						if($prix_ht_bl){
							$prix_ht_new = $prix_ht_bl;
						}else{
							$prix_ht_new = $prix_ht;
						}
						if($remise_bl){
							$remise_new = $remise_bl;
						}else{
							$remise_new = $remise;
						}
				?>
					<input type="hidden" id="tva_<? echo $row_2["id"]; ?>" value="<? echo $row_2["tva"]; ?>">
					<tr>
					   <td class="text-center input-text numeric form-inline">						  
						  <input type="text" class="form-control text-center code_article" readonly="readonly" name="code_article" id="code_article_<? echo $row_2["id"]; ?>" value="<? echo $row_2["code_produit"]; ?>">
					   </td>
					   <td class="text-center input-text textbig">
						  <input type="text" class="form-control des_article" readonly="readonly" name="des_article" id="des_article_<? echo $row_2["id"]; ?>" value="<? echo $row_2["desingnation"]; ?>">
					   </td>
					   <td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right qte" readonly="readonly" name="qte" id="qte_<? echo $row_2["id"]; ?>" value="<? echo $qte; ?>">
					   </td>
						<td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right pu"  name="pu" id="pu_<? echo $row_2["id"]; ?>" value="<? echo number_format($prix_ht_new, 3) ; ?>">
					   </td>
					   <td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right total_ht_brute" readonly="readonly" name="total_ht_brute" id="total_ht_brute_<? echo $row_2["id"]; ?>" value="">
					   </td>
					   <td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right remise" name="remise" id="remise_<? echo $row_2["id"]; ?>" value="<? echo $remise_new; ?>">
					   </td>
					   <td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right montant_remise_ht" readonly="readonly" name="montant_remise_ht" id="montant_remise_ht_<? echo $row_2["id"]; ?>" value="">
					   </td>
					   <td class="text-right input-text form-inline">
						  <input type="text" class="form-control text-right total_ht_net" readonly="readonly" name="total_ht_net" id="total_ht_net_<? echo $row_2["id"]; ?>" value="">
					   </td>
					   <td class="text-right input-text form-inline">
						  <input type="text" class="form-control text-right total_ttc" readonly="readonly" name="total_ttc" id="total_ttc_<? echo $row_2["id"]; ?>" value="">
					   </td>
					</tr>
				
				<?	
					$qte_all 	 = $qte_all + $qte;
					// $prix_ht_all = $prix_ht_all + $prix_ht;
				
						}
					}
				}
				//========= Recuperé les produits ajouté manuellment =====
				$query_manelle = "SELECT * FROM `pm_produitsachat`as a , pm_facture_avoir_vente_product as b WHERE a.id = b.name AND b.id_fac = ".$id_facture ;
				// echo "====>".$query_manelle."<br>";
				$result_manelle = @$db->query($query_manelle );
					if($result_manelle !== false){
						foreach($result_manelle as $row_man){
							
							$qte_a = $row_man["qte"];	
							$prix_ht_a = $row_man["prix"];	
							$remise_a = $row_man["remise"];
							
							$qte_all 	 = $qte_all + $qte_a;
?>

					<input type="hidden" id="tva_a-<? echo $row_man["id"]; ?>" value="<? echo $row_man["tva"]; ?>">
					<tr>
					   <td class="text-center input-text numeric form-inline">						  
						  <input type="text" class="form-control text-center code_article" readonly="readonly" name="code_article" id="code_article_a-<? echo $row_man["id"]; ?>" value="<? echo $row_man["code_produit"]; ?>">
					   </td>
					   <td class="text-center input-text textbig">
						  <input type="text" class="form-control des_article" readonly="readonly" name="des_article" id="des_article_a-<? echo $row_man["id"]; ?>" value="<? echo $row_man["desingnation"]; ?>">
					   </td>
					   <td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right qte" readonly="readonly" name="qte" id="qte_a-<? echo $row_man["id"]; ?>" value="<? echo $qte_a; ?>">
					   </td>
						<td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right pu"  name="pu" id="pu_a-<? echo $row_man["id"]; ?>" value="<? echo number_format($prix_ht_a, 3,'.','') ; ?>">
					   </td>
					   <td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right total_ht_brute" readonly="readonly" name="total_ht_brute" id="total_ht_brute_a-<? echo $row_man["id"]; ?>" value="">
					   </td>
					   <td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right remise" name="remise" id="remise_a-<? echo $row_man["id"]; ?>" value="<? echo $remise_a; ?>">
					   </td>
					   <td class="text-right input-text numeric form-inline">
						  <input type="text" class="form-control text-right montant_remise_ht" readonly="readonly" name="montant_remise_ht" id="montant_remise_ht_a-<? echo $row_man["id"]; ?>" value="">
					   </td>
					   <td class="text-right input-text form-inline">
						  <input type="text" class="form-control text-right total_ht_net" readonly="readonly" name="total_ht_net" id="total_ht_net_a-<? echo $row_man["id"]; ?>" value="">
					   </td>
					   <td class="text-right input-text form-inline">
						  <input type="text" class="form-control text-right total_ttc" readonly="readonly" name="total_ttc" id="total_ttc_a-<? echo $row_man["id"]; ?>" value="">
					   </td>
					</tr>
				
							
<?							
						}	
					}	
				
				//================ TOTAL =====================
				?>
			
					
					<tr>
					   <td class="text-center" colspan="2">						  
						 <b>TOTAL</b>
					   </td>
					   <td class="text-center input-text numeric form-inline">
						  <input type="text" class="form-control text-right " readonly="readonly" value="<? echo $qte_all; ?>" style=" font-weight: bold;">
					   </td>
						<td class="text-right input-text numeric form-inline">
						  
					   </td>
					   <td class="text-center input-text numeric form-inline">
						  <input type="text" class="form-control text-right " id="brute_ht_all" readonly="readonly" value="" style=" font-weight: bold; ">
					   </td>
					   <td class="text-center input-text numeric form-inline">
						  
					   </td>
					   <td class="text-center input-text numeric form-inline">
						  <input type="text" class="form-control text-right " id="remise_ht_all"readonly="readonly" value="" style=" font-weight: bold; ">
					   </td>
					   <td class="text-center input-text form-inline">
						  <input type="text" class="form-control text-right " id="total_ht_all" readonly="readonly" value="" style=" font-weight: bold; ">
					   </td>
					   <td class="text-center input-text form-inline">
						  <input type="text" class="form-control text-right " id="total_ttc_all" readonly="readonly" value="" style=" font-weight: bold;color:red; ">
					   </td>
					</tr>
			<?	
			}			
		 
		 
		 ?>
		 

         </tbody>
      </table>
   </div>
</div>		
		
		
		
		</div>
	</div>
	<div class="panel panel-default">
		<div class="panel-body">
			   
			   <div class="col-lg-12 result">
			   <div class=" form-inline text-right">
				
						<button type="button" class="btn btn-success mt15" id='saved' data-toggle="tooltip" data-placement="bottom" title="Imprimer">
							<i class="fa fa-floppy-o"></i><span class="hidden-sm hidden-xs"> Sauvgarder</span>
						</button>
					<div class=" form-inline text-right">
					<a href="print.php?id=<? echo $id_facture; ?>" >
						<button type="button" class="btn btn-default mt15" data-toggle="tooltip" data-placement="bottom" title="Imprimer">
							<i class="fa fa-print"></i><span class="hidden-sm hidden-xs"> Imprimer</span>
						</button>
					</a>	
				  </div>
				  <div class=" form-inline text-right">
					
						<button type="button" id="validate" class="btn btn-default mt15" data-toggle="tooltip" data-placement="bottom" title="Valider" style="background-color: #f24937;" >
							<i class="fa fa-check "></i><span class="hidden-sm hidden-xs"> Valider</span>
						</button>
						
				  </div>
			   </div>
		 </div>
	</div> 

</form>	
									
                    <?php
                    if($db !== false){
                        
                    } ?>
					
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<style>
.form-table td.input-text.numeric {
    max-width: 250px !important;
}
.form-table td.input-text.textbig {
    max-width: 400px !important;
	width: 400px !important;
}
</style>
<script>
    $(document).ready(function() {

	function calc_facture(action)
	{
		var cnt = 0;
		var pu_all = 0;
		var total_ht_all = 0;
		var remise_all = 0;
		var total_ht_net_all = 0;
		var total_ttc_all = 0;
		var id_facture = <? echo $_GET["id"]; ?>;
		var str  = "DELETE FROM `pm_facture_avoir_vente_gen` WHERE `id_facture` = "+id_facture+";";
		
		
		
		$( ".qte" ).each(function() {
		  var index = $(this).attr("id");
		  index	= index.split("_");
		  index = index[1];
		  var qte = $( this ).val();
		  var pu  = $( this ).parent().next().children().val();
		  var remise  = $( this ).parent().next().next().next().children().val();
		  var tva = $("#tva_"+index).val();
		  var desig  = $( this ).parent().prev().children().val();
		  var code  = $( this ).parent().prev().prev().children().val();
		  // console.log(tva);
		  // =======  Total HT ======
		  var total_ht = parseInt(qte) * pu ;
		  $("#total_ht_brute_"+index).val(formatNumber(total_ht));
		  // =======  Montant remise HT ======
		  var remise_ht = (remise * total_ht)/100;
		  $("#montant_remise_ht_"+index).val(formatNumber(remise_ht));
		  // =======  Total HT Net ======
		  var total_ht_net = total_ht- remise_ht;
		  $("#total_ht_net_"+index).val(formatNumber(total_ht_net));
		  // =======  Total ttc ======
		  var total_ttc = total_ht_net + parseFloat((total_ht_net*tva)/100);
		  // console.log(total_ttc);
		  $("#total_ttc_"+index).val(formatNumber(total_ttc));
		  
		  // TOTAUX ==============
		  pu_all += parseFloat(pu);
		  total_ht_all += total_ht;
		  remise_all += parseFloat(remise_ht);
		  total_ht_net_all += total_ht_net;
		  total_ttc_all += total_ttc;
		  
		  // $("#pu_all").val(pu_all.toFixed(3));
		  $("#brute_ht_all").val(formatNumber(total_ht_all));
		  $("#remise_ht_all").val(formatNumber(remise_all));
		  $("#total_ht_all").val(formatNumber(total_ht_net_all));
		  $("#total_ttc_all").val(formatNumber(total_ttc_all));
		  
		  str += "insert into pm_facture_avoir_vente_gen (`id_facture`, `code`, `designation`, `qte`, `pu_ht`, `ht_brute`, `remise`, `remise_ht`, `ht_net`, `total_ttc`) VALUES ('"+id_facture+"','"+code+"','"+desig+"','"+qte+"','"+pu+"','"+formatNumber(total_ht)+"','"+remise+"','"+formatNumber(remise_ht)+"','"+formatNumber(total_ht_net)+"','"+formatNumber(total_ttc)+"');";
		  // $(".result").html(str);
		  str += "UPDATE `pm_facture_avoir_vente_product` SET prix = '"+ pu + "', remise='"+remise+"' where id_fac = '"+id_facture+"';" ;
		  
		  
		});
		if(action == 1){
						
			mysql_exc(str); //=============== ici
			console.log(str);
			//=========== Update - Total TTC ========
			var TTC = total_ttc_all ;
			var update_ttc = "UPDATE `pm_facture_avoir_vente` SET total_ttc = '"+ TTC.toFixed(3) + "' where id = "+id_facture ;
			// console.log(update_ttc);
			mysql_exc(update_ttc); //=============== ici
			// console.log(update_ttc);
		}
		
	}
	
	//==========================================
	function formatNumber(number)
	{
		number = number.toFixed(3) ;
		// x = number.split('.');
		// x1 = x[0];
		// x2 = x.length > 1 ? '.' + x[1] : '';
		// var rgx = /(\d+)(\d{3})/;
		// while (rgx.test(x1)) {
			// x1 = x1.replace(rgx, '$1' + ' ' + '$2');
		// }
		return number;
	}	
	//==========================================
function mysql_exc(str)
{
		var url_get = "/admin/ajax/mysql_exc.php"
				
			$.ajax({
                url: url_get,
                type: "POST",
                       data: {
                           query: str,
                       },
                       dataType: "JSON",
                       success: function (jsonStr) { 
						var text = JSON.stringify(jsonStr) ;
						console.log(text);						
                       }
             });		  
}	
	//==========================================
	calc_facture(0);
	
	// if(count_recharge == 0){
		// calc_facture(1);
		// count_recharge++;
	// }else{
		// calc_facture(0);
	// }
	// $(document).on( "keyup",".pu, .remise",function() {	
	$(document).on( "click","#saved",function() {	
		calc_facture(1);
		$(".table-responsive").fadeOut(500).fadeIn(500);
	});
	
	$(document).on( "click","#validate",function() {	
		if (confirm("Êtes-vous sûr de vouloir valider la facture !")) {
			var id_facture = <? echo $_GET["id"]; ?>;
			mysql = "UPDATE `pm_facture_avoir_vente` SET validate = 1 where id="+id_facture;
			// alert(mysql);
			mysql_exc(mysql);
			setTimeout(function(){ document.location.href="index.php?view=list"; }, 500);
			
		}
	});
		
});
</script>	
<?php
$_SESSION['msg_error'] = "";
$_SESSION['msg_success'] = "";
$_SESSION['msg_notice'] = ""; ?>
