var table ;

var profile_id = '';

    var HTML_VIEW_PAY = '';
    var print_page =  `
                        <script>
                            setTimeout(function() {
                              window.print()
                            }, 2000)
                        </script>
                        `;
  
    var table_invoice     =`
                            <html>
                              <head>
                              <title>Invoice</title>
                              <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                              </head>
                              <style>
                              #Table_01 {
                              text-align: center;
                              font-weight:600;
                              }
                              .footer11 {
                                  position:fixed;
                                  
                                  bottom:0;
                                  
                              }
                              </style>
                              <body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
                                <center>

                              `;

    




    

    function save_items(itemid) {
        
            var cost_price = $("#"+itemid).val()
        
              $.ajax({
                  url: "models/crul_cost.php",
                  type:"POST",
                  dataType:"JSON",
                  data: {"type":"cost",
                          "cost_price" : cost_price,
                          "id":itemid} ,
                  complete:function(){
                    
                  },
                  beforeSend:function(){
                    
                  },
                  success: function(res) {
                    if(res.is_success == true){
                      // get_Products();
                       noty({
                                    width: 200,
                                    text: Translation(res.data),
                                    type: 'success',
                                    dismissQueue: true,
                                    timeout: 2000,
                                    layout: 'topRight',
                                    callback: {
                                              onShow: function() {},
                                              afterShow: function() {},
                                              onClose: function() {},
                                              afterClose: function() {},
                                              onCloseClick: function() {},
                                            },
                              });
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    }else{
                      swal({
                                  title: "Cancelled",
                                  text: Translation(res.data),
                                  confirmButtonColor: "#2196F3",
                                  type: "error"
                              });
                    }
                  }
              });
              
         
    }


  
    function show_invoice(itm,printing=null,detail_show=null){

          
          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";

          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'show_invoice', id : itm},
                dataType : 'json',
                success : function(response) {
                    // console.log(response)
                    
                      headers =`

                                  <table id="Table_01" width="795" height="796" border="0" cellpadding="0" cellspacing="0">
                                    <tr>
                                      <td colspan="8">
                                        <img src="images/ProfessionalDent_01.gif" width="794" height="159" alt=""></td>
                                      <td>
                                        <img src="images/spacer.gif" width="1" height="159" alt="">
                                      </td>
                                    </tr>
                                    <tr>
                                      <td colspan="2" rowspan="3">
                                        <img src="images/ProfessionalDent_02.gif" width="188" height="106" alt=""></td>
                                      <td colspan="2" rowspan="3" style="background-image: url('images/ProfessionalDent_03.gif'); color:white; text-align: left; padding-left: 10px;">
                                        <span style="font-size:18px;">`+response.invoice[0].customer_full_name+`</span><br>
                                         `+response.invoice[0].customer_phone+`<br>
                                          `+response.invoice[0].customer_address+`
                                      </td>
                                      <td colspan="2" rowspan="3">
                                        <img src="images/ProfessionalDent_04.gif" width="123" height="106" alt=""></td>
                                      <td colspan="2" style="background-image: url('images/ProfessionalDent_05.gif');">
                                        `+response.invoice[0].invoice_number+`
                                      </td>
                                      <td>
                                        <img src="images/spacer.gif" width="1" height="26" alt=""></td>
                                    </tr>

                                    <tr>
                                      <td colspan="2" style="background-image: url('images/ProfessionalDent_06.gif');">
                                         `+response.invoice[0].invoice_date+`
                                      </td>
                                      <td>
                                        <img src="images/spacer.gif" width="1" height="31" alt=""></td>
                                    </tr>

                                    <tr>
                                      <td colspan="2" rowspan="2">
                                        <img src="images/ProfessionalDent_07.gif" width="202" height="50" alt=""></td>
                                      <td>
                                        <img src="images/spacer.gif" width="1" height="49" alt=""></td>
                                    </tr>
                                    <tr>
                                      <td colspan="6" rowspan="2">
                                        <img src="images/ProfessionalDent_08.gif" width="592" height="22" alt=""></td>
                                      <td>
                                        <img src="images/spacer.gif" width="1" height="1" alt=""></td>
                                    </tr>
                                    <tr>
                                      <td colspan="2">
                                        <img src="images/ProfessionalDent_09.gif" width="202" height="21" alt=""></td>
                                      <td>
                                        <img src="images/spacer.gif" width="1" height="21" alt=""></td>
                                    </tr>`;
                        
                        

                      customer_details = ``;

                      if(response.invoice[0].discount > 0.00){
                        var dissc_img = "images/ProfessionalDent_14.gif";

                      }else{
                        var dissc_img = "images/ProfessionalDent_14a.gif";

                      }  


                      attach =  `<tr>
                                  <td>
                                    <img src="images/ProfessionalDent_10.gif" width="123" height="74" alt=""></td>
                                  <td colspan="2">
                                    <img src="images/ProfessionalDent_11.gif" width="274" height="74" alt=""></td>
                                  <td colspan="2">
                                    <img src="images/ProfessionalDent_12.gif" width="121" height="74" alt=""></td>
                                  <td>
                                    <img src="images/ProfessionalDent_13.gif" width="74" height="74" alt=""></td>
                                  <td>
                                    <img src="`+dissc_img+`" width="90" height="74" alt=""></td>
                                  <td>
                                    <img src="images/ProfessionalDent_15.png" width="112" height="74" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="1" height="74" alt=""></td>
                                </tr>
                                `;
                     
                      // show sell item details       

                      

                      for(var i=0 ; i < response.invoice.length;i++){    

                          if(response.invoice[i].discount > 0.00){
                            var dissc = currency_format_display(response.invoice[i].sell_actual_discount);

                          }else{
                            var dissc = "";

                          }                   


                          attach = attach + `
                                              <tr style="">
                                                <td style="background-image: url('images/ProfessionalDent_16.gif'); padding-left: 35px;">
                                                  `+(i+1)+`
                                                </td>
                                                <td colspan="2" style="background-image: url('images/ProfessionalDent_17.gif'); text-align:left;">
                                                   `+response.invoice[i].product_name+`
                                                </td>
                                                <td colspan="2" style="background-image: url('images/ProfessionalDent_18.gif');">
                                                  `+currency_format_display(response.invoice[i].item_sell_price_per_unit)+`
                                                </td>
                                                <td style="background-image: url('images/ProfessionalDent_19.gif');">
                                                 `+response.invoice[i].sell_item_quantity+`
                                                </td>
                                                <td style="background-image: url('images/ProfessionalDent_20.gif');">
                                                  `+dissc+`
                                                </td>
                                                <td style="background-image: url('images/ProfessionalDent_21.gif');">
                                                  `+currency_format_display(response.invoice[i].row_price)+`
                                                </td>
                                                <td>
                                                  <img src="images/spacer.gif" width="1" height="40" alt="">
                                                </td>
                                              </tr> `;
                        
                        
                       
                      } // for i

                      if(printing != null){
                        print_attach = `
                                        <script>
                                            setTimeout(function() {
                                              window.print()
                                            }, 2000)
                                        </script>
                                        `;
                      }else{
                        print_attach = "";
                      }

                      footers =`
                                <tr>
                                  <td colspan="6">
                                    <img src="images/ProfessionalDent_22.gif" width="592" height="84" alt=""></td>
                                  <td colspan="2" style="background-image: url('images/ProfessionalDent_23.gif'); font-size:20px;">
                                    `+currency_format_display(response.invoice[0].invoice_total_price_actual)+`
                                  </td>
                                  <td>
                                    <img src="images/spacer.gif" width="1" height="84" alt=""></td>
                                </tr>

                                <tr>
                                  <td colspan="8">
                                    <img src="images/ProfessionalDent_24.gif" width="794" height="114" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="1" height="114" alt=""></td>
                                </tr>
                                <tr>
                                  <td colspan="8">
                                    <img src="images/ProfessionalDent_25a.png" width="794" height="80" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="1" height="80" alt=""></td>
                                </tr>
                                <tr class="footer">
                                  <td colspan="8">
                                    <img src="images/ProfessionalDent_26b.png" width="794" height="73" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="1" height="73" alt=""></td>
                                </tr>
                                <tr>
                                  <td>
                                    <img src="images/spacer.gif" width="123" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="65" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="209" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="72" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="49" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="74" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="90" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="112" height="1" alt=""></td>
                                  <td></td>
                                </tr>
                              </table>
                              <!-- End Save for Web Slices -->
                              </body>
                            </center>
                         

                  
                     `+print_attach+`
                    </html>`;

                      

                     
                },
                complete: function() {
                       //  me.data('requestRunning', false);
                       HTML_VIEW = table_invoice + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                        window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }
    
    




    $('#print_pay').click(function(e) {
      e.preventDefault();
         print_invoice('Print','pay');
    });

    $('#pdf_pay').click(function(e) {
      e.preventDefault();
         print_invoice('PDF','pay');
    });


   

    




    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');
                  },
                  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_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('اختيار المادة')+'</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

    }



   

