<?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"];

?>
<!DOCTYPE html>
<head>
    <?php include("../../includes/inc_header_common.php"); ?>

</head>
<?
			$query_fact = "select * from pm_facture_achat where id =".$id_facture ;
			// echo "====>".$query_fact."<br>";
			$result_fact = @$db->query($query_fact);
			if($result_fact !== false){
				$row_fact = $result_fact->fetch();
				$ref_fact = $row_fact["ref_bl"];
				$fournisseur = $row_fact["fournisseur"];
				$validate = $row_fact["validate"];
				$remarque = $row_fact["remarque"];
				$date_entre = date("d-m-Y",$row_fact["date_entre"]);
				
				//==== Fournisseur =============
				$query_fr = "SELECT * FROM pm_fournisseurs WHERE id = ".$fournisseur;
				$result_fr = $db->query($query_fr);
				if($result_fr !== false && $db->last_row_count() > 0){
					$row_fr = $result_fr->fetch();																
					$fournisseur = $row_fr['name'];
				}				
			}

			
		if($validate == 1){
?>
<script>
    $(document).ready(function() {
		$("#validate").hide();
		$("input").each(function( index ) {
		  $(this).attr("readonly","readonly");
		});
	});
</script>		
<?
		}
?>
<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> Facture Achat N° <span style="color:red;"><? echo $ref_fact ;?></span> le <span style="color:red;"><? echo $date_entre; ?></span> - Fournisseur : <span style="color:red;"><? echo $fournisseur; ?></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">
	<h3>Remarque : <? echo $remarque; ?></h3>	
	<br>
      <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>            
            </tr>
         </thead>
         <tbody>
		 
		 <?
		 
			$qte_all 	 = 0;
			$prix_ht_all = 0;
			$array_tva = array();
			$array_tva_qte = array();
			$i = 0;
			
			$query_fact = "select * from pm_facture_achat where id =".$id_facture ;
			// echo "====>".$query_fact."<br>";
			$result_fact = @$db->query($query_fact);
			if($result_fact !== false){
				$row_fact = $result_fact->fetch();
				// $ref_fact = $row_fact["ref_bl"];
				$ref_bl = $row_fact["ref_be"];
				$timbre = $row_fact["timbre"];
				$array_bl = explode(",", $ref_bl);
				$count_bl = count($array_bl);
				// echo "===>".$count_bl[0];
				//========= Recuperé les produits =====
				for ($x = 0; $x < $count_bl; $x++)
				{	
					// echo "====>".$count_bl[$x];
					$query_prod = "SELECT * FROM `pm_produitsachat`as a , pm_be_product as b WHERE a.id = b.name AND b.qte > 0 AND b.id_be = ".$array_bl[$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"];	
						$remise = $row_2["remise"];	
						$remise_be = $row_2["remise1"];	
						if($remise_be){
							$remise = $remise_be;
						}
						// echo "momo ==> ".$row_2["tva"]; 
						// echo "tva ".$row_2["tva"]." ==> ".$row_2["prix"]." =//=> ".$i."<br>";
						$array_tva[$i] = $row_2["tva"];				
						
						$array_tva_qte[$row_2["tva"]] += $row_2["prix"];
					?>
					<input type="hidden" id="tva_<? echo $row_2["id"]; ?>" class="get_tva tva_<? echo $row_2["tva"]; ?>" value="<? echo $row_2["tva"]; ?>">
					<input type="hidden" id="fodec_<? echo $row_2["id"]; ?>" value="<? echo $row_2["fodec"]; ?>">
					<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 $prix_ht ; ?>">
					   </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; ?>">
					   </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>

					</tr>
				
	<?	
					$qte_all 	 = $qte_all + $qte;
					$prix_ht_all = $prix_ht_all + $prix_ht;
					$i++;
						}
					}
				}
				//========= Recuperé les produits ajouté manuellment =====
				$query_manelle = "SELECT * FROM `pm_produitsachat`as a , pm_facture_achat_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){
							
							// echo "tva ".$row_man["tva"]." ==> ".$row_man["prix"]." ==> ".$i."<br>";
							// $array_tva[$i] = $row_man["tva"];
							// $array_tva_qte[$row_man["tva"]] += $row_man["prix"];
?>


					<input type="hidden" id="tva_a-<? echo $row_man["id"]; ?>" class="get_tva tva_<? echo $row_man["tva"]; ?>" value="<? echo $row_man["tva"]; ?>">
					<input type="hidden" id="fodec_a-<? echo $row_man["id"]; ?>" value="<? echo $row_man["fodec"]; ?>">
					<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"  name="qte" id="qte_a-<? echo $row_man["id"]; ?>" value="<? echo $row_man["qte"]; ?>">
					   </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 $row_man["prix"] ; ?>">
					   </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 $row_man["remise"];; ?>">
					   </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>

					</tr>


