<?php
debug_backtrace() || die ("Direct access not permitted");
require_once("inc_header_common.php"); ?>




<script src="<?php echo DOCBASE.ADMIN_FOLDER; ?>/js/plugins/ckeditor/ckeditor.js"></script>
<script src="<?php echo DOCBASE.ADMIN_FOLDER; ?>/js/plugins/ckeditor/adapters/jquery.js"></script>
<script>
    $(function(){
        $('select[name="multiple_actions_file"]').on('change', function(){
            if(($(this).val() == 'delete_multi_file' && confirm('<?php echo $texts['DELETE_CONFIRM1']." ".$texts['LOOSE_DATAS']; ?>'))
            || ($(this).val() != 'delete_multi_file' && confirm('<?php echo $texts['ACTION_CONFIRM']." ".$texts['LOOSE_DATAS']; ?>')))
                $('#form').attr('action','index.php?view=form&csrf_token=<?php echo $csrf_token; ?>&action='+$(this).val()).submit();
        });
        $('.btn-slide').on('click', function(){
            var library = $('#wrap-library');
            if($(this).hasClass('left')){
                $(this).removeClass('left').addClass('right');
                library.animate({
                    right:'0px'
                }, 1000);
            }else{
                $(this).removeClass('right').addClass('left');
                library.animate({
                    right:-library.width()+'px'
                }, 1000);
            }
            return false;
        });
        $('.actions-file a').on('click', function(){
            if(!confirm('<?php echo $texts['ACTION_CONFIRM']." ".$texts['LOOSE_DATAS']; ?>')) return false;
        });
        $('textarea[data-editor="1"]').ckeditor();
        
        if($('.datepicker').length){
            $('.datepicker').datepicker({
                dateFormat: 'dd/mm/yy',
                minDate: null
            });
        }
        $('.add_option').on('click', function(){
            var list_id = $(this).attr('rel');
            $('#'+list_id+'_tmp > option:selected').remove().appendTo('#'+list_id);
            $('#'+list_id+' > option').prop('selected', true);
            return false;
            
        });
        $('.remove_option').on('click', function(){
            var list_id = $(this).attr('rel');
            $('#'+list_id+' > option:selected').remove().appendTo('#'+list_id+'_tmp');
            $('#'+list_id+' > option').prop('selected', true);
            return false;
        });
        $('.new_entry').on('click', function(){			
            var table = $($(this).attr('href'));
			// //console.log(table);
            var row = $('tr', table);
            var index = row.length-1;
            row = row.last().clone();
            $('input, textarea', row).val('');
            $('select > option', row).prop('selected', false);
            $('checkbox, radio', row).prop('checked', false);
            $('input, textarea, select, checkbox, radio', row).each(function(){
                old_name = $(this).attr('name');
                $(this).attr('name', old_name.replace(/([a-zA-Z_0-9\[\]]+)\[([0-9]+)\](\[\])?/, '$1['+index+']$3'));
            });
            row.appendTo(table);
            return false;
        });
        $('form').on('submit', function(){
            $('#overlay').show();
        });
        if($('textarea[data-editor="1"]').length){
            setTimeout(function(){
                $('.btn-slide').trigger('click');
            }, 800);
        }
		
		
		
	// =========== Module bon de commande =================
	// var array_module = ['bc','be','br','facture_achat','facture_avoir_vente'];
	var array_module = ['be','br','facture_achat','facture_avoir_vente'];
	var module_name = "<?php echo MODULE; ?>" ;
	// alert(module_name);
	if(jQuery.inArray(module_name, array_module) != -1){
	// if(module_name == "bc"){
		$(document).on( "change","#table_"+module_name+"_product select",function() {
			var val_select = $(this).val();
			var name_select = $(this).attr("name");
			var res = name_select.split("[");
			// var index = res[1].toString().substr(0, 1);
			var index = res[1].replace("]","");

				var url_get = "/admin/ajax/get_product.php"
				
			
                   $.ajax({
                       url: url_get,
                       type: "GET",
                       data: {
                           id: val_select,
                       },
                       dataType: "JSON",
                       success: function (jsonStr) { 
						var text = JSON.stringify(jsonStr) ;
						//console.log(text);
						var obj = JSON.parse(text);
							$( "input[name*='"+module_name+"_product_prix_0["+index+"]']").val(obj.prix_ht);
							$( "input[name*='"+module_name+"_product_coulissage_0["+index+"]']").val(obj.coulissage);
							$( "select[name*='"+module_name+"_product_unite_0["+index+"]']").val(obj.unite);
							// alert(obj.unite);

                       }
                   });
				   

			
		});
		
		$(document).on( "keyup","#table_"+module_name+"_product input",function() {
			var name_select = $(this).attr("name");
			var res = name_select.split("[");
			var index = res[1].replace("]","");
			var qte = $( "input[name*='"+module_name+"_product_qte_0["+index+"]']").val();
			var coulissage = $( "input[name*='"+module_name+"_product_coulissage_0["+index+"]']").val();
			var qte_embal = qte / coulissage;
			$( "input[name*='"+module_name+"_product_qte_emballe_0["+index+"]']").val( qte_embal.toFixed(1) );		
		});	
	
		// ====================================================	
		for (v = 0; v < 50; v++) { 
			// === readonly
			// alert("ok");
			// $( "select[name*='"+module_name+"_product_name_0["+v+"]']").attr("readonly","readonly");
			$( "input[name*='"+module_name+"_product_prix_0["+v+"]']").attr("readonly","readonly");
			$( "input[name*='"+module_name+"_product_coulissage_0["+v+"]']").attr("readonly","readonly");
			$( "select[name*='"+module_name+"_product_unite_0["+v+"]']").attr("readonly","readonly");
			
			$( "input[name*='"+module_name+"_product_qte_emballe_0["+v+"]']").attr("readonly","readonly");
		}	
	}	
	// ======== View produis Bon de commande ==============
	$(document).on( "change","#ref_bc",function() {
		
		$("#get_bc").remove();
		$("#dialog").remove();
		$("#get_be").remove();
		$("#dialog_be").remove();
		$("#add_product").remove();
		$("#table_be_product .form-control").val('');
		
		var id_prd = $(this).val();
		

		if(id_prd != ""){	
			// alert($(this).val());
			$(this).after('<button id="get_be" type="button" class="btn btn-primary" style="margin-left:20px;"><i class="fa fa-eye"></i><span class="hidden-sm hidden-xs"> Voir état CMD</span></button><button id="add_product" type="button" class="btn btn-success" style="margin-left:20px;"><i class="fa fa-plus"></i><span class="hidden-sm hidden-xs"> Ajouter les produits</span></button>');
			
			
			// ===== GET detail bon de commande ==========
			// $.ajax({
				// url: "/admin/ajax/get_product_bc.php",
				// type: "GET",
				// data: {
					// id: id_prd,
				// },
				// dataType: "html",
				// success: function (jsonStr) { 
					// $("#ref_bc").after('<div id="dialog" style="display:none;" title="Bon de commande N° BL_00'+id_prd+'"><p>'+jsonStr+'</p></div>'); 
					// $(document).on( "click","#get_bc",function() {
						// $( "#dialog" ).dialog({
								// width: 'auto'
						// });
					// });	
					
				// }
			// });
			// ========= GET product bon d'entré partielle =========
			$.ajax({
				url: "/admin/ajax/get_product_be.php",
				type: "GET",
				data: {
					id: id_prd,
				},
				dataType: "html",
				success: function (jsonStr) {
					if(jsonStr != ''){	
						$("#ref_bc").after('<div id="dialog_be" style="display:none;" title="Produits relatif à la commande N° BL_00'+id_prd+'"><p>'+jsonStr+'</p></div>'); 
						$(document).on( "click","#get_be",function() {
							$( "#dialog_be" ).dialog({
									width: 'auto'
							});
						});	
					}else{
						$("#get_be").remove();
					}
				}
			});			
			// =====================================================

		$(document).on( "click","#add_product",function() {	
			$("#add_product").hide();
			$.ajax({
				url: "/admin/ajax/get_product_bc_json.php",
				type: "GET",
				data: {
					id: id_prd,
					reste : 1
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var texte = JSON.stringify(jsonStr) ;
					//console.log(texte);
					var obj = JSON.parse(texte);
					// ==== ADD Produits =====
					var count = Object.keys(obj).length;
					// alert(count);
					// ======= ajouté les lignes ======
					var i = 1;
					if(count > 1){
						while (i < count) {
							$(".new_entry").click();
							i++;
						}						
					}
					// alert(obj[0].qte);
					for (j = 0; j < count; j++) { 						
						$( "select[name*='"+module_name+"_product_name_0["+j+"]']").val(obj[j].name);
						$( "input[name*='"+module_name+"_product_qte_0["+j+"]']").val(obj[j].qte);
						$( "input[name*='"+module_name+"_product_prix_0["+j+"]']").val(obj[j].prix);
						$( "input[name*='"+module_name+"_product_coulissage_0["+j+"]']").val(obj[j].coulissage);
						$( "select[name*='"+module_name+"_product_unite_0["+j+"]']").val(obj[j].unite);
						
						// === readonly
						$( "select[name*='"+module_name+"_product_name_0["+j+"]']").attr("readonly","readonly");
						$( "input[name*='"+module_name+"_product_prix_0["+j+"]']").attr("readonly","readonly");
						$( "input[name*='"+module_name+"_product_coulissage_0["+j+"]']").attr("readonly","readonly");
						$( "select[name*='"+module_name+"_product_unite_0["+j+"]']").attr("readonly","readonly");
					}
								
					
					
				}
			});			

		});						
			
			
		}	
	});
	
	// ==============================================
	// ============ Module facture_avoir_vente ======
	// ==============================================	
	if(module_name == "facture_avoir_vente"){
		$.ajax({
				   url: "/admin/ajax/get_brv.php",
					type: "GET",
					// data: {
						// id: fournisseur,
					// },
					dataType: "JSON",
					success: function (jsonStr) { 
						var text = JSON.stringify(jsonStr) ;
						//console.log(text);
						var obj = JSON.parse(text);
						var count = Object.keys(obj).length;
						for (j = 0; j < count; j++) { 
							// //console.log("select[name*='facture_avoir_ref_bl_0[0]'] [value='"+obj[j]+"']");
							$("select[name*='facture_avoir_vente_ref_br_0[0]_tmp[]'] [value='"+obj[j]+"']").hide();
						}
					}	
				});	
	}
	// ==============================================
	// ============ Module facture_avoir achat ======
	// ==============================================	
	if(module_name == "facture_avoir"){
		// ======= on relod page ============ lasser les BL pour ce fourniseur
						
			$('#ref_bl option').show();
			var fournisseur = $("#fournisseur").val();			
				$.ajax({
				   url: "/admin/ajax/get_facture_fourniseur.php",
					type: "GET",
					data: {
						id: fournisseur,
					},
					dataType: "JSON",
					success: function (jsonStr) { 
						var text = JSON.stringify(jsonStr) ;
						//console.log(text);
						var obj = JSON.parse(text);
						var count = Object.keys(obj).length;
						for (j = 0; j < count; j++) { 
							// //console.log("select[name*='facture_avoir_ref_bl_0[0]'] [value='"+obj[j]+"']");
							$("select[name*='facture_avoir_ref_bl_0[0]'] [value='"+obj[j]+"']").hide();
						}
					}	
				});
			
			$(document).on( "change","#fournisseur",function() {
			$('#ref_bl option').show();
			var fournisseur = $(this).val();			
				$.ajax({
				   url: "/admin/ajax/get_facture_fourniseur.php",
					type: "GET",
					data: {
						id: fournisseur,
					},
					dataType: "JSON",
					success: function (jsonStr) { 
						var text = JSON.stringify(jsonStr) ;
						//console.log(text);
						var obj = JSON.parse(text);
						var count = Object.keys(obj).length;
						for (j = 0; j < count; j++) { 
							// //console.log("select[name*='facture_avoir_ref_bl_0[0]'] [value='"+obj[j]+"']");
							$("select[name*='facture_avoir_ref_bl_0[0]'] [value='"+obj[j]+"']").hide();
						}
					}	
				});		
			});	
			// ============ Calcule TTC =========
			$(document).on( "change","input, select, radio",function() {
				
				var TTC = 0;
				var HT = parseFloat($("input[name*='facture_avoir_montant_ht_0[0]']").val());
				var timbre = parseFloat($("#timbre").val());
				//console.log(timbre);
				var tva = $("#tva").val();
				if(tva == ""){ tva = 0 ;}
				if(HT != ""){
					TTC = ((HT * tva)/100) + HT;
					if(timbre == 1){
						TTC = TTC + 0.6 ;
					}
				}
				$("input[name*='facture_avoir_total_ttc_0[0]']").val(TTC.toFixed(3));
			});					
	
	}

	
	// ==============================================
	// ============ Module facture_achat ============
	// ==============================================
	if(module_name == "facture_achat"){
		// ======= on relod page ============ lasser les BL pour ce fourniseur
			var id_frn_0 = $("#fournisseur").val();
			
			$('#facture_achat_ref_be_0_0_tmp option').show();
			
			$.ajax({
			   url: "/admin/ajax/get_bl_fourniseur.php",
				type: "GET",
				data: {
					id: id_frn_0,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					var count = Object.keys(obj).length;
					for (j = 0; j < count; j++) { 
						$('#facture_achat_ref_be_0_0_tmp [value="'+obj[j].id+'"]').hide();
					}
				}	
			});		
					
					
		// ==============================================
		// ========== on change fourniseur =======
		$(document).on( "change","#fournisseur",function() {
			var id_frn = $(this).val();
			
			$('#facture_achat_ref_be_0_0_tmp option').show();
			
			$.ajax({
			   url: "/admin/ajax/get_bl_fourniseur.php",
				type: "GET",
				data: {
					id: id_frn,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					var count = Object.keys(obj).length;
					for (j = 0; j < count; j++) { 
						$('#facture_achat_ref_be_0_0_tmp [value="'+obj[j].id+'"]').hide();
					}
				}
			});		
		});
	}	

	// ==============================================
	// ============ Module Be / Bc / Br ============
	// ==============================================
	if((module_name == "be") || (module_name == "br") || (module_name == "bc")){
		// ======= on relod page ============ laisser les produit pour ce fourniseur
			var id_frnn = $("#fournisseur").val();
			
			for (v = 0; v < 50; v++) { 
				$("select[name*='"+module_name+"_product_name_0["+v+"]'] option").show();
			}
			
			
			$.ajax({
			   url: "/admin/ajax/get_product_fourniseur.php",
				type: "GET",
				data: {
					id: id_frnn,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					var count = Object.keys(obj).length;
					for (j = 0; j < count; j++) { 
						for (v = 0; v < 50; v++) { 
							$("select[name*='"+module_name+"_product_name_0["+v+"]'] [value='"+obj[j].id+"']").hide();
						}	
					}
				}
			});	
			//==========================================
			$.ajax({
			   url: "/admin/ajax/get_bc_fourniseur.php",
				type: "GET",
				data: {
					id: id_frnn,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj_bc = JSON.parse(text);
					var coun_bc = Object.keys(obj_bc).length;
					$("select[name*='"+module_name+"_ref_bc_0[0]'] option").hide();	
					for (j = 0; j < coun_bc; j++) { 						 
						$("select[name*='"+module_name+"_ref_bc_0[0]'] [value='"+obj_bc[j].id+"']").show();	
						//console.log("select[name*='"+module_name+"_ref_bc_0[0]");
					}
				}
			});		
			//==========================================
	// ========== on change fourniseur =======
		// ------------ BL ---------------
		$(document).on( "change","#fournisseur",function() {
			// alert(module_name);
			var id_frnn = $(this).val();
			
			$("#ref_bc option").show();
			
			$.ajax({
			   url: "/admin/ajax/get_bc_fourniseur.php",
				type: "GET",
				data: {
					id: id_frnn,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj_bc = JSON.parse(text);
					var coun_bc = Object.keys(obj_bc).length;
					$("select[name*='"+module_name+"_ref_bc_0[0]'] option").hide();	
					for (j = 0; j < coun_bc; j++) { 						 
						$("select[name*='"+module_name+"_ref_bc_0[0]'] [value='"+obj_bc[j].id+"']").show();	
						//console.log("select[name*='"+module_name+"_ref_bc_0[0]");
					}
				}
			});		
		});
		// ------------ PRODUITS ---------
		$(document).on( "change","#fournisseur",function() {
			var id_frnn = $(this).val();
			
			for (v = 0; v < 50; v++) { 
				$("select[name*='"+module_name+"_product_name_0["+v+"]'] option").show();
			}
			
			$.ajax({
			   url: "/admin/ajax/get_product_fourniseur.php",
				type: "GET",
				data: {
					id: id_frnn,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					var count = Object.keys(obj).length;
					for (j = 0; j < count; j++) { 
						for (v = 0; v < 50; v++) { 
							$("select[name*='"+module_name+"_product_name_0["+v+"]'] [value='"+obj[j].id+"']").hide();
						}	
					}
				}
			});		
		});
		// ============== Test si la valeur est en stock ==========
		$(document).on( "change","#table_br_product input",function() {
			var val_input = $(this).val();
			var name = $(this).attr("name");
			var str = name.split("[");
			var res = str[1].replace("]", "");
			var id_elm = res;
			
			var val_prod = $("select[name*='br_product_name_0["+id_elm+"]']").val();
			//console.log(val_prod);			
			$.ajax({
			   url: "/admin/ajax/get_qte_stock.php",
				type: "GET",
				data: {
					id: val_prod,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					
					if(obj.qte_en_stock < val_input){
						if(obj.qte_en_stock < 0){ obj.qte_en_stock = 0 ;}
						alert("il ya seulment "+obj.qte_en_stock+" en stock !");
						$("input[name*='"+name+"']").val(obj.qte_en_stock);
						$("input[name*='"+name+"']").addClass("error_qte");
						return false;
					}	
				}
			});	
		});			
	}
	// ==============================================
	// ============ Module Bon de fabrication =======
	// ==============================================
	if(module_name == "bf"){
		var id_frnn = $("#product").val();

		
		// ------------ PRODUITS on load ---------

		
			$(".new_entry").hide();
			
			for (v = 0; v < 50; v++) { 
				$("select[name*='bf_product_id_produits_0["+v+"]'] option").hide();
			}
			
			$.ajax({
			   url: "/admin/ajax/get_product_mp.php",
				type: "GET",
				data: {
					id: id_frnn,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					var count = Object.keys(obj).length;
					for (j = 0; j < count; j++) { 
						for (v = 0; v < 50; v++) { 
							$("select[name*='bf_product_id_produits_0["+v+"]'] [value='"+obj[j].id+"']").hide();
						}	
					}
				}
			});	
		// ------------ QTE embalé on change ---------
		$(document).on( "keyup","input[name*='bf_qte_embal_0[0]']",function() {
			var qte_empable = $(this).val();
			var colisss = $("input[name*='bf_Colisage_0[0]']").val();
			var qteee = qte_empable * colisss ;
			// alert(qteee);
			$("input[name*='bf_qte_0[0]']").val(qteee);
			
		});	
		$(document).on( "keyup","input[name*='bf_qte_0[0]']",function() {
			var qte_empable = $(this).val();
			var colisss = $("input[name*='bf_Colisage_0[0]']").val();
			var qteee = qte_empable / colisss ;
			// alert(qteee);
			$("input[name*='bf_qte_embal_0[0]']").val(qteee.toFixed(3));
			
		});	
		
		
		//=========== change BE  =======
$(document).on("change", "input[name^='bf_product_qte_0']", function() {
    // Récupérer la valeur du champ modifié
    var valeur = $(this).val();

    // Exemple : afficher la valeur dans la console
    console.log("Valeur changée :", valeur);

    // Si tu veux récupérer aussi l’index (le numéro entre [ ])
    var name = $(this).attr("name");
    var match = name.match(/\[(\d+)\]/); // extrait le chiffre entre [ ]
    if (match) {
        var index = match[1];
        console.log("Index :", index);
    }
			
			var id_prd = index;
			// id_prd = id_prd.replace('bf_product_id_be_0[', "");
			// id_prd = id_prd.replace(']', "");
			
			var id_product = $("select[name*='bf_product_id_produits_0["+id_prd+"]']").val();
			
			var id_be = $(this).val();
			// alert(id_product);
			$.ajax({
			   url: "/admin/ajax/get_qte_be.php",
				type: "GET",
				data: {
					id: id_product,
					id_be: id_be,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					var count = Object.keys(obj).length;
					for (j = 0; j < count; j++) { 
						$(".qteGet_"+id_prd).text("");
						$("input[name*='bf_product_qte_0["+id_prd+"]'] ").parent().append("<span style='color:green;font-size: 13px;' class='qteGet_"+id_prd+"'> Max:"+obj[j].qte+"</span>");
						// alert(obj.qte);
					}	

				}
			});	
			
		});	
		//=======================================
		$(document).on( "change","#table_bf_product input",function() {
			var val_input = $(this).val();
			var name = $(this).attr("name");
			var str = name.split("[");
			var res = str[1].replace("]", "");
			var id_elm = res;
			
			var val_prod = $("select[name*='bf_product_id_produits_0["+id_elm+"]']").val();
			var val_be = $("select[name*='bf_product_id_be_0["+id_elm+"]']").val();
			//console.log(val_prod);			
			$.ajax({
			   url: "/admin/ajax/get_qte_be.php",
				type: "GET",
				data: {
					id: val_prod,
					id_be: val_be,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					// alert("il ya seulment "+obj[0].qte+"<"+val_input+" en stock !");
					if(parseInt(obj[0].qte) < parseInt(val_input)){
						if(parseInt(obj[0].qte) < 0){ parseInt(obj[0].qte) = 0 ;}
						alert("il ya seulment "+obj[0].qte+" en stock !");
						$("input[name*='"+name+"']").val(obj[0].qte);
						$("input[name*='"+name+"']").addClass("error_qte");
						return false;
					}else{
						$("input[name*='"+name+"']").addClass("succes_gte");
					}	
				}
			});	
		});			
		//=======================================
		
			// ------------ PRODUITS on change ---------
		$(document).on( "change","#product",function() {
			var id_frnn = $(this).val();
			
			var id_element = "";
			
			for (v = 0; v < 50; v++) { 
				$("select[name*='bf_product_id_produits_0["+v+"]'] option").hide();
				$("select[name*='bf_product_id_be_0["+v+"]'] option").hide(); // BE
				var this_id = $("input[name*='bf_product_id_0["+v+"]'] ").val();
				if (this_id != null){
					id_element += " id = "+this_id+" OR ";
				}
			}
			
			var query_delete = " DELETE FROM `pm_bf_product` WHERE "+id_element+" id = 0;"
			// alert(query_delete);
			//================ DELETE OLD product ===
			$.ajax({
			   url: "/admin/ajax/mysql_exc.php",
				type: "POST",
				data: {
					query: query_delete,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
				}
			});	
			
			
			$.ajax({
			   url: "/admin/ajax/get_product_mp.php",
				type: "GET",
				data: {
					id: id_frnn,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					var count = Object.keys(obj).length;
					for (j = 0; j < count; j++) { 
						for (v = 0; v < 50; v++) { 
							$("select[name*='bf_product_id_produits_0["+v+"]'] [value='"+obj[j].id+"']").hide();
						}	
					}
				}
			});
			
			$("#table_bf_product tbody tr:gt(0)").remove();
			// ============== AJOUT produit automatique ===========
			$.ajax({
			   url: "/admin/ajax/get_product_mp_list.php",
				type: "GET",
				data: {
					id: id_frnn,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					var count_mf = Object.keys(obj).length;
						var i = 1;
						if(count_mf > 1){
							// $("#table_bf_product tr").remove();
							while (i < count_mf) {
								$(".new_entry").click();
								i++;
							}						
						}
					
						for (j = 0; j < count_mf; j++) { 	
							// //console.log('==>'+obj[j].id);
							var ids_be = obj[j].ids_be.split(",");
							var i;
							for (i = 0; i < ids_be.length; ++i) {
								// //console.log("be==>"+ids_be[i]);
								$("select[name*='bf_product_id_be_0["+j+"]'] [value='"+ids_be[i]+"']").show();								
							}
							
							$( "select[name*='"+module_name+"_product_id_produits_0["+j+"]']").val(obj[j].id);
							$( "input[name*='"+module_name+"_product_qte_0["+j+"]']").val(obj[j].qte);
							$( "input[name*='"+module_name+"_product_prix_0["+j+"]']").val(obj[j].prix);
							$( "input[name*='"+module_name+"_product_coulissage_0["+j+"]']").val(obj[j].coulissage);
							$( "select[name*='"+module_name+"_product_unite_0["+j+"]']").val(obj[j].unite);
							
							$( "input[name*='"+module_name+"_product_coulissage_0["+j+"]']").attr("readonly","readonly");
							$( "select[name*='"+module_name+"_product_unite_0["+j+"]']").attr("readonly","readonly");
						}
				}
			});	
		//=============== GET collisage =========
			$.ajax({
			   url: "/admin/ajax/get_product_vente.php",
				type: "GET",
				data: {
					id: id_frnn,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj_bc = JSON.parse(text);
			
					//====== get infos === 				
					$("input[name*='bf_Colisage_0[0]']").val(obj_bc.coulissage);	

					
				}
			});
			// ====================================================			
				
		});
		//===================================================
		// ============== Test si la valeur est en stock ==========
		// $(document).on( "change","#table_bf_product input",function() {
			// var val_input = $(this).val();
			// var name = $(this).attr("name");
			// var str = name.split("[");
			// var res = str[1].replace("]", "");
			// var id_elm = res;
			// var val_prod = $("select[name*='bf_product_id_produits_0["+id_elm+"]']").val();
			// //console.log(val_prod);			
			// $.ajax({
			   // url: "/admin/ajax/get_qte_stock.php",
				// type: "GET",
				// data: {
					// id: val_prod,
				// },
				// dataType: "JSON",
				// success: function (jsonStr) { 
					// var text = JSON.stringify(jsonStr) ;
					// //console.log(text);
					// var obj = JSON.parse(text);
					
					// if(obj.qte_en_stock < val_input){
						// if(obj.qte_en_stock < 0){ obj.qte_en_stock = 0 ;}
						// alert("il ya seulment "+obj.qte_en_stock+" en stock !");
						// $("input[name*='"+name+"']").val(obj.qte_en_stock);
						// $("input[name*='"+name+"']").addClass("error_qte");
						// return false;
					// }	
				// }
			// });	
		// });			
	}
	// ==============================================
	// ==============================================
	
	// ==============================================
	// ============ Module Bon de fabrication =======
	// ==============================================
	if((module_name == "bl") || (module_name == "brv")){
	// ========== on change fourniseur =======
		
		// === readonly
		for (v = 0; v < 50; v++) { 
			$( "input[name*='"+module_name+"_product_name_0["+v+"]']").attr("readonly","readonly");
			$( "input[name*='"+module_name+"_product_coulissage_0["+v+"]']").attr("readonly","readonly");
			$( "select[name*='"+module_name+"_product_unite_0["+v+"]']").attr("readonly","readonly");
			$( "input[name*='"+module_name+"_product_remise1_0["+v+"]']").attr("readonly","readonly");
			// $( "input[name*='"+module_name+"_product_qte_emballe_0["+v+"]']").attr("readonly","readonly");
		}	
		// ------------ BL ---------------
		
		$(document).on( "change keyup","#table_"+module_name+"_product select",function() {
			// alert(module_name);
			var ref_prod = $(this).val();
			var name_select = $(this).attr("name");
			var res = name_select.split("[");
			var index = res[1].replace("]","");
// alert(index);	
			
			$.ajax({
			   url: "/admin/ajax/get_product_vente.php",
				type: "GET",
				data: {
					id: ref_prod,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj_bc = JSON.parse(text);
					
					//====== readonly ====
					$( "input[name*='"+module_name+"_product_name_0["+index+"]']").attr("readonly","readonly");
					$( "input[name*='"+module_name+"_product_coulissage_0["+index+"]']").attr("readonly","readonly");
					$( "select[name*='"+module_name+"_product_unite_0["+index+"]']").attr("readonly","readonly");
					$( "input[name*='"+module_name+"_product_remise1_0["+index+"]']").attr("readonly","readonly");
					// $( "input[name*='"+module_name+"_product_qte_emballe_0["+index+"]']").attr("readonly","readonly");
					//====== get infos === 
					$("input[name*='"+module_name+"_product_name_0["+index+"]']").val(obj_bc.desingnation);					
					$("input[name*='"+module_name+"_product_coulissage_0["+index+"]']").val(obj_bc.coulissage);	
					$("select[name*='"+module_name+"_product_unite_0["+index+"]']").val(obj_bc.unite);
					$("input[name*='"+module_name+"_product_remise1_0["+index+"]']").val(obj_bc.remise);
					
				}
			});		
		});
		
		$(document).on( "keyup","#table_"+module_name+"_product input",function() {
			var name_select = $(this).attr("name");
			var res = name_select.split("[");
			var index = res[1].replace("]","");
			var qte = $( "input[name*='"+module_name+"_product_qte_0["+index+"]']").val();
			var coulissage = $( "input[name*='"+module_name+"_product_coulissage_0["+index+"]']").val();
			
			var str = $(this).attr("name");
			var words = str.split('_');
			// alert(words[3]);
			if(words[3] == 'emballe'){
				var qte = $( "input[name*='"+module_name+"_product_qte_emballe_0["+index+"]']").val();
				var qte_embal = qte * coulissage;
				$( "input[name*='"+module_name+"_product_qte_0["+index+"]']").val( qte_embal.toFixed(3) );
			}else{
				var qte_embal = qte / coulissage;
				$( "input[name*='"+module_name+"_product_qte_emballe_0["+index+"]']").val( qte_embal.toFixed(3) );
			}
			
			// var qte_embal = qte * coulissage;
					
		});	
		//===================================================
		// ============== Test si la valeur est en stock ==========
		$(document).on( "change","#table_bl_product input",function() {
			var val_input = $(this).val();
			var name = $(this).attr("name");
			var str = name.split("[");
			var res = str[1].replace("]", "");
			var id_elm = res;
			
			var val_prod = $("select[name*='bl_product_id_produits_0["+id_elm+"]']").val();
			var val_customer = $("select[name*='bl_id_client_0[0]']").val();
			//console.log(val_prod);
		
			$.ajax({
			   url: "/admin/ajax/get_qte_stock_vente.php",
				type: "GET",
				data: {
					id: val_prod,
					id_client: val_customer,
				},
				dataType: "JSON",
				success: function (jsonStr) { 
					var text = JSON.stringify(jsonStr) ;
					//console.log(text);
					var obj = JSON.parse(text);
					
					if(obj.qte_en_stock < val_input){
						if(obj.qte_en_stock < 0){ obj.qte_en_stock = 0 ;}
						alert("il ya seulment "+obj.qte_en_stock+" en stock !\nQauntité : "+ (obj.qte_en_stock - val_input) );
						//$("input[name*='"+name+"']").val(obj.qte_en_stock);
						$("input[name*='"+name+"']").addClass("error_qte");
						return false;
					}	
				}
			});	
		});			
	}
	
	// ==============================================
	// ============ Module facture_achat ============
	// ==============================================
	if(module_name == "facture"){
		
		$('#facture_ref_bl_0_0_tmp option').show();
					
					$.ajax({
					   url: "/admin/ajax/get_bl.php",
						type: "GET",
						data: {
							id: id_frn_0,
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var count = Object.keys(obj).length;
							for (j = 0; j < count; j++) { 
							// //console.log(obj[j]);
								$('#facture_ref_bl_0_0_tmp option[value="'+obj[j]+'"]').hide();
							}
						}	
					});		
					
					
		$(document).on( "change","#id_client",function() {
			var idClient = $("#id_client").val();
			
				if(idClient != ""){
					// facture_todo(idClient);


				$('#facture_ref_bl_0_0_tmp option').show();
				$.ajax({
					   url: "/admin/ajax/get_bl_client.php",
						type: "GET",
						data: {
							id_client: idClient,
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var count = Object.keys(obj).length;
							for (j = 0; j < count; j++) { 
							console.log(obj[j]);
								// alert('#ref_facture_achat option[value="'+obj[j]+'"]');
								$('#facture_ref_bl_0_0_tmp option[value="'+obj[j]+'"]').hide();
							}
							
						}	
					});	
					
					
					
					
				}
		});	


				
						
	}


	// ==============================================
	// ============ Module Transaction ============
	// ==============================================
	if(module_name == "transaction"){
		
		$(document).on( "click",".datepicker",function() {
			$("#ui-datepicker-div").hide();
		});
		
		
		
		
		// $("button[name*='add']").hide();
		// $("button[name*='add_back']").hide();
		
		
		
		$(".hide_transaction").hide();
		
		
		var fournisseurs = $("#fournisseur").val();
		var clients = $("#client").val();
		if(fournisseurs != ""){
			Get_facture(fournisseurs);
			Get_facture_v2(fournisseurs);
			Get_retenue(fournisseurs);
		}
		if(clients != ""){
			Get_facture_vente_v2(clients);
		}
		
		
		
		$("input[name*='transaction_retenue_montant_0[0]'").parent().append('<button id="calculer_retenu" type="button" class="btn btn-success" style="margin-left:20px;"><i class="fa fa-registered"></i><span class="hidden-sm hidden-xs"> Calculer retenue</span></button>');
		$("input[name*='transaction_montant_0[0]'").parent().append('<button id="calculer_montant" type="button" class="btn btn-success" style="margin-left:20px;"><i class="fa fa-calculator"></i><span class="hidden-sm hidden-xs"> Calculer Montant</span></button>');
		
		$("input[name*='transaction_montant_0[0]'").parent().parent().parent().children().css('background-color',"rgb(211, 255, 203)");
		$("input[name*='transaction_montant_0[0]'").parent().parent().parent().children().css('padding',"13px");
		$("input[name*='transaction_montant_0[0]'").parent().parent().parent().children().css('height',"66px");
		
		
		var fournisseur = $("#fournisseur").val();
		var client = $("#client").val();
		// alert(fournisseur);
		if(fournisseur == "" && client == ""){
			
		}else if(fournisseur != ""){
			for (v = 0; v < 10; v++) { 
				$( "select[name*='"+module_name+"_product_ref_facture_vente2_0["+v+"]'] ").hide();
			}		
		}else{
			for (v = 0; v < 10; v++) { 
				$( "select[name*='"+module_name+"_product_ref_facture_achat2_0["+v+"]'] ").hide();
			}		
		}
		
		
		
		
		
		$(document).on( "click","#calculer_retenu",function() {
			calculer_retenue();
		});
		
		
		$(document).on( "click","#calculer_montant",function() {
			
			var test_vide = $("input[name*='"+module_name+"_product_montant_0[0]']").val();
			
			if(test_vide > 0){
				calculer_montant();
			}
			
			// $("button[name*='add']").show();
			// $("button[name*='add_back']").show();
			$(".hide_transaction").show();
			
		});
		
		
		
		for (v = 0; v < 10; v++) { 
			$("input[name*='"+module_name+"_product_date_ech_0["+v+"][date]']").attr("readonly","readonly");
			$("input[name*='"+module_name+"_product_montant_facture_0["+v+"]']").attr("readonly","readonly");
			$("input[name*='"+module_name+"_product_reste_0["+v+"]']").attr("readonly","readonly");		
			$("#ui-datepicker-div").hide();		
		}
		
		var type_ready = $("#type").val();
		// alert(type_ready);
		changeTypeTransaction(type_ready);
		$(document).on( "change","#type",function() {
			var type = $(this).val();
			changeTypeTransaction(type);
		});	
		//===== change fournisseur
		$(document).on( "change","#fournisseur",function() {
			var fournisseur = $(this).val();
			if(fournisseur == ""){
				$("#ref_facture_achat").val("");
				$("#ref_facture_achat").parent().parent().parent().hide();
				$("#ref_facture_vente").parent().parent().parent().show();
			}else{
				Get_facture(fournisseur);
				Get_facture_v2(fournisseur);
				Get_retenue(fournisseur);
				$("#ref_facture_achat").parent().parent().parent().show();
				$("#ref_facture_vente").val("");
				$("#client").val("");
				$("#ref_facture_vente").parent().parent().parent().hide();
	
			}	
		});
		//===== change Client
		$(document).on( "change","#client",function() {
			var client = $(this).val();
			if(client == ""){
				$("#ref_facture_achat").parent().parent().parent().show();
				$("#ref_facture_vente").val("");
				$("#ref_facture_vente").parent().parent().parent().hide();
			}else{
				Get_facture_vente_v2(client);
				$("#ref_facture_achat").val("");
				$("#fournisseur").val("");
				$("#ref_facture_achat").parent().parent().parent().hide();
				$("#ref_facture_vente").parent().parent().parent().show();				
			}	
		});	
		//===== change facture_achat V2 ===================================
		$(document).on( "change","#table_transaction_product select",function() {
			var facture_achat = $(this).val();
			var name_select = $(this).attr("name");
			var res = name_select.split("[");
			var index = res[1].replace("]","");
			
			// alert(index);
			if(res[0] == "transaction_product_ref_facture_vente2_0"){// facture vente
				// Get_TTC(facture_achat,"facture_achat");
				Get_details_facture_vente(facture_achat,index);
			}else{// facture achat
				// Get_TTC(facture_achat,"facture_achat");			
				Get_details_facture(facture_achat,index);	
				
			} 
			
		//===================
		$("button[name*='add']").hide();
		$("button[name*='add_back']").hide();
		//===================
					
		});	//===== change facture_achat
		$(document).on( "change","#ref_facture_achat, #retenue",function() {
			var facture_achat = $("#ref_facture_achat").val();
			if(facture_achat == ""){
				// Get_TTC(facture_achat,"facture_achat");
			}else{
				Get_TTC(facture_achat,"facture_achat");			
			}	
		});	
		//===== change facture_vente
		$(document).on( "change","#ref_facture_vente",function() {
			var facture_vente = $("#ref_facture_vente").val();
			if(facture_vente == ""){
				$("input[name*='transaction_retenue_montant_0[0]']").parent().parent().parent().show();
				$("#retenue").parent().parent().parent().show();
			}else{
				Get_TTC(facture_vente,"facture");				
				$("#retenue").parent().parent().parent().hide();
				$("#retenue").val("");
				
				$("input[name*='transaction_retenue_montant_0[0]']").parent().parent().parent().hide();
					
			}	
			
				//===================
		$("button[name*='add']").hide();
		$("button[name*='add_back']").hide();
			//===================	
		});	


	$(document).on( "change","#table_transaction_product input",function() {
		$("button[name*='add']").hide();
		$("button[name*='add_back']").hide();
	});		
		
	}






//================= Disable champ apres edit

	var is_edit = "<?php echo $_GET["id"]; ?>" ;
	if((module_name == "be") || (module_name == "bc") || (module_name == "facture_avoir")){
		// //console.log(">>>>>"+is_edit);
		if(is_edit > 0){
			//====facture_avoir
			// $( "#ref_bl").attr("readonly","readonly");
			//======= bbc
			for (v = 0; v < 50; v++) { 
				// $( "select[name*='"+module_name+"_product_name_0["+v+"]']").attr("readonly","readonly");
			}	
			//========== be	
			// $( "#ref_bc").attr("readonly","readonly");
			
		}


	
	};	











	
});



