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 edit_items(itemid){
          
          $("#edit_objid").val(itemid);
          $("#update_type").val('update');

          var headers           = '';
          var attach            = "";
          var attach_other      = "";
          var footers           = "";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          var total_rows        = 0;
          var resp;
          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'get_edit_invoice', id : itemid},
                dataType : 'json',
                success : function(response) {
                  
                  resp = response;

                 
                  
                 
                 
                  $("#edit_author").val(response.invoice[0].author);
                  $("#edit_customer_id_fk").val(response.invoice[0].customer_id_fk).selectpicker('refresh');
                  $("#edit_invoice_date").val(response.invoice[0].invoice_date);
                  $("#edit_invoice_note").val(response.invoice[0].invoice_note);
                  $("#edit_branch_id_fk").val(response.invoice[0].branch_id_fk);
                  $("#edit_stock_id_fk").val(response.invoice[0].stock_id_fk);
                  $("#edit_saleman_id_fk").val(response.invoice[0].saleman_id_fk);

                  if(response.invoice[0].invoice_status == 4){
                    $("#edit_invoice_type").val(response.invoice[0].invoice_status);

                  }else{
                    $("#edit_invoice_type").val(0);

                  }

                  total_rows = response.invoice.length;                     
                  
                  $("#edit_total_rows").val(total_rows);


                  

                  var discc = '';

                  if(response.invoice[0].discount_type ==1 ){
                    discc = response.invoice[0].discount;
                  }else{
                    discc = response.invoice[0].discount  + "%";
                    
                  }

                  if(parseFloat(response.invoice[0].actual_discount) <= 0 ){
                    discc = '';
                  }
                  
                     

                  attach =  `<div class="form-group">
                              <div class="table-responsive1">
                                <table  class="table col-sm-12 table-bordered .table-sm">
                                  <thead>
                                    <tr class="bg-blue ">
                                      <th>#</th>
                                      <th width="20%" class="multi_lang">`+Translation('المادة')+`</th>
                                      <th class="multi_lang">`+Translation('الكمية')+`</th>
                                      <th class="multi_lang">`+Translation('سعر الوحدة')+`</th>
                                      <th class="multi_lang">`+Translation('تخفيضات')+`</th>
                                      
                                      <th width="12%" class="multi_lang">`+Translation('الكلفة الاجمالية')+`</th>
                                      
                                      <th width="12%" class="multi_lang">`+Translation('ملاحظة')+`</th>
                                      <th></th>
                                    </tr>
                                  </thead>
                                  <tbody id="edit_purchase_item_body" >
                                
                                  `;
                     
                  // show sell item details  

                  var last_i    = 0;
                  var clss_last = '';
                  var area_all  = 0;
                  for(var i=0 ; i < total_rows;i++){

                      if( i == (total_rows -1)){
                        clss_last = 'tab_last';
                      }    
                      // compute total row price

                     

                      if(response.invoice[i].sell_discount_type ==1 ){
                        sell_discc = response.invoice[i].sell_discount;
                      }else{
                        sell_discc = response.invoice[i].sell_discount  + "%";
                      }

                      if(parseFloat(response.invoice[i].sell_actual_discount) <= 0 ){
                        sell_discc = '';
                      }
                  


                      attach = attach + `     
                                        <tr  id="edit_item_row_`+i+`" >
                                          <td  id="edit_num_`+i+`">`+(+i + +1)+`</td>
                                          
                                          <td >
                                           
                                            <select class="form-control multi_lang" name="edit_product_id_fk_`+i+`" id="edit_product_id_fk_`+i+`"   onchange="edit_load_prices(`+i+`);" data-live-search="true" required="required">

                                            </select>

                                          </td>

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

                                          </td>

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

                                          </td>


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

                                         

                                          <td >
                                            <input  value="`+currency_format_display(response.invoice[i].total_row_price)+`" id="edit_total_item_cost_`+i+`" name="edit_total_item_cost_`+i+`" type="text" class="form-control text-center " placeholder="`+Translation('الكلفة الاجمالية')+`"  disabled="disabled" >
                                            
                                          </td>

                                          <td >
                                            <input value="`+response.invoice[i].sell_item_notes+`" id="edit_sell_item_note_`+i+`" name="edit_sell_item_note_`+i+`" type="text" class="form-control multi_lang " placeholder="`+Translation('ملاحظة')+`" >
                                          </td>                                      


                                          <td >
                                            <button class="btn btn-link btn-xs edit_btn_add_item `+clss_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_`+i+`" onclick="remove_rows(`+i+`)">
                                              <i  class="icon-subtract text-danger-600"></i>
                                            </button>
                                            
                                          </td>
                                        </tr>
                                              
                                              `;
                        
                        
                       
                  } // for i



                  footers =`  
                                  </tbody>
                                  <tfoot>
                
                                    <tr class="alpha-teal">
                                      <th colspan="2" class="multi_lang">`+Translation('TOTALS')+`</th>
                                      <!-- <th></th> -->
                                      
                                      
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      <th>

                                        <input id="edit_invoice_total_no_disc" name="edit_invoice_total_no_disc" type="text" value="`+currency_format_display(response.invoice[0].invoice_total_price_actual)+`" class="form-control text-center" readonly style="height: 25px;">
                                      
                                      </th>
                                      
                                      
                                      
                                      <th></th>
                                      <th><i  class="icon-sigma "></i></th>
                                    </tr>

                                    <tr class="alpha-orange">
                                      <th colspan="2" class="multi_lang">`+Translation('DISCOUNT')+`</th>
                                      <!-- <th></th> -->
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      <th >
                                        <input id="edit_discount_total" name="edit_discount_total" type="text" value="`+(discc)+`" class="form-control text-center" data-discount-type="`+(response.invoice[0].discount_type)+`" data-discount-actual="`+(response.invoice[0].actual_discount)+`" style="height: 25px;" onchange1="edit_calc_total_invoice_price();" disabled="disabled">
                                      </th>
                                      
                                      <th></th>
                                      
                                      <th><i  class="icon-minus3 "></i></th>
                                    </tr>

                                    <tr class="alpha-primary">
                                      <th colspan="2" class="multi_lang">`+Translation('GRAND TOTALS')+`</th>
                                      <!-- <th></th> -->
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      <th >
                                        <input id="edit_grand_total" name="edit_grand_total" type="text" value="`+currency_format_display(response.invoice[0].invoice_total_net_balance)+`" class="form-control text-center" readonly style="height: 25px;">
                                      </th>
                                      
                                      <th></th>
                                      
                                      <th><i  class="icon-cash "></i></th>
                                    </tr>
                                    <!--
                                    <tr class="alpha-danger">
                                      <th colspan="2" class="multi_lang">`+Translation('PAYMENT')+`</th>
                                      
                                      <th >
                                        <input id="edit_payment_total" name="edit_payment_total" type="text" value="" data-payment-id-fk="" class="form-control text-center"  style="height: 25px;" onchange="edit_calc_payments();">
                                      </th>
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      
                                      <th></th>
                                      <th></th>
                                      
                                      
                                      <th></th>
                                      
                                      <th><i  class="icon-credit-card "></i></th>
                                    </tr>
                                    -->
                                  </tfoot>
                                </table>
                              </div>

                            </div>`;

                      

                     
                },
                complete: function() {

                      HTML_VIEW_PAY =  headers + customer_details + attach + attach_other + footers;
                     
                      $("#edited_purchase_contain").html(HTML_VIEW_PAY);
                      // $("#inv_numb").val(itm);


                      

                      $('#edit_form_cont').modal('toggle');

                     
                      for(var i=0 ; i < total_rows;i++){ // to load product in select
                       
                        edit_get_products(i,resp.invoice[i].product_id_fk,'edit_product_id_fk_');
                      }

                     
                     
                }

          }); // submit ajax



    }   



    

    function delete_items(itemid) {
        
          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_invoice.php",
                  type:"POST",
                  dataType:"JSON",
                  data: {"type":"delete","obj_id":itemid} ,
                  complete:function(){
                    
                  },
                  beforeSend:function(){
                    
                  },
                  success: function(res) {
                    if(res.is_success == true){
                      // get_Products();
                      swal({
                                  title: "Deleted!",
                                  text: Translation(res.data),
                                  confirmButtonColor: "#66BB6A",
                                  type: "success"
                              });
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    }else{
                      swal({
                                  title: "Cancelled",
                                  text: Translation(res.data),
                                  confirmButtonColor: "#2196F3",
                                  type: "error"
                              });
                    }
                  }
              });
              }
          }); // /confirm
    }


  
    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


    }
    
    


    


    

    function add_payments(itm,cust_id){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'show_invoice_payments_for_add', 
                        id : itm, 
                        cust_id: cust_id
                        },
                dataType : 'json',
                success : function(response) {
                    
                        
                        customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:99%;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                             `+Translation('اسم الزبون')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                             `+Translation('رقم الهاتف')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                             `+Translation('العنوان')+` 
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].customer_address+` </span>
                                              </td>
                                             </tr>
                                            </table>
                                            <br>
                                            `;

                      attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:99%;border-collapse:collapse;border:#000000; '>
                                   <tr style='page-break-inside:avoid;' class="td_head">
                                    <td width=23 style='width:14.4pt;' class="table2_td">
                                    `+Translation('ت')+`
                                    </td>
                                    <td width=68 style='width:50.7pt;' class="table2_td">
                                      <span style="font-size:12px; color:black;">`+Translation('المبلغ الكلي للوصل')+`</span>
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                      <span style="font-size:12px; color:black;">`+Translation('المبلغ المدفوع الكلي')+`</span> 
                                    </td>
                                   
                                    <td width=74 style='width:55.5pt;'  class="table2_td">
                                      <span style="font-size:12px; color:black;">`+Translation('المبلغ المتبقي على الحساب')+`</span>
                                    </td>

                                    <td width=87 style='width:65.25pt;' class="table2_td ">
                                      <span style="font-size:12px; color:black;">`+Translation('الدفعة الجديدة')+`</span> 
                                    </td>
                                    <td width=79 style='width:58.95pt;' class="table2_td">
                                      <span style="font-size:12px; color:black;">`+Translation('الباقي بعد الدفعة الجديدة')+`</span> 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                      <span style="font-size:12px; color:black;">`+Translation('تاريخ الدفعة')+`</span> 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                      <span style="font-size:12px; color:black;">`+Translation('رقم الوصل الورقي')+`</span> 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                      <span style="font-size:12px; color:black;">`+Translation('Saleman')+`</span> 
                                    </td>
                                    <td width=114 style='width:85.5pt;' class="table2_td last_td">
                                      <span style="font-size:12px; color:black;">`+Translation('ملاحظات')+` </span> 
                                    </td>                                    
                                    
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){
                     
  
                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i+1)+` </span>
                                                    </td>

                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  style="font-size:16px;" id="inv_product_`+i+`" > `+currency_format_display(response.invoice[i].invoice_total_net_balance)+` </span>
                                                    </td>

                                                    <td width=64 style='width:48.3pt;'>
                                                      <span style="font-size:16px;"  id="inv_quantity"> `+currency_format_display(response.invoice[i].total_paid)+` </span>
                                                    </td>

                                                    

                                                    <td width=74 style='width:55.5pt;' >
                                                      <input style="font-size:16px;" type="text" id="inv_total_paid_`+i+`" data-total-remain-price="`+response.invoice[i].total_remained+`" name="inv_total_paid_`+i+`" class="form-control text-center" value="`+currency_format_display(response.invoice[i].total_remained)+`" placeholder="المبلغ المدفوع لهذه المادة" readonly >
                                                    </td>

                                                    <td width=87  style='width:65.25pt;'>
                                                      <input style="font-size:16px; background-color: greenyellow;" type="text" id="inv_paid_price_`+i+`" name="inv_paid_price_`+i+`" class="form-control text-center text-danger text-black" placeholder="الدفعة الجديدة" onchange="compute_remain_price(this.value,this.id);" >  
                                                    </td>
                                                    
                                                    <td width=79 style='width:58.95pt;'>
                                                      <input style="font-size:16px;" type="text" id="inv_row_remaind_price_`+i+`" name="inv_row_remaind_price_`+i+`" class="form-control text-center" value="`+currency_format_display(response.invoice[i].total_remained)+`"  placeholder="الباقي" readonly >
                                                    </td>

                                                    <td width=114 style='width:85.5pt;' class="last_td">
                                                      <input type="text" id="pay_date_`+i+`" name="pay_date_`+i+`" class="form-control daterange-single" placeholder="تاريخ الدفعة"  required="required"> 
                                                    </td>

                                                    <td width=114 style='width:85.5pt;' class="last_td">
                                                      <input type="text" id="paper_no_`+i+`" name="paper_no_`+i+`" class="form-control" placeholder="رقم الوصل الورقي"  required="required"> 
                                                    </td>

                                                    <td width=114 style='width:85.5pt;' class="last_td">
                                                      <select id="sale_man_id_`+i+`" name="sale_man_id_`+i+`" class="form-control"  data-live-search="true">
                

                                                      </select>
                                                    </td>

                                                    <td width=114 style='width:85.5pt;' class="last_td">
                                                      <textarea type="text" id="pay_note_`+i+`" name="pay_note_`+i+`" class="form-control" placeholder="ملاحظات" ></textarea> 
                                                    </td>
                                                    
                                                   </tr>
                                                  `;
                        
                        
                       
                      } // for i

                      

                      // total_pay = response.invoice[0].total_paid; // to check if havnt payment show msg not have payment
                      footers =`
                                </table>

                                </div>


                                </body>

                                `+print_attach+`

                                </html>`;

                      

                     
                },
                complete: function() {

                      HTML_VIEW_PAY =  headers + customer_details + attach + attach_other + footers;
                      
                        $("#invoice_pay_add").html(HTML_VIEW_PAY);
                        $("#customer_id_pay").val(cust_id);
                        $("#invoice_id_pay").val(itm);
                        get_Saleman_pay();
                        $('.daterange-single').daterangepicker({ 
                            singleDatePicker: true,
                            locale: {
                                format: 'YYYY-MM-DD'
                            }
                        });

                        $('#add_payments_modal').modal('toggle');
                     
                }

          }); // submit ajax


    }

    function show_payments(itm,printing=null){

          var headers           = '';
          var attach            = "";
          var attach_other      = "";
          var footers           = "";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'show_payments', id : itm},
                dataType : 'json',
                success : function(response) {
                    
                      headers =`

                                    <table  dir=rtl border=1 cellspacing=0 cellpadding=0
                                       style='background:white;border-collapse:collapse;border:none; font-weight:bold;'>
                                       <tr>
                                        <td width=590 colspan=6 style='width:6.15in;border:none;padding:0in 5.4pt 0in 5.4pt'>       
                                          <span style="float: left; font-size: 20px;" id="inv_slogan">`+COMPANY_NAME+`</span>
                                        </td>
                                       </tr>
                                       <tr style='height:9.95pt'>
                                        <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                                        <span id="inv_address"> `+Translation(COMPANY_ADDRESS)+` </span>
                                        </td>
                                        <td width=295 colspan=3 rowspan=2 style='width:221.4pt;' class="table0_td">
                                        <span id="inv_logo">  </span>
                                        </td>
                                       </tr>
                                       
                                       <tr style='height:9.95pt'>
                                        <td width=295 colspan=3 style='width:221.4pt;' class="table0_td">
                                        `+Translation('موبايل')+` : <span dir="ltr" id="inv_phone"> `+COMPANY_PHONE+` </span>
                                        <br>
                                       `+Translation('البريد الالكتروني')+`  : <span dir="ltr" id="inv_email"> `+COMPANY_EMAIL+` </span>
                                        </td>
                                       </tr>
                                       
                                       <tr style='height:9.95pt'>
                                        <td width=118 style='width:88.55pt;' class="table0_td1">
                                       `+Translation('رقم الوصل')+`  :
                                        </td>
                                        <td width=139 style='width:1.45in;' class="table0_td1">
                                        <span id="inv_num" style="color:red;">`+response.invoice[0].invoice_number+`</span>
                                        </td>
                                        <td width=77 colspan=2 style='width:.8in;' class="table0_td1">
                                        
                                        </td>
                                        <td width=116 style='width:87.3pt;' class="table0_td1">
                                       `+Translation('التــــــــــــاريخ')+`  :     
                                        </td>
                                        <td width=140 style='width:104.95pt;' class="table0_td1">
                                        <span id="inv_date">`+response.invoice[0].invoice_date+`</span>
                                        </td>
                                       </tr>
                                       
                                       
                                      </table>
                                      <br>
                                          `;
                        
                      customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:6.2in;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                             `+Translation('اسم الزبون')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                             `+Translation('رقم الهاتف')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                             `+Translation('العنوان')+` 
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].customer_address+` </span>
                                              </td>
                                             </tr>
                                            </table>
                                            <br>
                                            `;

                      attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:443.5pt;border-collapse:collapse;border:#000000; '>
                                   <tr style='page-break-inside:avoid;' class="td_head">
                                    <td width=23 style='width:14.4pt;' class="table2_td">
                                   `+Translation('ت')+` 
                                    </td>
                                    <td width=68 style='width:50.7pt;' class="table2_td">
                                   `+Translation('المادة')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('الكمية')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                   `+Translation('مجموع السعر')+` 
                                    </td>
                                    <td width=114 style='width:85.5pt;' class="table2_td">
                                   `+Translation('المبلغ المدفوع')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td">
                                   `+Translation('تاريخ الدفع')+` 
                                    </td>
                                    <td width=152 style='width:113.85pt;' class="table2_td last_td">
                                   `+Translation('ملاحظات')+` 
                                    </td>
                                    
                                    
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){

                        // compute and format discount
                        var disss = 0;
                        if(response.invoice[i].sell_discount != '0.00'){
                          if(response.invoice[i].sell_discount_type == 0){
                          var disss = response.invoice[i].sell_discount + " %";
                          }else{
                            var disss = currency_format_display(response.invoice[i].sell_discount);
                          }
                        }

                        // compute total row price

                        var total_row_price = 0;

                        if(response.invoice[i].other_id_fk > 0){
                          total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        
                        }else{
                          total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        }



                        if(response.invoice[i].product_id_fk > 0){
  

                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details"> `+currency_format_display(response.invoice[i].paid_amount)+` </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+`  </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <span  id="inv_unit_price"> `+(response.invoice[i].payment_note)+` </span>
                                                    </td>
                                                    
                                                    
                                                   </tr>
                                                  `;
                        
                        }else{ // other product

                          attach_other = attach_other + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(response.invoice.length)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt;'>
                                                      <span  id="inv_details">`+currency_format_display(response.invoice[i].paid_amount)+` </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+` </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <span  id="inv_unit_price"> `+(response.invoice[i].payment_note)+` </span>
                                                    </td>
                                                    
                                                    
                                                   </tr>
                                                  `;

                        }
                       
                      } // for i

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

                      total_pay = response.invoice[0].total_paid; // to check if havnt payment show msg not have payment
                      footers =`
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('التنزيلات')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ الكلي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].invoice_total_price_actual)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المدفوع')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_paid)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المتبقي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_remained)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.3in'>
                                 
                                  <td width=517 colspan=7  style='width:388.0pt;border:none;background:white;
                                    padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                    <span id="inv_note">`+Translation('ملاحظة')+` : `+response.invoice[0].invoice_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=6  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('التوقيع')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

                     
                },
                complete: function() {

                      HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;

                      if(total_pay == null || total_pay ==''){
                        noty({
                            width: 200,
                            text: Translation("هذه الوصل لا يحتوي على اي دفوعات"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',

                          });
                      }else{
                        $("#invoice_show").html(HTML_VIEW_PAY);
                        $("#inv_numb").val(itm);

                        $('#show_payments_modal').modal('toggle');
                      }
                     
                }

          }); // submit ajax


    }


    function edit_payments(itm,printing=null){

          var headers           ='';
          var attach            = "";
          var attach_other      = "";
          var footers           ="";
          var customer_details  = "";
          var print_attach      = "";
          var total_pay         = "";
          $.ajax({
                url : 'models/crul_invoice.php',
                type : 'POST',
                data : {type:'show_payments', id : itm},
                dataType : 'json',
                success : function(response) {
                    console.log(response)
                    
                       
                        customer_details = `

                                            <table  dir=rtl border=1 cellspacing=0 cellpadding=0  width=595 style='width:90%;border-collapse:collapse;border:none'>
                                             <tr style='page-break-inside:avoid;' class="td_head">
                                              <td width=307 style='width:3.2in;' class="table1_td">
                                             `+Translation('اسم الزبون')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td">
                                             `+Translation('رقم الهاتف')+` 
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td last_td">
                                             `+Translation('العنوان')+` 
                                              </td>
                                             </tr>
                                             <tr style='page-break-inside:avoid;' class="td_body">
                                              <td width=307 style='width:3.2in;' class="table1_td1">
                                              <span  id="inv_customer_name"> `+response.invoice[0].customer_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.invoice[0].customer_phone+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.invoice[0].customer_address+` </span>
                                              </td>
                                             </tr>
                                            </table>
                                            <br>
                                            `;

                      attach =  `
                                  <table id="inv_table"  dir=rtl border=1 cellspacing=0 cellpadding=0 width=591 style='width:90%;border-collapse:collapse;border:#000000; '>
                                   <tr style='page-break-inside:avoid;' class="td_head">
                                    <td width=23 style='width:14.4pt;' class="table2_td">
                                   `+Translation('ت')+` 
                                    </td>
                                    <td width=68 style='width:50.7pt;' class="table2_td">
                                   `+Translation('المادة')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td">
                                   `+Translation('الكمية')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td ">
                                   `+Translation('مجموع السعر')+` 
                                    </td>
                                    <td width=114 style='width:85.5pt;' class="table2_td">
                                   `+Translation('المبلغ المدفوع')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td">
                                   `+Translation('تاريخ الدفع')+` 
                                    </td>
                                    <td width=152 style='width:113.85pt;' class="table2_td">
                                   `+Translation('ملاحظات')+` 
                                    </td>
                                    <td width=64 style='width:48.3pt;' class="table2_td last_td">
                                   `+Translation('العمليات')+` 
                                    </td>
                                    
                                    
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.invoice.length;i++){

                        // compute and format discount
                        var disss = 0;
                        if(response.invoice[i].sell_discount != '0.00'){
                          if(response.invoice[i].sell_discount_type == 0){
                          var disss = response.invoice[i].sell_discount + " %";
                          }else{
                            var disss = currency_format_display(response.invoice[i].sell_discount);
                          }
                        }

                        // compute total row price

                        var total_row_price = 0;

                        if(response.invoice[i].other_id_fk > 0){
                          total_row_price = response.invoice[i].sell_item_quantity * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        
                        }else{
                          total_row_price = response.invoice[i].total_length * response.invoice[i].item_sell_price_per_meter - response.invoice[i].actual_discount;
                          total_row_price = currency_format_display(total_row_price);
                        }



                        if(response.invoice[i].product_id_fk > 0){
  

                          attach = attach + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(i)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt; font-family:  Times, serif;'>
                                                      <input type="text" id="edit_inv_paid_price_`+i+`" data-payment-id-fk="`+response.invoice[i].invoice_payment_id+`" data-sell-id-fk="`+response.invoice[i].sell_item_id+`" name="edit_inv_paid_price_`+i+`" class="form-control text-center text-success text-black" placeholder="`+Translation('الدفعة الجديدة')+`" value="`+currency_format_display(response.invoice[i].paid_amount)+`"  >  

                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+`  </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <textarea type="text" id="edit_pay_note_`+i+`" name="edit_pay_note_`+i+`" class="form-control" placeholder="`+Translation('ملاحظات')+`" >`+(response.invoice[i].payment_note)+`</textarea> 

                                                    </td>
                                                    
                                                    <td width=64 style='width:48.3pt;'>
                                                      
                                                      <div class=" " >
                                                       <a id="save_payment_btn_`+i+`" class="btn btn-primary btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="update_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('حفظ')+`">
                                                          <i class="icon-floppy-disk"></i>
                                                       </a>
                                                       <a id="remove_payment_btn_`+i+`" class="btn btn-danger btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="remove_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('حذف الدفعة')+`">
                                                          <i class="icon-x"></i>
                                                       </a>
                                                      </div>
                                                    </td>
                                                    
                                                   </tr>
                                                  `;
                        
                        }else{ // other product

                          attach_other = attach_other + `
                                                  <tr style='page-break-inside:avoid;' class="td_body">
                                                    <td width=23 style='width:14.4pt;'>
                                                      <span  id="inv_count"> `+(response.invoice.length)+` </span>
                                                    </td>
                                                    <td width=68 style='width:50.7pt;'>
                                                      <span  id="inv_product"> `+response.invoice[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.invoice[i].sell_item_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+total_row_price+` </span>
                                                    </td>
                                                    <td width=114 style='width:85.5pt;'>
                                                      <input type="text" id="edit_inv_paid_price_other`+i+`" data-payment-id-fk="`+response.invoice[i].invoice_payment_id+`" data-sell-id-fk="`+response.invoice[i].sell_item_id+`" name="edit_inv_paid_price_other" class="form-control text-center text-success text-black" placeholder="`+Translation('الدفعة الجديدة')+`" value="`+currency_format_display(response.invoice[i].paid_amount)+`"  >  

                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+response.invoice[i].paid_date+` </span>
                                                    </td>
                                                    <td width=152 style='width:113.85pt;'>
                                                      <textarea type="text" id="edit_pay_note_other`+i+`" name="edit_pay_note_other`+i+`" class="form-control" placeholder="`+Translation('ملاحظات')+`" >`+(response.invoice[i].payment_note)+`</textarea> 

                                                    </td>
                                                    
                                                    <td width=64 style='width:48.3pt;'>
                                                      
                                                      <div class=" " >
                                                       <a id="save_payment_btn_other`+i+`" class="btn btn-primary btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="update_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('حفظ')+`">
                                                          <i class="icon-floppy-disk"></i>
                                                       </a>
                                                       <a id="remove_payment_btn_other`+i+`" class="btn btn-danger btn-xs" style="margin-top: 3px; margin-bottom: 3px; padding: 4px 7px;" onclick="remove_payments(this.id)" data-popup="tooltip" data-original-title="`+Translation('حذف دفعة')+`">
                                                          <i class="icon-x"></i>
                                                       </a>
                                                      </div>
                                                    </td>

                                                   </tr>
                                                  `;

                        }
                       
                      } // for i

                     

                      total_pay = response.invoice[0].total_paid; // to check if havnt payment show msg not have payment
                      footers =`
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('التنزيلات')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].total_discount)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ الكلي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.invoice[0].invoice_total_price_actual)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المدفوع')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_paid)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=6 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ المتبقي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                  `+currency_format_display(response.invoice[0].total_remained)+`
                                  </td>
                                 </tr>
                                 <tr style='page-break-inside:avoid;height:.3in'>
                                 
                                  <td width=517 colspan=7  style='width:388.0pt;border:none;background:white;
                                    padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                    <span id="inv_note">`+Translation('ملاحظة')+` : `+response.invoice[0].invoice_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=6  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('التوقيع')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

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

                      HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                      if(total_pay == null || total_pay ==''){
                        noty({
                            width: 200,
                            text: Translation("هذه الوصل لا يحتوي على اي دفوعات"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',

                          });
                      }else{
                        $("#edit_payments_fields").html(HTML_VIEW_PAY);
                        $("#edit_pay_inv_id").val(itm);

                        $('#edit_payments_modal').modal('toggle');
                      }
                     
                        // window.open().document.write(HTML_VIEW);
                }

          }); // submit ajax


    }



  
    function update_payments (id){

        var row_num1        = id.split('_');
        var row_num         = row_num1[3];
        // alert(row_num)
        var inv_id          = $("#edit_pay_inv_id").val();
        var notes           = $("#edit_pay_note_"+row_num).val();
        var paid            = $("#edit_inv_paid_price_"+row_num).val();
        var sell_id_fk      = $("#edit_inv_paid_price_"+row_num).attr("data-sell-id-fk");
        var payment_id      = $("#edit_inv_paid_price_"+row_num).attr("data-payment-id-fk");

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

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

          paid = parseFloat(paid);

        var check1          = true;

        if(paid == '' || paid <= 0 || paid == null || paid == undefined || isNaN(paid)){
            noty({
                    width: 200,
                    text: Translation('الرجاء قم بادخال مبلغ دفعه'),
                    type: 'success',
                    dismissQueue: true,
                    timeout: 2000,
                    layout: 'topRight',
              });
            check1 = false;
        }



        if(check1){
            $("#save_payment_"+row_num).attr('disabled',true);
            $.ajax({
                url: "models/crul_invoice.php",
                type:"POST",
                dataType: "JSON",
                data : {inv_id              :inv_id,
                        paid                :paid,
                        sell_ids            :sell_id_fk,
                        payment_id          :payment_id,
                        notes               :notes,
                        type                :'update_payments'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                   

                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    $('#edit_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');
                }

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

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

        
    }


    function remove_payments (id){

          swal({
              title: Translation("هل انت متأكد؟!"),
              text: Translation("سوف لن تستطيع استرجاع المعلومات المرتبطة بهذا السجل في حالة المسح"),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: Translation("موافق: امسح!"),
              cancelButtonText: Translation("الغاء الامر"),
              closeOnConfirm: true,
              closeOnCancel: true
          },
          function(isConfirm){
              if (isConfirm) {

                        var row_num1        = id.split('_');
                        var row_num         = row_num1[3];

                        var inv_id          = $("#edit_pay_inv_id").val();
                        var notes           = $("#edit_pay_note_"+row_num).val();
                        var paid            = $("#edit_inv_paid_price_"+row_num).val();
                        var sell_id_fk      = $("#edit_inv_paid_price_"+row_num).attr("data-sell-id-fk");
                        var payment_id      = $("#edit_inv_paid_price_"+row_num).attr("data-payment-id-fk");

                        if (paid.indexOf('$') > -1)
                          {
                            
                            var paid = parseFloat(paid.replace('$',''));
                            
                          }

                        var check1          = true;

                        



                        if(check1){
                            $("#remove_payment_btn_"+row_num).attr('disabled',true);
                            $.ajax({
                                url: "models/crul_invoice.php",
                                type:"POST",
                                dataType: "JSON",
                                data : {inv_id              :inv_id,
                                        paid                :paid,
                                        sell_ids            :sell_id_fk,
                                        payment_id          :payment_id,
                                        notes               :notes,
                                        type                :'delete_payments'}
                            })
                            .done(function(res) {
                               
                                  if(res.is_success == true){

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

                                   

                                    $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                                    $('#edit_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');
                                }

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

                            })
                            .always(function() {
                                console.log("complete");
                            });
                        }else{
                            noty({
                                  width: 200,
                                  text: Translation('الرجاء التأكد من القيم المدخلة وايضا يجب ادخال دفعة جديدة على الاقل'),
                                  type: 'success',
                                  dismissQueue: true,
                                  timeout: 3000,
                                  layout: 'topRight',
                            });
                        }
               
              }
          }); // /confirm



        
    }


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

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


    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');
                  },
                  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");


    function invoce_filter_btn_label(){

       if(query_ip =='not' ){
         $("#inv_filter").html(Translation('فلترة الوصولات'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-teal-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==2){
         $("#inv_filter").html(Translation('واصل'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-success-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==3){
         $("#inv_filter").html(Translation('مسترجع'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-purple-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==4){
         $("#inv_filter").html(Translation('عروض'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-violet-400 btn-labeled dropdown-toggle');

       }
       if(query_ip ==1 ){
         $("#inv_filter").html(Translation('واصل جزئيا'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-orange-400 btn-labeled dropdown-toggle');

       }
       

       if(query_ip ==0 ){
         $("#inv_filter").html(Translation('غير واصل'));
         $("#inv_filter_btn").removeClass();
         $("#inv_filter_btn").addClass('btn bg-danger-400 btn-labeled dropdown-toggle');

       }

     }


   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_invoice.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": 10,
              "data": null,
              "render": function (data,type,row) {

                      var today = new Date();
                      var dd = today.getDate();
                      var mm = today.getMonth()+1; //January is 0!
                      var yyyy = today.getFullYear();

                      if(dd.toString().length <2){
                        dd = "0" + dd;
                      }


                      if(mm.toString().length <2){
                        mm = "0" + mm;
                      }

                      today =  yyyy + '-' + mm + '-' + dd;

                      var btns = '';

                      if(IS_VIEW==0){


                          if(PROFILE_TYPE != 2){

                          
                            if(row[2]==today){ // fully editing
                              btns = `<li class='text-primary-600'>
                                          <a  class='text-primary-400' onclick="edit_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                              <i class='icon-pencil7'></i>`+Translation('تعديل')+`
                                          </a>
                                      </li>

                                      `;

                            }else{ // deliveried to customer so they can't change anything
                              btns = ``;
                            }
                          }else{

                             btns = `<li class='text-primary-600'>
                                          <a  class='text-primary-400' onclick="edit_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                              <i class='icon-pencil7'></i>`+Translation('تعديل')+`
                                          </a>
                                      </li>

                                      <li class='text-danger-600'>
                                          <a  class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                              <i class='icon-trash'></i>`+Translation('حذف')+`
                                          </a>
                                      </li>`;

                          }

                          btns = btns + ` <li class='text-primary-600'>
                                                <a   class='text-purple-400' onclick="add_payments(`+row[0]+`,`+row[10]+`)" data-popup='tooltip' data-original-title='`+Translation('اضافة دفعه على حساب الزبون')+`'>
                                                    <i class='icon-cash'></i>`+Translation('تسديد الوصل')+`
                                                </a>
                                            </li>`;

                      }

                     

                      return  `<ul class='icons-list '>
                                         
                                        <li class="dropdown">
                                          <a  class="dropdown-toggle" data-toggle="dropdown"  data-original-title='`+Translation('تفاصيل دفوعات الوصل')+` '>
                                            <i class="icon-menu9"></i>
                                          </a>

                                          <ul class="dropdown-menu dropdown-menu-right">      
                                            
                                            <li class='text-primary-600'>
                                                <a   class='text-orange-400' onclick="show_invoice(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('عرض وصل البيع')+`'>
                                                    <i class='icon-calculator'></i> `+Translation('عرض وصل البيع')+`
                                                </a>
                                            </li>

                                            <li class='text-primary-600'>
                                                <a   class='text-pink-400' onclick="show_invoice(`+row[0]+`,'Print')" data-popup='tooltip' data-original-title='`+Translation('طباعة الوصل')+`'>
                                                    <i class='icon-printer4'></i>`+Translation('طباعة الوصل')+`
                                                </a>
                                            </li>     

                                           
                                            `+btns+`
                                            

                                          </ul>
                                        </li>
                                        
                                    </ul>`;
                        }
          },


            {
               "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[0]+`)"  data-popup='tooltip' data-original-title='`+Translation('عرض الوصل')+`'>`+data+`</a>`;


               },
               "targets": 1
            },

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


                        return  `<a onclick="load_account_statment(`+row[10]+`)"  data-popup='tooltip' data-original-title='`+Translation('عرض جميع وصولات الزبون')+`'>`+data+`</a>`;


               },
               "targets": 3
            },

            
           

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

                    return currency_format_display(data);
                },
                "targets": 4
            },


           
            
            

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


                   if(data ==2 ){
                     status=  `<span class="label bg-green-600 btn-block ">`+Translation('واصل')+`</span>`;
                   }else if(data ==1 ){
                     status=  `<span class="label bg-orange btn-block ">`+Translation('واصل جزئيا')+`</span>`;
                   }else if(data ==0 ){
                     status=  `<span class="label bg-danger btn-block ">`+Translation('غير واصل')+`</span>`;
                   }else if(data ==4 ){
                     status=  `<span class="label bg-violet btn-block ">`+Translation('Offer')+`</span>`;
                   }

                   
                   return  status ;
                },
                "targets": 6
            }
            

           
        ],
        "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 () {
         
        // $("div.datatable-header").append(`<a  style="margin-left:15px;" class="btn bg-info-400"  id="headerBtn" onclick="add_item()"> <i class="icon-file-pdf position-right"></i> Add Category </a>`);   
         

          if(IS_VIEW==0){

            $("div.datatable-header").append(`<a data-toggle="collapse"
                                      style="margin-right:10px;"
                                      data-target="#add-form-cont"
                                      
                                      aria-controls="add-form-cont"
                                      aria-expanded="false"
                                      class="btn btn-primary"
                                      id="add_Item_Btn">
                                        <i class="`+CURRENT_BTN_ICON+`"></i> `+Translation(CURRENT_BTN)+`
                                    </a>`); 
          }else{
              $("#add-form-cont").addClass('collapse');

          }

             $("div.datatable-header").append(`&nbsp;<div class="btn-group">
                          <button id="inv_filter_btn" type="button"
                          class="btn bg-teal-400 btn-labeled dropdown-toggle"
                          data-toggle="dropdown"><b><i class="icon-filter4">
                          </i></b> <span id="inv_filter">`+Translation('فلترة الوصولات')+`</span> <span class="caret"></span></button>
                          <ul class="dropdown-menu dropdown-menu-right">
                          <li><a href="index.php?p=invoice"><i class="icon-close2 text-teal"></i>`+Translation('ازالة الفلتر')+`  </a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice&ip=2"><i class="icon-coins text-success"></i>`+Translation('الواصل')+` </a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice&ip=1"><i class="icon-bell-check text-info"></i>`+Translation('واصل جزئيا')+`  </a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice&ip=0"><i class="icon-alarm-check text-danger"></i>`+Translation('غير واصل')+` </a></li>
                          <li class="divider"></li>
                          <li><a href="index.php?p=invoice&ip=4"><i class=" icon-task text-violet"></i>`+Translation('عروض')+`  </a></li>
                         
                        </ul>
                      </div>`);
 
            invoce_filter_btn_label();

            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'
    });


});