<?							
						$i++;
						}	
					}	
				
				//================ 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>

					</tr>
			<?	
			
			}			
		 
		 
		 ?>
		  
         </tbody>
      </table>
<div style="width: 50%;float: left;">	  
      <table class="table table-bordered table-hover table-striped form-table" id="table_calc_1" >
         <thead id="tva">
		
            <tr>
               <td><b>Total</b></td>            
               <td align="right"><b class="all_total_tva"></b></td>                   
            </tr>			
         </thead>
         <tbody></tbody>
	</table>	
</div>
<div style="width: 50%;float: left;">	
      <table class="table table-bordered table-hover table-striped form-table" id="table_calc_2" >
         <thead>
            <tr>       
               <td align="right"><b>Total HT brute</b></td>            
               <td align="right"><b class="brute_ht_all"></b></td>            
            </tr>
           <tr>       
               <td align="right"><b>Montant remise</b></td>            
               <td align="right"><b class="remise_ht_all"></b></td>            
            </tr>
           <tr>       
               <td align="right"><b>Total HT net</b></td>            
               <td align="right"><b class="total_ht_all"></b></td>            
            </tr>
           <tr>       
               <td align="right"><b>Total FODEC</b></td>            
               <td align="right"><b class="fodec_product_all"></b></td>            
            </tr>
           <tr>       
               <td align="right"><b>Total TVA</b></td>            
               <td align="right"><b class="all_total_tva"></b></td>            
            </tr>
           <tr>       
               <td align="right"><b>Timbre</b> <input id="timbre" type="checkbox" <? if($timbre == 1){ ?>checked="checked"<? } ?> ></td>            
               <td align="right"><b id="timbre_champ">1.000</b></td>            
            </tr>
           <tr>       
               <td align="right"><b>Total TTC</b></td>            
               <td align="right"><b id="total_ttc_all"></b></td>            
            </tr>

         </thead>
         <tbody></tbody>
	</table>	