function calculer_retenue() {
	
	
	var count_elements = $('.count_product').length;
	
	
			var timbre = 0;
			var retn = 0;
			var total_montant = 0;
			var total_montant_avoir = 0;
			var retenue = $("#retenue").val();
			
			for (v = 0; v < count_elements; v++) { 
				var val_mnt = $("input[name*='transaction_product_montant_facture_0["+v+"]']").val();
				
				
				if (!isNaN(val_mnt)) {
					total_montant += parseFloat(val_mnt);
					// total_montant2 += parseFloat(val_mnt);					
					timbre++;
				
				}	
				
			//===== Voir les factures d'avoir accosier
			var id_facture = $("select[name*='transaction_product_ref_facture_achat2_0["+v+"]']").val();			
					$.ajax({
					   url: "/admin/ajax/get_facture_acc_avoir.php",
						type: "GET",
						data: {
							id: id_facture,
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var montant_avoir = 0;
							if((obj.total_ttc) !== null){
	
								$("#accosiated").remove();
								$("#calculer_retenu").parent().append("<span style='color:rgb(233, 12, 89);padding-left: 10px;' id='accosiated'><img src='/admin/images/alert.gif' width='32' /> Facture avoir associé </span>");
							}
							
					//console.log(total_montant);
					console.log(" Timbre ==>  "+ timbre)	
					retn = ( (total_montant-timbre) * retenue)/100 ;
					console.log(" retn ==>  "+ retn)
					$("input[name*='transaction_retenue_montant_0[0]").val(toFixed2(retn, 3));						
						
						}	
					});	
				
					

			}
			

		
					
							
			
			
			
			// $("input[name*='transaction_montant_0[0]'").val(total_montant.toFixed(3));
}


