
  var table 

  var query_id = getQueryVariable("id");
  var query_pid = getQueryVariable("pid");
  var query_sid = getQueryVariable("sid");
  var query_bid = getQueryVariable("bid");
  var query_cid = getQueryVariable("cid");

  

  function delete_items(itemid) {
    block = $("#list_of_items_tbl");
    // bootstrap modal confirmation box
      swal({
          title: Translation("هل انت متأكد؟!"),
          text: Translation("سوف لن تستطيع استرجاع المعلومات المرتبطة بهذا السجل في حالة المسح"),
          type: "warning",
          showCancelButton: true,
          confirmButtonColor: "#EF5350",
          confirmButtonText: Translation("موافق: امسح!"),
          cancelButtonText: Translation("الغاء الامر"),
          closeOnConfirm: false,
          closeOnCancel: true
      },
      function(isConfirm){
          if (isConfirm) {
            $.ajax({
              url: "models/crul_stock.php",
              type:"POST",
              dataType : "JSON",
              data: {"type":"delete","obj_id":itemid} ,
              complete:function(){
               // hideLoader();
              },
              beforeSend:function(){
               // showLoader("Deleting Category");
              },
              success: function(res) {

                if(res.is_success == true){
                  swal({
                          title: Translation("حذف"),
                          text: Translation(res.data),
                          confirmButtonColor: "#66BB6A",
                          type: "success"
                      });
                  $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                }else{
                  swal({
                          title: Translation("خطأ"),
                          text: Translation(res.data),
                          confirmButtonColor: "#2196F3",
                          type: "error"
                      });
                }
              }
          });
          }
      }); // /confirm
  }

  // finish_product

  function compute_remain_price(val, id){

    var row_num1 = id.split('_');
    var row_num = row_num1[3];
    if(val !="" &&  !isNaN(val) && val !=null && val !=undefined ){
      val = val;
    }else{
      val = 0;
    }
      // var real_price = $("#product_row_total_"+row_num).attr('data-actual-row-price'); 
      var old_remain   = $("#inv_total_paid_"+row_num).attr('data-total-remain-price');
      
        // alert("old_paid="+old_paid)

      // if(real_price == null || real_price == undefined || isNaN(real_price)){real_price=0;}
      if(old_remain   == null || old_remain   == undefined || isNaN(old_remain)){old_remain=0; }
     
      var new_remaind = old_remain - val;

     
      if(new_remaind < 0){

        //  noty({
        //         width: 200,
        //         text: Translation("الرجاء التأكد من القيمة المدخلة لان المدفوعات اصبحت اكبر من السعر الكلي للمادة"),
        //         type: 'error',
        //         dismissQueue: true,
        //         timeout: 4000,
        //         layout: 'topRight',
        //       });

        // $("#"+id).val('');
        // $("#inv_row_remaind_price_"+row_num).val(currency_format_display( old_remain));

        $("#inv_row_remaind_price_"+row_num).val(currency_format_display( new_remaind));

      }else{
        $("#inv_row_remaind_price_"+row_num).val(currency_format_display( new_remaind));

      }

       // compute total invoice paid and total remained
        var sum = 0;        

        $('input[id^="inv_paid_price_"]').each(function() 
        { 
          if(!isNaN(this.value) && this.value.length!=0) 
          {
            sum += parseFloat(this.value);            
          }         
        });

        var old_papid   = $("#total_inv_paid").attr('data-total-inv-paid');
        if(old_papid   == null || old_papid   == undefined || isNaN(old_papid)){old_papid=0; }

        var new_pay = +old_papid + +sum;
        $("#total_inv_paid").html(currency_format_display(new_pay));

        var old_actual_price   = $("#total_inv_actual").attr('data-total-inv-actual');
        if(old_actual_price   == null || old_actual_price   == undefined || isNaN(old_actual_price)){old_actual_price=0; }

        var all_invoice_remaind = old_actual_price - new_pay;
        $("#total_inv_remain").html(currency_format_display(all_invoice_remaind));


  }
    

   

    




  function get_Branch(){



          $.ajax({
                url : 'models/crul_branch.php',
                type : 'POST',
                data : {type:'get',branch_id:BRANCH_ID},
                dataType : 'json',
                success : function(response) {
                    var attach ='<option value="" selected="selected">'+Translation('تحديد الفرع')+'</option>';
                    
                    for(var i=response.length-1 ; i >= 0;i--){
                        
                    
                      attach = attach + '<option data-stock-id-fk="'+response[i].stock_id+'" data-subtext="'+response[i].location+'" value="'+response[i].branch_id+'">'+response[i].branch_name+'</option>';
                      
                    }
                      $("#branch_id_fk").html(attach);
                      $("#edit_branch_id_fk").html(attach);
                      $('#branch_id_fk').selectpicker('refresh');
                      // $("#edit_stock_id_fk").selectpicker('refresh');
                },
                complete: function() {
                       
                }

          }); // submit ajax

  }



  function get_Customer(){

          $.ajax({
                url : 'models/crul_customer.php',
                type : 'POST',
                data : {type:'get'},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<option value="" selected="selected">'+Translation('تحديد الزبون')+'</option>';
                    var aaa='';
                      for(var i=response.length-1 ; i >= 0;i--){
                        var tp  = response[i][2];
                        var tp1 = response[i][3];
                        var tp2 = response[i][4];
                        var tp3 = response[i][5];
                        attach = attach + '<option data-profile-price="'+response[i][6]+'" data-subtext="'+Translation('هاتف')+': '+tp+' || '+Translation('شركة')+': '+tp2+' || '+Translation('محدودية المال')+': '+currency_format_display(tp3)+' " value="'+response[i][0]+'">'+response[i][1]+'</option>';
                        aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

                      }
                      $("#customer_id_fk").html(attach);
                      $("#edit_customer_id_fk").html(attach);
                      $('#customer_id_fk').selectpicker('refresh');
                      $("#edit_customer_id_fk").selectpicker('refresh');

                      $("#main_customer_id_fk").html(attach);

                      $('#main_customer_id_fk').selectpicker('refresh');

                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

  }


  function get_Saleman(){

          $.ajax({
                url : 'models/crul_saleman.php',
                type : 'POST',
                data : {type:'get'},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<option value="" selected="selected">'+Translation('تحديد المندوب')+'</option>';
                    var aaa='';
                      for(var i=response.length-1 ; i >= 0;i--){
                        
                        attach = attach + '<option  data-subtext="'+Translation('هاتف')+': '+response[i][2]+'  " value="'+response[i][0]+'">'+response[i][1]+'</option>';
                        
                      }
                      $("#saleman_id_fk").html(attach);
                      $("#edit_saleman_id_fk").html(attach);
                      $('#saleman_id_fk').selectpicker('refresh');
                      $("#edit_saleman_id_fk").selectpicker('refresh');
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

  }


  function get_Saleman_pay(){

          $.ajax({
                url : 'models/crul_saleman.php',
                type : 'POST',
                data : {type:'get'},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<option value="" selected="selected">'+Translation('تحديد المندوب')+'</option>';
                    var aaa='';
                      for(var i=response.length-1 ; i >= 0;i--){
                        
                        attach = attach + '<option  data-subtext="'+Translation('هاتف')+': '+response[i][2]+'  " value="'+response[i][0]+'">'+response[i][1]+'</option>';
                        
                      }
                      $("#sale_man_id_0").html(attach);
                      $('#sale_man_id_0').selectpicker('refresh');
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

  }

   
  function get_product_search(){
        
        $.ajax({
                url : 'models/crul_product.php',
                type : 'POST',
                data : {type:'get_product_with_last_buy_price'},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<option value="" selected="selected">'+Translation('Search for Products')+'</option>';
                    for(var i=response.length-1 ; i >= 0;i--){
                        
                       
                      attach = attach + '<option  data-subtext="" value="'+response[i].product_id+'" data-sell-price="'+response[i].sell_price+'"  data-last-buy-price="'+response[i].buy_price+'">'+response[i].product_name+'</option>';

                        
                    }
                     
                      
                      $("#product_id").html(attach);
                      $('#product_id').selectpicker('refresh');

                      
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

        

       

  }

  function get_products(row_num){
        
        $.ajax({
                url : 'models/crul_product.php',
                type : 'POST',
                data : {type:'get_product_with_last_buy_price'},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<option value="" selected="selected">'+Translation('Search for Products')+'</option>';
                    for(var i=response.length-1 ; i >= 0;i--){
                        
                       
                      attach = attach + '<option  data-subtext="" value="'+response[i].product_id+'" data-sell-price="'+response[i].sell_price+'"  data-last-buy-price="'+response[i].buy_price+'">'+response[i].product_name+'</option>';

                        
                    }
                     
                      
                      $("#product_id_fk_"+row_num).html(attach);
                      $('#product_id_fk_'+row_num).selectpicker('refresh');

                      $("#edit_product_id_fk_"+row_num).html(attach);
                      $('#edit_product_id_fk_'+row_num).selectpicker('refresh');

                      
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

        

       

  }


  function edit_get_products(row_num,id=null,typ=null){
        
        $.ajax({
                url : 'models/crul_product.php',
                type : 'POST',
                data : {type:'get_product_with_last_buy_price'},
                dataType : 'json',
                success : function(response) {
                      var attach ='<option value="" selected="selected">'+Translation('اختيار المادة')+'</option>';
                      
                      for(var i=response.length-1 ; i >= 0;i--){   
                         
                        attach = attach + '<option  data-subtext="" value="'+response[i].product_id+'" data-sell-price="'+response[i].sell_price+'"  data-last-buy-price="'+response[i].buy_price+'">'+response[i].product_name+'</option>';
                          
                      }  
                    
                      
                      if(typ == 'edit_product_id_fk_'){
                        $("#"+typ+row_num).html(attach);
                        $("#"+typ+row_num).selectpicker('refresh');
                      }
                      
                      


                      if(id !=null && id !=''){
                        $('#'+typ+row_num).val(id).selectpicker('refresh');
                      }
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

        

       

  }

  







   

  function load_on_hand(row_num){
       
        var product_id  = $("#product_id_fk_"+row_num).val();
        var stock_id    = $("#stock_id_fk").val();

        if(stock_id ==null || stock_id =='' || stock_id == undefined){
          noty({
                    width: 200,
                    text: Translation("الرجاء قم بتحديد اسم المخزن لعرض الكمية المتوفرة من هذه المادة"),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
                  });
          return false;
        }
        
        $.ajax({
                url : 'models/crul_stock_detail.php',
                type : 'POST',
                data : {type:'get_on_hand',product_id:product_id,stock_id:stock_id},
                dataType : 'json',
                success : function(response) {
                  console.log(response)
                    if(response.data[0].on_hand_quantity <= 0){
                      $("#on_hand_alert_"+row_num).removeClass('bg-success');
                      $("#on_hand_alert_"+row_num).addClass('bg-warning');
                    }else{
                      $("#on_hand_alert_"+row_num).removeClass('bg-warning');
                      $("#on_hand_alert_"+row_num).addClass('bg-success');
                    }
                      $("#on_hand_alert_"+row_num).text(response.data[0].on_hand_quantity);   
                    
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax


     
    // end loading price
  }
 

  function load_prices(row_num){
      
        
        
        var sell_price    = $("#product_id_fk_"+row_num+" option:selected").attr('data-sell-price');
       

        

        if(sell_price=='' || sell_price ==null){
            noty({
                    width: 200,
                    text: Translation("لم يتم تحديد سعر بيع لهذه المادة"),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',

                  });
            return false;
        }

        $("#sell_price_"+row_num).val(sell_price);

        calc_total_item_cost("sell_price_"+row_num,row_num);

       
    // end loading price
  }


  function edit_load_prices(row_num){
      
        var sell_price    = $("#edit_product_id_fk_"+row_num+" option:selected").attr('data-sell-price');
       

        

        if(sell_price=='' || sell_price ==null){
            noty({
                    width: 200,
                    text: Translation("لم يتم تحديد سعر بيع لهذه المادة"),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',

                  });
            return false;
        }

        $("#edit_sell_price_"+row_num).val(sell_price);

        edit_calc_total_item_cost("edit_sell_price_"+row_num,row_num);
  }

   


  function load_invoices(id=null){
       
       
        
        $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'load_invoices'},
                dataType : 'json',
                success : function(response) {
                  // console.log(response.data)
                    var attach ='<option value="" selected="selected">'+Translation('اختيار الوصل الاصلي')+'</option>';
                      for(var i=response.data.length-1 ; i >= 0;i--){
                        
                        var tp  =response.data[i]['customer_full_name'];
                        var tp1 =response.data[i]['invoice_date'];
                        attach = attach + '<option data-subtext="'+Translation('اسم الزبون')+' : '+tp+' || '+Translation('تاريخ الوصل')+' : '+tp1+'"  value="'+response.data[i]['invoice_id']+'">'+response.data[i]['invoice_number']+'</option>';
                      }
                      $("#original_invoice_id_fk").html(attach);
                      $('#original_invoice_id_fk').selectpicker('refresh');
                      // console.log(attach)
                      $("#edit_original_invoice_id_fk").html(attach);
                      $("#edit_original_invoice_id_fk").selectpicker('refresh');

                      if(id !=null){
                        $("#edit_original_invoice_id_fk").val(id).selectpicker('refresh');

                      }
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax


     
    // end loading price
  }


    


  function load_last_prices(row_num){
    // load price for this product

        
        // var P_ID  = $("#product_id_fk_"+row_num).val();
        // // to load the last sell price for this customer
        // var Cus_ID  = $("#customer_id_fk").val();

        // if(Cus_ID=='' || Cus_ID ==null){
        //     noty({
        //             width: 200,
        //             text: Translation("الرجاء قم بتحديد اسم الزبون لتحميل اخر سعر بيع له"),
        //             type: 'error',
        //             dismissQueue: true,
        //             timeout: 3000,
        //             layout: 'topRight',
        //           });
        //     return false;
        // }


        // $.ajax({
        //         url : 'models/crul_product_price.php',
        //         type : 'POST',
        //         data : {type:'get_last_sell_price',p_val:P_ID,Cus_ID:Cus_ID},
        //         dataType : 'json',
        //         success : function(response) {
                 
        //               if(response==0){
        //                 $("#last_sell_price_"+row_num).val('');
                        
        //                 noty({
        //                   width: 200,
        //                   text: Translation("لا يوجد اخر سعر بيع لهذا الزبون"),
        //                   type: 'error',
        //                   dismissQueue: true,
        //                   timeout: 3000,
        //                   layout: 'topRight',
        //                 });

        //               }else{
        //                 $("#last_sell_price_"+row_num).val(response[0][0]); 
                        
        //               }
        //         },
        //         complete: function() {

        //         }

        //   }); // submit ajax
    // end loading price
  }



  function calc_total_item_cost(id,row_no){
        var row_num1 = id.split('_');
        var row_num = row_no ; // row_num1[4];
        var actual_disc = 0;

        var total_item_cost = $("#purchase_quantity_"+row_num).val() * $("#sell_price_"+row_num).val();

        var actual_disc = 0;
        
        var discount = $("#discount_"+row_num).val();
        if (discount.indexOf('%') > -1)
        {
          $("#discount_"+row_num).attr('data-discount-type','0'); // percentage
          var diss = parseFloat(discount.replace('%',''));
          if(!isNaN(diss)){
            actual_disc     = (total_item_cost * diss / 100);
          }
          
        }else if(discount !='' && !isNaN(discount)){
          $("#discount_"+row_num).attr('data-discount-type','1'); // absolute
          actual_disc = discount;
        }
        
        $("#discount_"+row_num).attr('data-discount-actual',actual_disc); // absolute
        
        total_item_cost = total_item_cost - actual_disc;
        total_item_cost = total_item_cost.toFixed(2);
        

        $("#total_item_cost_"+row_num).val(currency_format_display(total_item_cost));  
        
        calc_total_invoice_price();
  }


  function edit_calc_total_item_cost(id,row_no){
        

        var row_num1 = id.split('_');
        var row_num = row_no ; // row_num1[4];
        var actual_disc = 0;

        var total_item_cost = $("#edit_purchase_quantity_"+row_num).val() * $("#edit_sell_price_"+row_num).val();

        var actual_disc = 0;
        
        var discount = $("#edit_discount_"+row_num).val();
        if (discount.indexOf('%') > -1)
        {
          $("#edit_discount_"+row_num).attr('data-discount-type','0'); // percentage
          var diss = parseFloat(discount.replace('%',''));
          if(!isNaN(diss)){
            actual_disc     = (total_item_cost * diss / 100);
          }
          
        }else if(discount !='' && !isNaN(discount)){
          $("#edit_discount_"+row_num).attr('data-discount-type','1'); // absolute
          actual_disc = discount;
        }
        
        $("#edit_discount_"+row_num).attr('data-discount-actual',actual_disc); // absolute
        
        total_item_cost = total_item_cost - actual_disc;
        total_item_cost = total_item_cost.toFixed(2);
        

        $("#edit_total_item_cost_"+row_num).val(currency_format_display(total_item_cost));  
        
        
        edit_calc_total_invoice_price();


        
  }

  

  function calc_payments(row_num=null) {

        // check if current payment greater than row total price
          

          // var cur_pay   = $("#payment_total").val();
          // var prod_cost = $("#purchase_total").val();


          // if (prod_cost.indexOf('$') > -1)
          // {
            
          //    prod_cost = prod_cost.replace('$','');
            
          // }

          // if (prod_cost.indexOf(',') > -1)
          // {
            
          //    prod_cost = prod_cost.replace(/,/g,'');
            
          // }


          // if (cur_pay.indexOf('$') > -1)
          // {
            
          //    cur_pay = cur_pay.replace('$','');
            
          // }

          // if (cur_pay.indexOf(',') > -1)
          // {
            
          //    cur_pay = cur_pay.replace(/,/g,'');
            
          // }

          // prod_cost = parseFloat(prod_cost);
          // cur_pay   = parseFloat(cur_pay);

          // if(cur_pay > prod_cost){
          //   noty({
          //             width: 200,
          //             text: Translation("قيمة المبلغ المدفوع اكبر من المجموع الكلي لهذه الوصل .. الرجاء ادخال القيمة الصحيحة"),
          //             type: 'error',
          //             dismissQueue: true,
          //             timeout: 3000,
          //             layout: 'topRight',
          //           });
            
            
          //     $("#payment_total").val('');
            
          // }

  }


  function edit_calc_payments(row_num=null) {

        // check if current payment greater than row total price
          

          // var cur_pay   = $("#edit_payment_total").val();
          // var prod_cost = $("#edit_purchase_total").val();


          // if (prod_cost.indexOf('$') > -1)
          // {
            
          //    prod_cost = prod_cost.replace('$','');
            
          // }

          // if (prod_cost.indexOf(',') > -1)
          // {
            
          //    prod_cost = prod_cost.replace(/,/g,'');
            
          // }


          // if (cur_pay.indexOf('$') > -1)
          // {
            
          //    cur_pay = cur_pay.replace('$','');
            
          // }

          // if (cur_pay.indexOf(',') > -1)
          // {
            
          //    cur_pay = cur_pay.replace(/,/g,'');
            
          // }

          // prod_cost = parseFloat(prod_cost);
          // cur_pay   = parseFloat(cur_pay);

          // if(cur_pay > prod_cost){
          //   noty({
          //             width: 200,
          //             text: Translation("قيمة المبلغ المدفوع اكبر من المجموع الكلي لهذه الوصل .. الرجاء ادخال القيمة الصحيحة"),
          //             type: 'error',
          //             dismissQueue: true,
          //             timeout: 3000,
          //             layout: 'topRight',
          //           });
            
            
          //     $("#edit_payment_total").val('');
            
          // }

  }



  function calc_total_invoice_price(){
        // footer of table purchase_total
        var invoice_total =0;
        var curnt_row_num = $("#total_rows").val();
        for (var i = 1; i <= curnt_row_num; i++) {

          // check if items exisit and not delted
          if($("#total_item_cost_"+i).length > 0){  
            var td_cost = $("#total_item_cost_"+i).val();
            // var td_cost = $("#purchase_quantity_"+i).val() * $("#sell_price_"+i).val();

          
            cost = td_cost.split(" ");
            rep_cost =cost[0].replace(/,/g,'');
            if(isNaN(rep_cost) || rep_cost ==""){
              rep_cost =0;
            }
            invoice_total = +invoice_total + +parseFloat(rep_cost).toFixed(2);
          }
          
        }


        

        // before discount
        $("#invoice_total_no_disc").val(currency_format_display(invoice_total));

        var actual_disc = 0;
        // discount and checking for % or absolute val
        var discount = $("#discount_total").val();
        if (discount.indexOf('%') > -1)
        {
          $("#discount_total").attr('data-discount-type','0'); // percentage
          var diss = parseFloat(discount.replace('%',''));
          if(!isNaN(diss)){
            actual_disc     = (invoice_total * diss / 100);
          }
          
        }else if(discount !='' && !isNaN(discount)){
          $("#discount_total").attr('data-discount-type','1'); // absolute
          actual_disc = discount;
        }

        $("#discount_total").attr('data-discount-actual',actual_disc); // absolute discount

        // price after discount
        invoice_total = invoice_total - actual_disc;
        $("#grand_total").val(currency_format_display(invoice_total));
        calc_total_discount_price();


  }


  function edit_calc_total_invoice_price(){
        
        var invoice_total =0;
        var curnt_row_num = $("#edit_total_rows").val();
        for (var i = 0; i <= curnt_row_num; i++) {

          // check if items exisit and not delted
          if($("#edit_total_item_cost_"+i).length > 0){  
            var td_cost = $("#edit_total_item_cost_"+i).val();
            
            cost = td_cost.split(" ");
            rep_cost =cost[0].replace(/,/g,'');
            if(isNaN(rep_cost) || rep_cost ==""){
              rep_cost =0;
            }
            invoice_total = +invoice_total + +parseFloat(rep_cost).toFixed(2);
          }
          
        }


        // before discount
        $("#edit_invoice_total_no_disc").val(currency_format_display(invoice_total));

        var actual_disc = 0;
        // discount and checking for % or absolute val
        var discount = $("#edit_discount_total").val();
        if (discount.indexOf('%') > -1)
        {
          $("#edit_discount_total").attr('data-discount-type','0'); // percentage
          var diss = parseFloat(discount.replace('%',''));
          if(!isNaN(diss)){
            actual_disc     = (invoice_total * diss / 100);
          }
          
        }else if(discount !='' && !isNaN(discount)){
          $("#edit_discount_total").attr('data-discount-type','1'); // absolute
          actual_disc = discount;
        }

        $("#edit_discount_total").attr('data-discount-actual',actual_disc); // absolute discount

        // price after discount
        invoice_total = invoice_total - actual_disc;
        $("#edit_grand_total").val(currency_format_display(invoice_total));
        edit_calc_total_discount_price();



  }


  function calc_total_discount_price(){
        // footer of table purchase_total
        var invoice_total =0;
        var curnt_row_num = $("#total_rows").val();
        for (var i = 1; i <= curnt_row_num; i++) {

          // check if items exisit and not delted
          if($("#total_item_cost_"+i).length > 0){  
            var td_cost = $("#discount_"+i).attr('data-discount-actual');
           
            
            if(isNaN(td_cost) || td_cost ==""){
              td_cost =0;
            }
            invoice_total = +invoice_total + +parseFloat(td_cost).toFixed(2);
          }
          
        }

       
        $("#discount_total").attr('data-discount-type','1'); // absolute
        $("#discount_total").attr('data-discount-actual',invoice_total); // absolute discount
        

        // before discount
        $("#discount_total").val(currency_format_display(invoice_total));

        


  }


  function edit_calc_total_discount_price(){
        // footer of table purchase_total
        var invoice_total =0;
        var curnt_row_num = $("#edit_total_rows").val();
        for (var i = 0; i <= curnt_row_num; i++) {

          // check if items exisit and not delted
          if($("#edit_total_item_cost_"+i).length > 0){  
            var td_cost = $("#edit_discount_"+i).attr('data-discount-actual');
           
            
            if(isNaN(td_cost) || td_cost ==""){
              td_cost =0;
            }
            invoice_total = +invoice_total + +parseFloat(td_cost).toFixed(2);
          }
          
        }

       
        $("#edit_discount_total").attr('data-discount-type','1'); // absolute
        $("#edit_discount_total").attr('data-discount-actual',invoice_total); // absolute discount
        

        // before discount
        $("#edit_discount_total").val(currency_format_display(invoice_total));

        


  }


  function repeat_discount(){
        // footer of table purchase_total
        var dis_val = $("#repeated_discount").val();
       
        var curnt_row_num = $("#total_rows").val();
        for (var i = 1; i <= curnt_row_num; i++) {

          // check if items exisit and not delted
          if($("#total_item_cost_"+i).length > 0){  
            $("#discount_"+i).val(dis_val);

            calc_total_item_cost('id',i);
           
          }
          
        }


  }


    


  function Add_Rows(){

    var curnt_row_num = $("#edit_total_rows").val();
    var CNT = +curnt_row_num + +1;
    var attach_new_row =`

                        <tr  id="edit_item_row_`+CNT+`" >
                          <td  id="edit_num_`+CNT+`">`+(+CNT + +1)+`</td>


                          <td >
                                         
                            <select class="form-control multi_lang" name="edit_product_id_fk_`+CNT+`" id="edit_product_id_fk_`+CNT+`"   onchange="edit_load_prices(`+CNT+`);" data-live-search="true" required="required">

                            </select>

                          </td>

                          <td >
                            <input type="number" value="1" id="edit_purchase_quantity_`+CNT+`" name="edit_purchase_quantity_`+CNT+`"  class="form-control text-center " placeholder="`+Translation('الكمية')+`"  onchange="edit_calc_total_item_cost(this.id,`+CNT+`);" required="required">

                          </td>

                          <td >
                            <input  value="" id="edit_sell_price_`+CNT+`" name="edit_sell_price_`+CNT+`" type="text" class="form-control text-center" placeholder="`+Translation('سعر بيع الوحدة')+`" onchange="edit_calc_total_item_cost(this.id,`+CNT+`);" required="required" >

                          </td>


                          <td >
                            <input  value="" id="edit_discount_`+CNT+`" name="edit_discount_`+CNT+`" type="text" class="form-control text-center" data-discount-type="" data-discount-actual="" placeholder="`+Translation('التخفيضات')+`" onchange="edit_calc_total_item_cost(this.id,`+CNT+`);"  >
                          </td>

                         

                          <td >
                            <input  value="" id="edit_total_item_cost_`+CNT+`" name="edit_total_item_cost_`+CNT+`" type="text" class="form-control text-center " placeholder="`+Translation('الكلفة الاجمالية')+`"  disabled="disabled" >
                            
                          </td>

                          <td >
                            <input value="" id="edit_sell_item_note_`+CNT+`" name="edit_sell_item_note_`+CNT+`" type="text" class="form-control multi_lang " placeholder="`+Translation('ملاحظة')+`" >
                          </td>
                           


                          <td >
                            <button class="btn btn-link btn-xs edit_btn_add_item tab_last" onclick="Add_Rows()">
                              <i  class="icon-add text-blue"></i>
                            </button>
                            <button tabindex="-1" class="btn btn-link btn-xs btn_remove_item" id="edit_row_`+CNT+`" onclick="remove_rows(`+CNT+`)">
                              <i  class="icon-subtract text-danger-600"></i>
                            </button>
                            
                          </td>
                        </tr>
                          `;

          $("#edit_purchase_item_body").append(attach_new_row);
          $("#edit_total_rows").val(CNT);
          get_products(CNT);
         

  }


  function remove_rows(row_num){
  
        
        $("#edit_item_row_"+row_num).remove();
        edit_calc_total_invoice_price();
        edit_calc_payments();
  
  }

  
  function auto_number(){

      var curnt_row_num = $("#total_rows").val();
      var CNT = +curnt_row_num + +1;
      var k =1;
      for (var i = 1; i <= CNT; i++) {
        if($("#num_"+i).length > 0){
          $("#num_"+i).text(k);
          k++;
        }
        
      }

  }


  function get_Stock(){



            $.ajax({
                  url : 'models/crul_stock.php',
                  type : 'POST',
                  data : {type:'get',branch_id:BRANCH_ID},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="" selected="selected">'+Translation('تحديد المخزن')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp =Translation("خزن");
                          if(response[i][2]==1){tp =Translation("انتاج");}
                          attach = attach + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

                        }
                        $("#stock_id_fk").html(attach);
                        $("#edit_stock_id_fk").html(attach);
                        $('#stock_id_fk').selectpicker('refresh');
                        // $("#edit_stock_id_fk").selectpicker('refresh');
                  },
                  complete: function() {
                         
                  }

            }); // submit ajax

  }


  function add_to_cart(id,price, prod_name){

    var total_quantity  = 1;

    var found_product = false;


    $('#add_table tr').each(function() 
      { 

          var p_id        = ($(this).find('input[name="product_id_fk[]"]').val());
          var p_qty       = ($(this).find('input[name="purchase_quantity[]"]').val());

          

          if(p_id == id ){
            total_quantity = +p_qty + +1;  
            $(this).find('input[name="purchase_quantity[]"]').val(total_quantity);        
            found_product = true;  
          }         
      });

      if(found_product == false){

       

        var attach = `<tr>
                      <td>${id}</td>
                      <td>
                        <input type="hidden" id="product_id_fk[]" name="product_id_fk[]" value="${id}">
                        ${prod_name}
                      </td>
                      <td>
                        <input type="number" id="purchase_quantity[]" name="purchase_quantity[]" value="${1}" class="form-control text-center text-black text-size-large">
                      </td>
                      <td>
                        <input type="text" id="sell_price[]" name="sell_price[]" value="${price}" class="form-control text-center text-black text-size-large">
                      </td>
                      <td>
                        <input id="discount[]" name="discount[]" type="text" value="0"  class="form-control text-center text-black text-size-large">
                      </td>
                      <td>
                        <input type="text" id="total_item_cost[]" name="total_item_cost[]" value="${price}" class="form-control text-center text-black text-size-large">
                      </td>
                      <td>
                        <input type="text" id="sell_item_note[]" name="sell_item_note[]" class="form-control text-center text-black text-size-large">
                      </td>
                      <td>
                        <!--<button class="btn btn-link btn-xs clone_row" >
                          <i  class="icon-add text-blue"></i>
                        </button> -->
                        <button class="btn btn-link btn-xs remove_row" >
                          <i  class="icon-subtract text-danger-600"></i>
                        </button>
                      </td>

                  </tr>`;

        $("#add_table").append(attach);

      }

      
      calc_totals();



  }
    
    



  function get_Stock(){

          $.ajax({
                url : 'models/crul_stock.php',
                type : 'POST',
                data : {type:'get',branch_id:BRANCH_ID},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<a  class="filter_btn btn bg-teal-400 btn-labeled legitRipple" href="index.php?p=assets"><span id="stocks_filter_link_0">'+Translation('جميع المخازن')+'</span></a>';
                    var attach1 ='<option value="" selected="selected">'+Translation('تحديد المخزن')+'</option>';
                      for(var i=response.length-1 ; i >= 0;i--){
                        var tp  =response[i][2]
                        
                        attach1 = attach1 + '<option data-subtext="'+tp+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';

                        attach = attach + '<a class="filter_btn btn bg-teal-400 btn-labeled legitRipple"  href="index.php?p=assets&id='+response[i][0]+'"><span id="stocks_filter_link_'+response[i][0]+'">'+response[i][1]+'</span></a>';
                        
                         
                        
                      }
                      $("#stock_filter").html(attach);
                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

  }


  function get_Branch(){

          $.ajax({
                url : 'models/crul_branch.php',
                type : 'POST',
                data : {type:'get',branch_id:BRANCH_ID},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<a class="filter_btn btn bg-orange-400 btn-labeled legitRipple"  href="index.php?p=order"><span id="branch_filter_link_0">'+Translation('جميع الافرع')+'</span></a>';
                    var attach1 ='<option value="" selected="selected">'+Translation('تحديد الفرع')+'</option>';
                    for(var i=response.length-1 ; i >= 0;i--){
                                       
                     
                          attach = attach + '<a class="filter_btn btn bg-orange-400 btn-labeled legitRipple"  href="index.php?p=order&bid='+response[i].branch_id+'"> <span id="branch_filter_link_'+response[i].branch_id+'">'+response[i].branch_name+'</span></a>';  
                          attach1 = attach1 + '<option data-stock-id-fk="'+response[i].stock_id+'" data-subtext=" '+response[i].location+' " value="'+response[i].branch_id+'">'+response[i].branch_name+'</option>';
                          
                    }
                      
                    $("#branch_filter").html(attach);

                    $("#branch_id_fk").html(attach1);

                    $('#branch_id_fk').selectpicker('refresh');

                      
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

  }


  function get_Supplier(){

          $.ajax({
                url : 'models/crul_supplier.php',
                type : 'POST',
                data : {type:'get'},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<a class="filter_btn btn bg-info-400 btn-labeled legitRipple" href="index.php?p=assets"><span id="supplier_filter_link_0">'+Translation('جميع الموردين')+'</span></a>';
                    var attach1 ='<option value="" selected="selected">'+Translation('تحديد المورد')+'</option>';
                    for(var i=response.length-1 ; i >= 0;i--){
                                       
                     
                          attach = attach + '<a class="filter_btn btn bg-info-400 btn-labeled legitRipple" href="index.php?p=assets&sid='+response[i][0]+'"><span id="supplier_filter_link_'+response[i][0]+'">'+response[i][1]+'</span></a>';  
                        
                    }
                      
                    $("#supplier_filter").html(attach);
                      
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

  }


  function get_Category(){

          $.ajax({
                url : 'models/crul_category.php',
                type : 'POST',
                data : {type:'get'},
                dataType : 'json',
                success : function(response) {
                  //console.log(response)
                    var attach ='<a class="filter_btn btn bg-info-400 btn-labeled legitRipple" onclick="get_Products(0)"><span id="supplier_filter_link_0">'+Translation('All Category')+'</span></a>';
                    var attach1 ='<option value="" selected="selected">'+Translation('تحديد المورد')+'</option>';
                    for(var i=response.length-1 ; i >= 0;i--){
                                       
                     
                          attach = attach + '<a class="filter_btn btn bg-success-400 btn-labeled legitRipple" onclick="get_Products('+response[i][0]+')"><span id="supplier_filter_link_'+response[i][0]+'">'+response[i][1]+'</span></a>';  
                        
                    }
                      
                    $("#supplier_filter").html(attach);
                      
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                }

          }); // submit ajax

  }


  function get_Products(cat_id,pid=0){

          $.ajax({
                url : 'models/crul_order.php',
                type : 'POST',
                data : {type:'get_product',
                        bid:BRANCH_ID,
                        id:query_id,
                        cid:query_cid,
                        sid:query_sid,
                        pid:pid,
                        cat_id:cat_id
                      },
                dataType : 'json',
                success : function(response) {
                    var attach ='<br>';
                    var attach1 =``;
                    $("#totals").html(`Total Products : `+response.data.length);
                    
                      for(var i=0 ; i <response.data.length ;i++){

                          if (response.data[i].image_path =='') {
                            response.data[i].image_path = 'assets/images/placeholder.jpg';
                          }

                          attach+=`<div class="col-sm-3 col-xs-4">
                                    <div class="thumbnail">
                                        <div class="thumb thumb-rounded">
                                          <img src="${response.data[i].image_path}" alt="">
                                          <div class="caption-overflow">
                                            <span>
                                              <a href="${response.data[i].image_path}" class="btn bg-success-400 btn-icon btn-xs legitRipple" data-popup="lightbox"><i class="icon-plus2"></i></a>
                                            </span>
                                          </div>
                                        </div>
                                    
                                        <div class="caption text-center">
                                          <h5 class="text-semibold no-margin">
                                            <p class="text-center" style="max-width:300px;text-overflow: ellipsis;white-space: nowrap;">
                                              ${response.data[i].product_name}
                                            </p>
                                            <small class="display-block">Avialabe Quantity : <span class="text-primary text-semibold">${response.data[i].on_hand_quantity}</span></small>
                                            <h4 class="no-margin text-danger-600 text-semibold">$${response.data[i].sell_price}</h4>

                                          </h5>
                                          <a onclick="add_to_cart(${response.data[i].product_id},${response.data[i].sell_price},'${response.data[i].product_name}')" class="btn bg-teal-400 btn-xs "><i class="icon-cart-add position-left"></i> <span class="text-size-small">Add to cart</span></a>
                                        </div>
                                      </div>
                                  </div>`;
                        
                          attach1+= `<li class="media panel panel-body stack-media-on-mobile">
                                      <a href="${response.data[i].image_path}" class="media-left" data-popup="lightbox">
                                        <img src="${response.data[i].image_path}" width="96" alt="">
                                      </a>

                                      <div class="media-body">
                                        <h6 class="media-heading text-semibold">
                                          <a href="">${response.data[i].product_name}</a>
                                        </h6>

                                        

                                        <p class="content-group-sm">Avialabe Quantity : ${response.data[i].on_hand_quantity}</p>

                                        <ul class="list-inline list-inline-separate">
                                          <li>All items from <a href="index.php?p=assets&cid=${response.data[i].category_id}">${response.data[i].category}</a></li>
                                        </ul>
                                      </div>

                                      <div class="media-right text-center">
                                        <h3 class="no-margin text-semibold">$${response.data[i].sell_price}</h3>

                                       


                                        <button type="button" onclick="add_to_cart(${response.data[i].product_id},${response.data[i].sell_price},'${response.data[i].product_name}')" class="btn bg-teal-400 mt-15"><i class="icon-cart-add position-left"></i> Add to cart</button>
                                      </div>
                                    </li>`;


                        
                         
                        
                      }
                      $("#product_list").html(attach);

                      
                },
                complete: function() {
                       //  me.data('requestRunning', false);

                }

          }); // submit ajax

  }


  function calc_totals(prefix=''){
    var total_row   = 0;
    var value_gran  = 0;

    var cart_count = 0;

    $('#purchase_quantity\\[\\]').each(function(index,data) {

        var qty   = $(this).val();
        var price = $('#sell_price\\[\\]').eq(index).val();
        var disc  = $('#discount\\[\\]').eq(index).val();

        total_row = $(this).val() * price - disc;
        total_row = parseFloat(total_row).toFixed(2)

        $('#total_item_cost\\[\\]').eq(index).val(total_row);
      

        value_gran =+value_gran + +total_row;

        cart_count =+cart_count + +qty;

    });

   
    value_gran  = parseFloat(value_gran).toFixed(2)


    $(".cart-count").html(cart_count)
    $("#grand_total").val(value_gran)



  }

  function show_cart(){
    $('#add_form_cont').modal('toggle');
  }

  

$(document).ready(function() {

    get_Products(0);
    get_Category();
    get_Branch();
    get_product_search();

    get_Customer();
    get_Saleman();
    
    // get_Branch();

    $("#main_customer_id_fk").on('change', function(){
      $("#customer_id_fk").val($(this).val());
      $('#customer_id_fk').selectpicker('refresh');

    })

    $("#product_id").on('change', function(){
      var pid = $(this).val();
      get_Products(0,pid)
    })

    $("#add_table").on('click','.remove_row', function(){
      $(this).closest('tr').remove();
      calc_totals();
    })

    $('#add_form').on('change', ':input', function(e) {
      e.preventDefault()

      calc_totals();
    });

  

    $('#add_form').submit(function(event) {
          event.preventDefault();

      

          var fd=new FormData(this);

          var stock_id_fk                 = $("#branch_id_fk option:selected").attr('data-stock-id-fk');


          
          fd.append("type",'create');
          fd.append("stock_id_fk",stock_id_fk);

          $("#submit_add_btn").attr('disabled',true);
          $.ajax({
              url: "models/crul_order.php",
              type:"POST",
              dataType: "JSON",
              data: fd,
              processData: false,
              contentType: false
          
          })
          .done(function(res) {
             
              if(res.is_success == true){

                $("#add_form")[0].reset();

                noty({
                      width: 200,
                      text: Translation(res.data),
                      type: 'success',
                      dismissQueue: true,
                      timeout: 2000,
                      layout: 'topRight',
                      callback: {
                                  onShow: function() {
                                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);

                                  },
                                  afterShow: function() {
                                   // show_report(res.id,'Print');
                                  },
                                  onClose: function() {

                                    location.reload();
                                  },
                                  afterClose: function() {},
                                  onCloseClick: function() {},
                                },
                });

             
              }else{
                  swal({
                      title: Translation("خطأ"),
                      text: Translation(res.data),
                      confirmButtonColor: "#66BB6A",
                      type: "warning"
                  });
              }

              $("#submit_add_btn").attr('disabled',false);
          })
          .fail(function(err) {
              $("#submit_add_btn").attr('disabled',false);

               swal({
                  title: Translation("خطأ"),
                  text: (err),
                  confirmButtonColor: "#66BB6A",
                  type: "error"
              });
              $("#submit_add_btn").attr('disabled',false);
          })
          .always(function() {
              console.log("complete");
              $("#submit_add_btn").attr('disabled',false);

          });
          

    });

      
        

});




$(function() {
//var singleSelect = $('.datatable-column-search-inputs').DataTable();
    
    $('.daterange-single').daterangepicker({ 
        singleDatePicker: true,
        locale: {
            format: 'YYYY-MM-DD'
        }
    });


});