$(document).ready(function() {
  
    get_products(1);
    get_Customer();
    get_Saleman();
    
    get_Branch();
    // get_Stock();
   

    
    $("#add_form").on('change', '[id^="product_id_fk_"]',function(e){
          
       var ID   = $(this).attr('id');
       var num  = ID.split('_');
       load_prices(num[3]);

      
    });
    
   



    $('#invoice_transaction').change(function(e) {
      e.preventDefault();
         
         // check if its new or return invoice
         if(this.value == "Return"){
          load_invoices();
          $("#original_invoice_id_fk").attr('required','required');

         }else{
          $("#original_invoice_id_fk").removeAttr('required');
          $("#original_invoice_id_fk").html('');
          $("#original_invoice_id_fk").selectpicker('refresh');

         }

    });


    $('#edit_invoice_transaction').change(function(e) {
       e.preventDefault();
         
       // check if its new or return invoice
       if(this.value == "Return"){
        load_invoices();
        $("#edit_original_invoice_id_fk").attr('required','required');

       }else{
        $("#edit_original_invoice_id_fk").removeAttr('required');
        $("#edit_original_invoice_id_fk").html('');
        $("#edit_original_invoice_id_fk").selectpicker('refresh');

       }

    });

    // to prevent default show modal on page load

   

    // add new row to purchase menu
    $("#purchase_item_body").on('click','.btn_add_item',function(e){
      e.preventDefault();
      var curnt_row_num = $("#total_rows").val();
      var CNT = +curnt_row_num + +1;
      var attach_new_row =`
                          <tr  id="item_row_`+CNT+`" >
                            <td  id="num_`+CNT+`">`+CNT+`</td>
                            
                            
                            <td >
                              <select class="form-control multi_lang stop_enter" name="product_id_fk_`+CNT+`" id="product_id_fk_`+CNT+`" data-width="100%"    data-live-search="true" required="required">

                              </select>
                            </td>
                            
                            <td >
                              <input type="number" value="1" id="purchase_quantity_`+CNT+`" name="purchase_quantity_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('QNTY')+`"  onchange="calc_total_item_cost(this.value,`+CNT+`);" required="required">
                            </td>

                            <td  >
                              <input type="text" id="sell_price_`+CNT+`" name="sell_price_`+CNT+`"  class="form-control text-center multi_lang stop_enter" placeholder="`+Translation('سعر الوحدة')+`" required="required" onchange="calc_total_item_cost(this.value,`+CNT+`);">
                            </td>
                            <td >
                              <input id="discount_`+CNT+`" name="discount_`+CNT+`" type="text" value="" class="form-control text-center text-black text-size-large stop_enter" data-discount-type="" data-discount-actual=""  onchange="calc_total_item_cost(this.value,`+CNT+`);">
                             
                            </td>


                            

                            <td >
                              <input id="total_item_cost_`+CNT+`" name="total_item_cost_`+CNT+`" type="text" class="form-control multi_lang text-center stop_enter" placeholder="`+Translation('الكلفة الاجمالية')+`" disabled="disabled" tabindex="-1">
                         
                            </td>
                            
                           
                        
                            <td >
                              <input type="text" id="sell_item_note_`+CNT+`" name="sell_item_note_`+CNT+`" class="form-control stop_enter" placeholder="`+Translation('ملاحظة')+`" >
                            </td>
                            
                            <td >
                              <button class="btn btn-link btn-xs btn_add_item" >
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button tabindex="-1" class="btn btn-link btn-xs btn_remove_item" id="row_`+CNT+`" >
                                <i  class="icon-subtract text-danger-600"></i>
                              </button>
                              
                            </td>
                          </tr>
                            `;

            $("#purchase_item_body").append(attach_new_row);
            $("#total_rows").val(CNT);
            get_products(CNT);
            auto_number();


    });

    // remove current row 
     $("#purchase_item_body").on('click','.btn_remove_item',function(e){
          e.preventDefault();
          // console.log(this.id);
          var row_num1 = this.id.split('_');
          var row_num = row_num1[1];
          $("#item_row_"+row_num).remove();
          calc_total_invoice_price();
          calc_payments();
          auto_number();
    });

     // to prevent submitting form
    $("#edited_purchase_contain").on('click','.edit_btn_add_item',function(e){
        e.preventDefault();

    });

    

   


    $('#add_payments_form').on('submit', function(e){

          e.preventDefault();

          var cust_id   = $("#customer_id_pay").val();
          var inv_id    = $("#invoice_id_pay").val();
          var pay_date  = $("#pay_date_0").val();
          var sale_man  = $("#sale_man_id_0").val();
          // inv_product_other
          
          var pay_price_array                  =[];
          var pay_notes_array                  =[];
          var paper_no_array                   =[];
          var check_price_array                =[];
          
          var k =0 ;
          $('input[id^="inv_paid_price_"]').each(function() 
          { 
            if(!isNaN(this.value) && this.value.length>0) 
            {
              pay_price_array[k]      = parseFloat(this.value);

              var row_num1            = this.id.split('_');
              var row_num             = row_num1[3]; 
              var notes               = $("#pay_note_"+row_num).val();   
              var paper_no            = $("#paper_no_"+row_num).val();   

              pay_notes_array[k]      = notes;
              paper_no_array[k]       = paper_no;

              check_price_array[k]    = Checks('inv_paid_price_'+row_num,'No',0.0001,null);

              k =k+1;   

            }         
          });
          

          var check_paid  = false;
          var check_ids   = true;

          for(m=0;m<check_price_array.length;m++){

            
            if(check_price_array[m]==true){
              check_paid = true;   // because it accept at least one payment
            }

          }

          if(check_paid && check_ids){
            $("#submit_add_pay_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                data : {cust_id             :cust_id,
                        inv_id              :inv_id,
                        paid_date           :pay_date,
                        sale_man            :sale_man,
                        paper_no            :paper_no_array,
                        row_payments        :pay_price_array,
                        notes               :pay_notes_array,
                        branch_id_fk        :BRANCH_ID,
                        type                :'add_payments'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                   

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

                    // i will reload the page to reset all fields
                    
               
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }

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

            });
          }else{
              noty({
                    width: 200,
                    text: Translation('الرجاء التأكد من القيم المدخلة وايضا يجب ادخال دفعة جديدة على الاقل'),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
          }

          

    });


   




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

          var cnt                                 = $("#total_rows").val();
          
          var product_id_array                    =[];
          var quantity_array                      =[];
          var unit_price_array                    =[];
          var discount_array                      =[];
          var discount_type_array                 =[];
          var actual_discount_array               =[];
          var buy_price_array                     =[];
          var notes_array                         =[];
          var row_price_array                     =[];
          
          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];
          
         
          var k=1;

          for(var i =1; i <= cnt; i++){

              var productID       = $("#product_id_fk_"+i).val();
              var quantityField   = $("#purchase_quantity_"+i).val();
              var unit_price      = $("#sell_price_"+i).val();
              var notes           = $("#sell_item_note_"+i).val();
              var buy_price       = $("#product_id_fk_"+i+" option:selected").attr('data-last-buy-price');

              var row_total_price = $("#total_item_cost_"+i).val();
              var discount        = $("#discount_"+i).val();
              var discount_type   = $("#discount_"+i).attr('data-discount-type');
              var discount_actual = $("#discount_"+i).attr('data-discount-actual');

              

              if(productID != undefined && productID != null && productID != ''){

                row_total_price     = row_total_price.replace('$','');
                row_total_price     = row_total_price.replace(/,/g,'');
                row_total_price     = parseFloat(row_total_price);

                

                check_products[k]         = Checks('product_id_fk_'+i);
                check_quantity[k]         = Checks('purchase_quantity_'+i,'No');
                check_price[k]            = Checks('sell_price_'+i,'No');
               
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                unit_price_array[k]       = unit_price;
                buy_price_array[k]        = buy_price; 

                row_price_array[k]        = row_total_price;
               

                discount_array[k]         = discount;
                discount_type_array[k]    = discount_type;
                actual_discount_array[k]  = discount_actual;

                k++;
              }
          }
          
          var customer_id_fk              = $("#customer_id_fk").val();  
          var author                      = "";
          var invoice_date                = $("#invoice_date").val();
          var branch_id_fk                = $("#branch_id_fk").val();
          // var stock_id_fk                 = $("#stock_id_fk").val();
          var stock_id_fk                 = $("#branch_id_fk option:selected").attr('data-stock-id-fk');

          var invoice_type                = $("#invoice_type").val();
          var invoice_note                = $("#invoice_note").val();
          var saleman_id_fk               = $("#saleman_id_fk").val();

          var invoice_total_no_disc       = $("#invoice_total_no_disc").val();
          var total_invoice               = $("#grand_total").val();
          var total_paid                  = $("#payment_total").val();

          var discount                    = $("#discount_total").val();
          var discount_type               = $("#discount_total").attr('data-discount-type');
          var discount_actual             = $("#discount_total").attr('data-discount-actual');


          total_invoice                   = total_invoice.replace('$','');
          total_invoice                   = total_invoice.replace(/,/g,'');
          total_invoice                   = parseFloat( total_invoice);

          invoice_total_no_disc           = invoice_total_no_disc.replace('$','');
          invoice_total_no_disc           = invoice_total_no_disc.replace(/,/g,'');
          invoice_total_no_disc           = parseFloat( invoice_total_no_disc);
          
          // total_paid                      = total_paid.replace('$','');
          // total_paid                      = total_paid.replace(/,/g,'');
          // total_paid                      = parseFloat( total_paid);
          total_paid                      = "";

          if(isNaN(total_paid) || total_paid =="" || total_paid==null || total_paid==undefined){
            total_paid ="";
          }
          

          var Check4      = true;

          var invoice_transaction     = $('#invoice_transaction').val();
          // var original_invoice_id_fk  = $('#original_invoice_id_fk').val();

          


          

          var Check1      = Checks('customer_id_fk');
          var Check2      = Checks('invoice_date');
          var Check3      = Checks('branch_id_fk');
          
          var CheckPro    = true;
          var checkQty    = true;
          var checkprice  = true;
          var checkheight  = true;
          var checkwidth  = true;
          var checkcolor  = true;

          for(m=1;m<=check_products.length;m++){

            if(check_products[m]==false){
              CheckPro = false;
            }
            if(check_quantity[m]==false){
              checkQty = false;
            }

            if(check_price[m]==false){
              checkprice = false;
            }

            
          }

          


        if(Check1 && Check2 && Check3 && Check4 && checkheight && checkwidth && checkcolor && CheckPro && checkQty  && checkprice){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                

                data : {customer_id_fk            :customer_id_fk,
                        author                    :author,
                        invoice_date              :invoice_date,
                        branch_id_fk              :branch_id_fk,
                        invoice_note              :invoice_note,
                        invoice_type              :invoice_type,
                        invoice_transaction       :invoice_transaction,
                        saleman_id_fk             :saleman_id_fk,
                        stock_id_fk               :stock_id_fk,

                        discount                  :discount,
                        discount_type             :discount_type,
                        discount_actual           :discount_actual,
                        

                        invoice_total_no_disc     :invoice_total_no_disc,
                        total_invoice             :total_invoice,
                        total_paid                :total_paid,

                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        sell_price                :unit_price_array,
                        sell_item_note            :notes_array,
                        buy_price                 :buy_price_array,
                        discount_array            :discount_array,
                        discount_type_array       :discount_type_array,
                        actual_discount_array     :actual_discount_array,
                        row_price                 :row_price_array,
                        type                      :'create'}
            
            })
            .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() {

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

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

                    // i will reload the page to reset all fields
                    
               
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }

                $("#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);

            });
        }else{
          noty({
                    width: 200,
                    text: Translation('الرجاء التأكد من القيم المدخلة '),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
        }

    });




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

          var catId                               = $("#edit_objid").val();

          var cnt                                 = $("#edit_total_rows").val();


  
          
          var product_id_array                    =[];
          var quantity_array                      =[];
          var unit_price_array                    =[];
          var discount_array                      =[];
          var discount_type_array                 =[];
          var actual_discount_array               =[];
          var buy_price_array                     =[];
          var notes_array                         =[];
          var row_price_array                     =[];
          
          var check_products                      =[];
          var check_quantity                      =[];
          var check_price                         =[];



          var k=1;

          for(var i =0; i <= cnt; i++){

              var productID       = $("#edit_product_id_fk_"+i).val();
              var quantityField   = $("#edit_purchase_quantity_"+i).val();
              var unit_price      = $("#edit_sell_price_"+i).val();
              var notes           = $("#edit_sell_item_note_"+i).val();
              var buy_price       = $("#edit_product_id_fk_"+i+" option:selected").attr('data-last-buy-price');

              var row_total_price = $("#edit_total_item_cost_"+i).val();
              var discount        = $("#edit_discount_"+i).val();
              var discount_type   = $("#edit_discount_"+i).attr('data-discount-type');
              var discount_actual = $("#edit_discount_"+i).attr('data-discount-actual');

              

              if(productID != undefined && productID != null && productID != ''){

                row_total_price     = row_total_price.replace('$','');
                row_total_price     = row_total_price.replace(/,/g,'');
                row_total_price     = parseFloat(row_total_price);

                

                check_products[k]         = Checks('edit_product_id_fk_'+i);
                check_quantity[k]         = Checks('edit_purchase_quantity_'+i,'No');
                check_price[k]            = Checks('edit_sell_price_'+i,'No');
               
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
                unit_price_array[k]       = unit_price;
                buy_price_array[k]        = buy_price; 

                row_price_array[k]        = row_total_price;
               

                discount_array[k]         = discount;
                discount_type_array[k]    = discount_type;
                actual_discount_array[k]  = discount_actual;

                k++;
              }
          }


          var customer_id_fk              = $("#edit_customer_id_fk").val();  
          var author                      = "";
          var invoice_date                = $("#edit_invoice_date").val();
          var branch_id_fk                = $("#edit_branch_id_fk").val();
          // var stock_id_fk                 = $("#edit_stock_id_fk").val();
          var stock_id_fk                 = $("#edit_branch_id_fk option:selected").attr('data-stock-id-fk');
          
          var invoice_type                = $("#edit_invoice_type").val();
          var invoice_note                = $("#edit_invoice_note").val();
          var saleman_id_fk               = $("#edit_saleman_id_fk").val();

          var invoice_total_no_disc       = $("#edit_invoice_total_no_disc").val();
          var total_invoice               = $("#edit_grand_total").val();
          var total_paid                  = $("#edit_payment_total").val();

          var discount                    = $("#edit_discount_total").val();
          var discount_type               = $("#edit_discount_total").attr('data-discount-type');
          var discount_actual             = $("#edit_discount_total").attr('data-discount-actual');


          total_invoice                   = total_invoice.replace('$','');
          total_invoice                   = total_invoice.replace(/,/g,'');
          total_invoice                   = parseFloat( total_invoice);

          invoice_total_no_disc           = invoice_total_no_disc.replace('$','');
          invoice_total_no_disc           = invoice_total_no_disc.replace(/,/g,'');
          invoice_total_no_disc           = parseFloat( invoice_total_no_disc);
          
          // total_paid                      = total_paid.replace('$','');
          // total_paid                      = total_paid.replace(/,/g,'');
          // total_paid                      = parseFloat( total_paid);

          if(isNaN(total_paid) || total_paid =="" || total_paid==null || total_paid==undefined){
            total_paid ="";
          }
          

          var Check4      = true;

          var invoice_transaction     = $('#edit_invoice_transaction').val();
          // var original_invoice_id_fk  = $('#original_invoice_id_fk').val();

          


          

          var Check1      = Checks('edit_customer_id_fk');
          var Check2      = Checks('edit_invoice_date');
          var Check3      = Checks('edit_branch_id_fk');
          
          var CheckPro    = true;
          var checkQty    = true;
          var checkprice  = true;
          var checkheight  = true;
          var checkwidth  = true;
          var checkcolor  = true;



          for(m=1;m<=check_products.length;m++){

            if(check_products[m]==false){
              CheckPro = false;
            }
            if(check_quantity[m]==false){
              checkQty = false;
            }

            if(check_price[m]==false){
              checkprice = false;
            }

            
          }


         


          if(Check1 && Check2 && Check3 && Check4 && checkheight && checkwidth && checkcolor && CheckPro && checkQty  && checkprice){
            $("#submit_edit_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                data : {customer_id_fk            :customer_id_fk,
                        author                    :author,
                        invoice_date              :invoice_date,
                        branch_id_fk              :branch_id_fk,
                        invoice_note              :invoice_note,
                        invoice_type              :invoice_type,
                        invoice_transaction       :invoice_transaction,
                        saleman_id_fk             :saleman_id_fk,
                        stock_id_fk               :stock_id_fk,
                        invoice_id                :catId,

                        discount                  :discount,
                        discount_type             :discount_type,
                        discount_actual           :discount_actual,
                        

                        invoice_total_no_disc     :invoice_total_no_disc,
                        total_invoice             :total_invoice,
                        total_paid                :total_paid,

                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        sell_price                :unit_price_array,
                        sell_item_note            :notes_array,
                        buy_price                 :buy_price_array,
                        discount_array            :discount_array,
                        discount_type_array       :discount_type_array,
                        actual_discount_array     :actual_discount_array,
                        row_price                 :row_price_array,
                        type                      :'update'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                    

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

                    // i will reload the page to reset all fields
                    
               
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }

                $("#submit_edit_btn").attr('disabled',false);
            })
            .fail(function(err) {
                 swal({
                    title: Translation("خطأ"),
                    text: (err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                $("#submit_edit_btn").attr('disabled',false);
            })
            .always(function() {
                console.log("complete");
            });
        }else{
          noty({
                    width: 200,
                    text: Translation('الرجاء التأكد من القيم المدخلة '),
                    type: 'error',
                    dismissQueue: true,
                    timeout: 3000,
                    layout: 'topRight',
              });
        }

         
    });


   
    


});







$(function() {

 
    
  $(".touchspin-basic").TouchSpin({
        min: 1,
        max: 10000000,
        step: 1,
        buttondown_class: "btn btn-xs",
        buttonup_class: "btn btn-xs"
    });

  var start_date = moment().add(5, 'days');

  $('.daterange-single').daterangepicker({ 
        singleDatePicker: true,
        locale: {
            format: 'YYYY-MM-DD'
        }
    });

  $("#delivery_time").daterangepicker({ 
        singleDatePicker: true,
        startDate: start_date,
        locale: {
            format: 'YYYY-MM-DD'
        }
    });

  // Mini
    $('.select-size-xs').select2({
        containerCssClass: 'select-xs'
    });


   // Setting datatable defaults
    $.extend( $.fn.dataTable.defaults, {
        autoWidth: false,
        columnDefs: [{ 
            orderable: false,
            width: '100px',
            targets: [ 5 ]
        }],
        dom: '<"datatable-header"fBl><"datatable-scroll"t><"datatable-footer"ip>',
        language: {
            search: '<span>'+Translation('بحث')+':</span> _INPUT_',
            searchPlaceholder: Translation('بحث عن')+'...',
            lengthMenu: '<span>'+Translation('عرض')+':</span> _MENU_',
            paginate: { 'first': 'First', 'last': 'Last', 'next': '&'+Left_Arraw+'arr;', 'previous': '&'+Right_Arraw+'arr;' }
            
        },
        drawCallback: function () {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');
        },
        preDrawCallback: function() {
            $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');
        }
    });


    

    // Individual column searching with text inputs
    $('.datatable-column-search-inputs tfoot td').not(':last-child').each(function () {
        var title = $('.datatable-column-search-inputs thead th').eq($(this).index()).text();
        $(this).html('<input type="text" class="form-control input-sm" placeholder="'+Translation('بحث عن')+' '+title+'" />');
    });
    
    

   var query_ip = getQueryVariable("ip");




   var table = $('.datatable-column-search-inputs').DataTable({
        
        // keys: {
        //     className: 'focus focus-success'
        // },
        buttons: {            
            buttons: [
                {
                    extend: 'copyHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: [ 0, ':visible' ]
                    }
                },
                {
                    extend: 'excelHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'pdfHtml5',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'print',
                    className: 'btn btn-default',
                    exportOptions: {
                        columns: ':visible'
                    }
                },
                {
                    extend: 'colvis',
                    text: '<i class="icon-three-bars"></i> <span class="caret"></span>',
                    className: 'btn bg-blue btn-icon'
                }
                
            ]
        },
        lengthMenu: [
            [  10, 25, 50, 100 ],
            [  '10', '25', '50', '100' ]
        ],
        "processing": true,
        "serverSide": true,
        "ajax": {
        "url" : "models/crul_cost_return.php",
        "data": function(d){
          d.type = "load";
          if(query_ip !='not'){
            d.ip =query_ip ;
          }



          d.branch_id=BRANCH_ID;
        }
        },
        drawCallback: function() {
                  $('[data-popup=tooltip]').tooltip();
                  $('[data-popup=popover-custom]').popover({
                    template: '<div class="popover  border-teal-400"><div class="arrow"></div><h3 class="popover-title bg-teal-400"></h3><div class="popover-content"></div></div>'
                  });

            },
        "columnDefs": [
          {
              "targets": 11,
              "data": null,
              "render": function (data,type,row) {

                     if(IS_VIEW==0){


                            return  `<ul class='icons-list text-center'>
                                        
                                       

                                        <li class='text-primary-600'>
                                            <a  class='text-danger-400' onclick="save_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('Update Cost Price')+`'>
                                                <i class='icon-floppy-disk icon-2x'></i>
                                            </a>
                                        </li>

                                        

                                    </ul>`;
                    }else{
                      return '';
                    }

              }
          },


            {
               "render": function(data, type, row){


                        // return  `<a onclick="show_invoice(`+row[0]+`)"  data-popup='tooltip' data-original-title='Show Invoice Details'>`+data+`</a>`;
                        return  `<a onclick="show_invoice(`+row[11]+`)"  data-popup='tooltip' data-original-title='`+Translation('عرض الوصل')+`'>`+data+`</a>`;


               },
               "targets": 1
            },

            

            

           
            
            

            {
                "render": function(data, type, row){
                   


                   if(data =='Invoice' ){
                     status=  `<span class="label bg-green-600 btn-block ">Invoice</span>`;
                   }else{
                     status=  `<span class="label bg-warning-600 btn-block ">`+Translation('Return')+`</span>`;
                   }

                   
                   return  status ;
                },
                "targets": 3
            },

            {
                "render": function(data, type, row){
                   
                   return  `<input type='number' id='${row[0]}' name='${row[0]}' value='${data}' style='width:100px; background-color:yellow'>` ;
                },
                "targets": 7
            }
            

           
        ],
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {


            if(   aData[5] == 1 ){ // outcome type
                $(nRow).children().each(function (index, td) {
                    $(this).addClass('alpha-info');
                });
            }
        },
        "order": [[0,'desc']],
        "displayLength": 25,
      
        initComplete: function () {
         
         

          
              $("#add-form-cont").addClass('collapse');

          
 
          

            this.api().columns().every( function() {
                var column = this;
                

            });
            escape_notes();
        }
    });

    
    table.columns().every( function () {
        var that = this;
        $('input', this.footer()).on('keyup change', function () {
            that.search(this.value).draw();
        });
    });


    // high light row and column
    var lastIdx = null;
     
    $('.datatable-highlight tbody').on('mouseover', 'td', function() {
        var chk_inx =table.cell(this).index();
        if(chk_inx != undefined && chk_inx !=null && chk_inx !='' ){ // because child row
          var colIdx = table.cell(this).index().column;

          if (colIdx !== lastIdx) {
              $(table.cells().nodes()).removeClass('active');
              $(table.column(colIdx).nodes()).addClass('active');
          }
        }
        
    }).on('mouseleave', function() {
        $(table.cells().nodes()).removeClass('active');
    });

    // end highlight row and column

    // Single row selection
    
    $('.datatable-column-search-inputs tbody').on('click', 'tr', function() {
        if ($(this).hasClass('success')) {
            $(this).removeClass('success');
        }
        else {
            table.$('tr.success').removeClass('success');
            $(this).addClass('success');
        }
    });


         // change filter to top
    $('.datatable-column-search-inputs tfoot tr').insertAfter($('.datatable-column-search-inputs thead tr'))


    $('.dataTables_length select').select2({
        minimumResultsForSearch: Infinity,
        width: 'auto'
    });


});