function calculer_montant() {
			var timbre = 0;
			var total_montant = 0;
			var total_montant2 = 0;
			for (v = 0; v < 10; v++) { 
				var val_mnt = $("input[name*='transaction_product_montant_0["+v+"]']").val();
				var val_mnt2 = $("input[name*='transaction_product_montant_facture_0["+v+"]']").val();
				
				if (!isNaN(val_mnt)) {
					timbre++;
					total_montant += parseFloat(val_mnt);				
					total_montant2 += parseFloat(val_mnt2);				
				}	
			}
			
			total_montant2 = total_montant2 - timbre ; //=== supprimer timbre fiscal 
			
			var retenue = $("#retenue").val();
			var retenue_mawjoud  = $("input[name*='transaction_retenue_montant_0[0]").val();
			
			
			
				if(retenue == "" && retenue_mawjoud == ""){
					var montant = total_montant;
					$("input[name*='transaction_retenue_montant_0[0]").val('');
				}else if(retenue_mawjoud != ""){	
					total_montant = total_montant - retenue_mawjoud;
				}else{
					var retn = (total_montant2 * retenue)/100 ;
					var montant = total_montant - retn;
					$("input[name*='transaction_retenue_montant_0[0]").val(toFixed2(retn, 3));
					total_montant = total_montant - retn;
				}		

		
			
			console.log("total_montant ==> "+total_montant2);
			console.log("retenue ==> "+toFixed2(retn, 3));
			console.log("timbre ==> "+timbre);



			
			$("input[name*='transaction_montant_0[0]'").val(total_montant.toFixed(3));
			
		
}