</div>	
   </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" 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;
}
#table_calc_1, #table_calc_2{
	width:100% !important;	
    background-color: #c1c1c1;
}
#table_calc_1 td, #table_calc_2 td{
    border: solid 1px #000;
}
</style>
<script>
    $(document).ready(function() {

	function calc_facture(action)
	{
		var cnt = 0;
		var timbre = 1.000 ;
		var timbre_stat = 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 fodec_product_all = 0;
		var id_facture = <? echo $_GET["id"]; ?>;
		var str  = "";
		var mysql  = "";
		var taux_tva_all = new Array();
		
		//======== Delet from facture gen ====================
		var str = "DELETE FROM `pm_facture_gen` WHERE id_facture="+id_facture+" ;";
		// mysql_exc(delet);
		//========================= Calcule taux TVA ===========================


		// console.log(monArraySeria);		
		//====================================================
		$( ".qte" ).each(function() {
		//======== Timbre ===========
		if($("#timbre").is(':checked')){
			 timbre = 1.000 ;
			 timbre_stat = 1 ;
			 $("#timbre_champ").html("1.000");
		} else {
			 timbre = 0 ;
			 timbre_stat = 0 ;
			 $("#timbre_champ").html("-");
		}		
		//===========================	
		  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 fodec = $("#fodec_"+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 = parseFloat(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 Fodec ======
		  // if (isNaN(parseFloat(total_ht_net))) { total_ht_net = 0 ;}
		  var fodec_product = (total_ht_net * fodec)/100 ;
		  // =======  Taux TVA ======
		  var taux_tva = ((total_ht_net+fodec_product)*tva)/100 ;	
		  // console.log("Tau_TVA ==>"+tva+' ==> '+taux_tva);				  
		  // =======  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;
		  fodec_product_all += fodec_product;
		  if (taux_tva_all[tva] == null){
			  taux_tva_all[tva] = 0;
		  }
			 
		  taux_tva_all[tva] += parseFloat(taux_tva);
		  
		  
		  
		  // $("#pu_all").val(pu_all.toFixed(3));
		  $("#brute_ht_all").val(formatNumber(total_ht_all));
		  $(".brute_ht_all").html(formatNumber(total_ht_all));
		  $(".fodec_product_all").html(formatNumber(fodec_product_all));
		  $("#remise_ht_all").val(formatNumber(remise_all));
		  $(".remise_ht_all").html(formatNumber(remise_all));
		  $("#total_ht_all").val(formatNumber(total_ht_net_all));
		  $(".total_ht_all").html(formatNumber(total_ht_net_all));
		  
		  
		  str += "insert into pm_facture_gen (`id_facture`, `code`, `designation`, `qte`, `pu_ht`, `ht_brute`, `remise`, `remise_ht`, `ht_net`, `total_ttc`) VALUES ('"+id_facture+"','"+code+"','"+desig+"','"+qte+"','"+pu+"','"+remise+"','"+formatNumber(remise_ht)+"','"+tva+"','"+formatNumber(total_ht_net)+"','"+formatNumber(total_ttc)+"');";
		  // $(".result").html(str);
		  
		//===== UPDATE IN DB ===============
		  var indexy = index;
		  var index_id	= indexy.split("-");
		  var index_id_ref = index_id[0];
		  var index_id_num = index_id[1];
		  // console.log("index_id ==> " + index_id_num);
		  
		  if(remise == ""){ remise = 0; }
		  // remise = parseFloat(remise);
		  
		  if(index_id_ref == "a"){
			  mysql = "UPDATE `pm_facture_achat_product` SET qte ='"+qte+"' , prix = '"+pu+"', remise = '"+remise+"' where id="+index_id_num+" ;";
			  // alert(mysql);	
			if(action == 1){
				mysql_exc(mysql);
			}				
		 }else{
			mysql = "UPDATE `pm_be_product` SET qte ='"+qte+"' , prix = '"+pu+"', remise1 = '"+remise+"' where id="+index+" ;";
			  // console.log(mysql);	
			if(action == 1){
				mysql_exc(mysql);
			}
		 }
		  // console.log(mysql);
		});
		
		var tva = "DELETE FROM `pm_facture_achat_tva` WHERE id_fac ="+id_facture+" ;";
		
		var monArraySeria = '<tr><td><b>Taux TVA</b></td><td align="right"><b>Montant TVA</b></td></tr>';
		var all_total_tva = 0;
		for (var i in taux_tva_all)
		{
			// alert(i);
			if(i != 0){
				monArraySeria += '<tr><td>TVA '+i+'%</td><td align="right">'+formatNumber(taux_tva_all[i])+'</td></tr>';
				tva += "INSERT INTO `pm_facture_achat_tva`(`id_fac`, `tva`, `montant_tva`) VALUES ("+id_facture+","+i+","+taux_tva_all[i].toFixed(3)+");";
				$('#total_tva_'+i).html(formatNumber(taux_tva_all[i]));
				all_total_tva += taux_tva_all[i] ;
				// monArraySeria += 'Key: ' + i + '; Valeur: ' + taux_tva_all[i] + "\r\n";
			}
			
		}
		 monArraySeria += '<tr><td><b>TOTAL</b></td><td align="right"><b>'+formatNumber(all_total_tva)+'</b></td></tr>';
		$('#tva').html(monArraySeria);
		$(".all_total_tva").html(formatNumber(all_total_tva));
		// console.log(monArraySeria);
		// =========== update table TVA ==============
		mysql_exc(tva);
		
		//========= Total TTC ===========
		 var TTC = parseFloat(total_ht_net_all) + parseFloat(fodec_product_all) + parseFloat(all_total_tva) + timbre;
		 // console.log("TTC ===> "+TTC);
		$("#total_ttc_all").html(formatNumber(TTC));
		
		// if(action == 1){
			// console.log("aa");
			var update_ttc = "UPDATE `pm_facture_achat` SET total_ttc = "+ TTC.toFixed(3) + ", timbre ="+timbre_stat+", fodec ="+fodec_product_all.toFixed(3)+", total_ht ="+total_ht_net_all.toFixed(3)+" where id = "+id_facture ;
			// alert(update_ttc);
			mysql_exc(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 x1 + x2;
	}	
	//==========================================
function mysql_exc(str)
{
	
	<? if($_GET["no_edit"] <> 1){ ?>
		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);
	$(document).on( "change",".pu, .remise, .qte",function() {	
		calc_facture(1);
	});
	//======== if timbre
	$(document).on( "change","#timbre",function() {	
		calc_facture(1);
	});
	$(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_achat` SET validate = 1 where id="+id_facture;
			mysql_exc(mysql);
			setTimeout(function(){ document.location.href="index.php?view=list"; }, 500);
			
		}
	});
	
		
});
</script>	
<?php
$_SESSION['msg_error'] = "";
$_SESSION['msg_success'] = "";
$_SESSION['msg_notice'] = ""; ?>