function toFixed2(num, fixed) {
    var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
    return num ;
}



function addDays(theDate, days) {
    return new Date(theDate.getTime() + days*24*60*60*1000);
}

function changeTypeTransaction(type)
{
	if(type == "in"){
		$("#retenue").parent().parent().parent().hide();
		$("#retenue").parent().parent().parent().next().hide();
		$("input[name*='transaction_date_echeance_0[0][date]']").parent().parent().parent().parent().show();				
	}else{
		$("#retenue").parent().parent().parent().show();
		$("#retenue").parent().parent().parent().next().show();	
		$("input[name*='transaction_date_echeance_0[0][date]']").parent().parent().parent().parent().show();				
	}
}

function Get_facture(id_fournisseur)
{
	$('#ref_facture_achat option').show();

		var module_name = "<?php echo MODULE; ?>" ;
	
				$.ajax({
					   url: "/admin/ajax/get_facture_fourniseur.php",
						type: "GET",
						data: {
							id: id_fournisseur,
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var count = Object.keys(obj).length;
							for (j = 0; j < count; j++) { 
							//console.log(obj[j]);
								$('#ref_facture_achat option[value="'+obj[j]+'"]').hide();
							}
							
						}	
					});	
}

function Get_facture_v2(id_fournisseur)
{
var module_name = "<?php echo MODULE; ?>" ;

	for (v = 0; v < 10; v++) { 
		$( "select[name*='"+module_name+"_product_ref_facture_achat2_0["+v+"]'] option").hide();
	}
			
				$.ajax({
					   url: "/admin/ajax/get_facture_fourniseur_v2.php",
						type: "GET",
						data: {
							id: id_fournisseur,
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var count = Object.keys(obj).length;
							for (j = 0; j < count; j++) { 
							//console.log(obj[j]);
								for (v = 0; v < 10; v++) { 
									$( "select[name*='"+module_name+"_product_ref_facture_achat2_0["+v+"]'] option[value='"+obj[j]+"']").show();
									$( "select[name*='"+module_name+"_product_ref_facture_vente2_0["+v+"]']").hide();
								}	
							}
							
						}	
					});	
}

function Get_retenue(id_fournisseur)
{
var module_name = "<?php echo MODULE; ?>" ;


		$( "select[name*='"+module_name+"_retenue_0[0]'] option").hide();

			
				$.ajax({
					   url: "/admin/ajax/get_retenue.php",
						type: "GET",
						data: {
							id: id_fournisseur,
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var count = Object.keys(obj).length;
							// for (j = 0; j < count; j++) { 
							//console.log("retenue ==> "+obj.retenue);
							$( "select[name*='"+module_name+"_retenue_0[0]'] option[value='']").show();
							$( "select[name*='"+module_name+"_retenue_0[0]'] option[value='"+obj.retenue+"']").show();


							// }
							
						}	
					});	
}




function Get_facture_vente_v2(id_client)
{
var module_name = "<?php echo MODULE; ?>" ;

	for (v = 0; v < 10; v++) { 
		$( "select[name*='"+module_name+"_product_ref_facture_vente2_0["+v+"]'] option").hide();
	}
			
				$.ajax({
					   url: "/admin/ajax/get_facture_client_v2.php",
						type: "GET",
						data: {
							id_client: id_client,
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var count = Object.keys(obj).length;
							for (j = 0; j < count; j++) { 
							//console.log(obj[j]);
								for (v = 0; v < 10; v++) { 
									$( "select[name*='"+module_name+"_product_ref_facture_vente2_0["+v+"]'] option[value='"+obj[j]+"']").show();
									$( "select[name*='"+module_name+"_product_ref_facture_achat2_0["+v+"]']").hide();
								}	
							}
							
						}	
					});	
}

function Get_details_facture_vente(id_facture,index)
{
var module_name = "<?php echo MODULE; ?>" ;


			
				$.ajax({
					   url: "/admin/ajax/get_details_facture_vente.php",
						type: "GET",
						data: {
							id: id_facture,
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var count = Object.keys(obj).length;
							
							$("input[name*='"+module_name+"_product_date_ech_0["+index+"][date]']").attr("readonly","readonly");
							$("input[name*='"+module_name+"_product_montant_facture_0["+index+"]']").attr("readonly","readonly");
							$("input[name*='"+module_name+"_product_reste_0["+index+"]']").attr("readonly","readonly");	
							
							$("input[name*='"+module_name+"_product_date_ech_0["+index+"][date]']").val(obj["date_ech"]);								
							$("input[name*='"+module_name+"_product_montant_facture_0["+index+"]']").val(obj["total_ttc"]);								
							$("input[name*='"+module_name+"_product_reste_0["+index+"]']").val(obj["reste"]);								
							$("input[name*='"+module_name+"_product_montant_0["+index+"]']").val(obj["reste"]);	
							// alert(obj["date_ech"]);
							
							//======= Update Montant
							calculer_montant();	
							//==========
							if(obj["date_ech"] != ""){
								Get_echeance(obj["date_ech"]);
							}
							
							//==========
						}	
					});	
}
function Get_details_facture(id_facture,index)
{
var module_name = "<?php echo MODULE; ?>" ;


			
				$.ajax({
					   url: "/admin/ajax/get_details_facture.php",
						type: "GET",
						data: {
							id: id_facture,
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var count = Object.keys(obj).length;
							
							$("input[name*='"+module_name+"_product_date_ech_0["+index+"][date]']").attr("readonly","readonly");
							$("input[name*='"+module_name+"_product_montant_facture_0["+index+"]']").attr("readonly","readonly");
							$("input[name*='"+module_name+"_product_reste_0["+index+"]']").attr("readonly","readonly");	
							
							$("input[name*='"+module_name+"_product_date_ech_0["+index+"][date]']").val(obj["date_ech"]);								
							$("input[name*='"+module_name+"_product_montant_facture_0["+index+"]']").val(obj["total_ttc"]);								
							$("input[name*='"+module_name+"_product_reste_0["+index+"]']").val(obj["reste"]);								
							$("input[name*='"+module_name+"_product_montant_0["+index+"]']").val(obj["reste"]);	
							// alert(obj["date_ech"]);

							//======= Update Montant
							calculer_montant();
							
							//==========
							// Get_echeance(obj["date_ech"]);
							if(obj["date_ech"] != ""){
								Get_echeance(obj["date_ech"]);
							}
							//==========
							
							
						}	
					});	
}




function Get_echeance(date_reglement)
{
	//=====================
	var type_ready = $("#type").val();
	//=====================
	var words = date_reglement.split('-');
	var date_getted = words[2]+"-"+words[1]+"-"+words[0] ;
	var d=new Date(date_getted);
	var d_from_facture=d.getTime();
	//=================
	var date_ech = $("input[name*='transaction_date_echeance_0[0][date]']").val();
	var words2 = date_ech.split('-');
	if(words2[0].length < 3 ){
		var date_getted2 = words2[2]+"-"+words2[1]+"-"+words2[0] ;	
		var d2=new Date(date_getted2);		
	}else{
		var d2=new Date(date_ech);
	}

	var d_tawa=d2.getTime();	
	
	// alert(d_tawa +" | "+ d_from_facture);
	if((d_tawa < d_from_facture) && (type_ready == "out") ){
		$("input[name*='transaction_date_echeance_0[0][date]']").val(date_reglement);
	}


	

}


function Get_TTC(id_facture,table)
{
					$.ajax({
					   url: "/admin/ajax/get_ttc_facture.php",
						type: "GET",
						data: {
							id    : id_facture,
							table : table
						},
						dataType: "JSON",
						success: function (jsonStr) { 
							var text = JSON.stringify(jsonStr) ;
							//console.log(text);
							var obj = JSON.parse(text);
							var count = Object.keys(obj).length;
							if(obj["total_ttc"] == 0){
								var ref_facture = $("#ref_facture_achat option[value='"+id_facture+"']").text();
								alert("Merci de générer la facture +++ "+ref_facture+" +++");
							}
							var retenue = $("#retenue").val();
							if(retenue == ""){
								var montant = obj["total_ttc"];
								$("input[name*='transaction_retenue_montant_0[0]").val('');
							}else{
								var retn = (obj["total_ttc"] * retenue)/100 ;
								var montant = obj["total_ttc"] - retn;
								$("input[name*='transaction_retenue_montant_0[0]").val(retn.toFixed(3));
							}
							
							$("input[name*='transaction_montant_0[0]").val(parseFloat(montant).toFixed(3));
							var date_facture = obj["date_entre"] ;
							var fournisseur = obj["fournisseur"] ;
							// Get_echeance(fournisseur,date_facture);
						}	
					});	
}
</script>


<?php
if(NB_FILES > 0 && (in_array("add", $permissions) || in_array("edit", $permissions) || in_array("all", $permissions))){ ?>
    <script src="<?php echo DOCBASE.ADMIN_FOLDER; ?>/includes/uploadifive/jquery.uploadifive.js"></script>
    <link href="<?php echo DOCBASE.ADMIN_FOLDER; ?>/includes/uploadifive/uploadifive.css" rel="stylesheet">
    <script src="<?php echo DOCBASE.ADMIN_FOLDER; ?>/js/toolMan.js"></script>
    <script>
        var dragsort = ToolMan.dragsort();
        var junkdrawer = ToolMan.junkdrawer();
        
        $(function() {
            
            $('.files-list').each(function(){
                
                var id_list = $(this).attr('id');
                
                dragsort.makeListSortable(document.getElementById(id_list), saveOrder);
                
                function saveOrder(item) {
                    var group = item.toolManDragGroup;
                    var id = group.element.parentNode.getAttribute('id');
                    if(id == null) return;
                    group.register('dragend', function(){
                        
                        var list = ToolMan.junkdrawer().serializeList(document.getElementById(id_list));
                        
                        $.ajax({
                            type: "POST",
                            url: '<?php echo DOCBASE.ADMIN_FOLDER; ?>/includes/order_medias.php?list='+list+'&table=<?php echo MODULE."_file"; ?>&id_item=<?php echo $id; ?>&prefix=file'
                        });
                    })
                }
            });
            
            <?php
            if(empty($_SESSION['msg_error'])){ ?>
                $.ajax({
                    type: 'POST',
                    url: '<?php echo DOCBASE.ADMIN_FOLDER; ?>/includes/clear_tmp.php',
                    data: 'dir=medias/<?php echo MODULE; ?>/tmp&token=<?php echo $_SESSION['token'];?>',
                    success: function(data){
                        
                    }
                });
                <?php
            } ?>
            
            $('.file_upload').each(function(){
                
                var id = $(this).attr('id');
                var rel = $(this).attr('rel').split(',');
                var lang = rel[0];
                var max_file = rel[1];
                
                if(max_file > 10) max_file = 10;
                
                var container = $('#file_uploaded_'+lang);
                if($('.prev-file', container).size() > 0) container.slideDown();
                
                $('#'+id).uploadifive({
                    'formData'         : {
                        'timestamp' : '<?php echo $_SESSION['timestamp'];?>',
                        'uniqid' : '<?php echo $_SESSION['uniqid'];?>',
                        'token' : '<?php echo $_SESSION['token'];?>',
                        'dir' : '<?php echo MODULE; ?>',
                        'root_bo' : '<?php echo DOCBASE.ADMIN_FOLDER; ?>/',
                        'exts' : '<?php echo serialize(array_keys($allowable_file_exts)); ?>',
                        'lang' : lang
                    },
                    'buttonText'     : '<i class="fa fa-folder-open"></i> <?php echo $texts['CHOOSE_FILE']; ?>',
                    'fileTypeDesc'     : 'Files',
                    'fileTypeExts'     : '<?php foreach(array_keys($allowable_file_exts) as $file_ext) echo "*.".$file_ext.";*.".mb_strtoupper($file_ext, "UTF-8").";"; ?>',
                    'multi'            : (max_file > 1),
                    'queueSizeLimit': max_file,
                    'uploadLimit'     : max_file,
                    'queueID'        : 'file_upload_'+lang+'-queue',
                    'uploadScript'     : '<?php echo DOCBASE.ADMIN_FOLDER; ?>/includes/uploadifive/uploader/uploadifive.php',
                    'onUploadComplete' : function(file, data, response){
                        
                        data = data.split('|');
                        
                        if($('.prev-file', container).size() == 0) container.slideDown();
                            
                        var filename = data[0].substring(data[0].lastIndexOf('/')+1);
                        var ext = filename.substring(filename.lastIndexOf('.')+1).toLowerCase();
                        
                        if((data[2] == 0 && data[3] == 0) || ext == 'swf'){
                        
                            var icon_file = '';
                            
                            switch(ext){
                                <?php
                                foreach($allowable_file_exts as $file_ext => $icon_file)
                                    echo "case '".$file_ext."' : icon_file = '".$icon_file."'; break;\n"; ?>
                            }
                            
                            container.append('<div class="prev-file"><img src="<?php echo DOCBASE; ?>common/images/'+icon_file+'" alt="" border="0">'+filename.substring(0, filename.lastIndexOf('.')).substring(0, 15)+'...'+ext+'<br>'+data[1]+'</div>');
                        
                        }else
                            container.append('<div class="prev-file"><img src="'+data[0]+'" alt="" border="0">'+filename.substring(0, filename.lastIndexOf('.')).substring(0, 15)+'...'+ext+'<br>'+data[1]+' | '+data[2]+' x '+data[3]+'</div>');
                        
                        if($('.prev-file', container).size() == 1) container.slideDown();
                    }
                });
            });
        });
    </script>
	
	
    <?php
} ?>


<style>
#dialog td,th{
	padding:10px;
	text-align: center;
}
#dialog_be td,th{
	padding:5px;
	text-align: center;
}
.error_qte{
	border: 1px solid red;
}
.succes_gte{
	border: 1px solid green;
}
</style>

