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;
                              }
                              </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_order.php',
                type : 'POST',
                data : {type:'get_edit_invoice', id : itemid},
                dataType : 'json',
                success : function(response) {
                  
                  resp = response;

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

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


                  

                     

                  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('Product')+`</th>
                                      <th class="multi_lang">`+Translation('Quantity')+`</th>
                                      <th class="multi_lang">`+Translation('Note')+`</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

                     

                   


                      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+`"   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('الكمية')+`"   required="required">

                                          </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>
                
                                 
                                  </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_order.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_order.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_01O.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_02O.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_04O.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_12O.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_15O1.gif" 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++){    

                                         


                          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');">
                                                  
                                                </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');">
                                                  
                                                </td>
                                                <td style="background-image: url('images/ProfessionalDent_21.gif');">
                                                  `+(response.invoice[i].sell_item_notes)+`
                                                </td>
                                                <td>
                                                  <img src="images/spacer.gif" width="1" height="83" 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;">
                                    
                                  </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>
                                  <td colspan="8">
                                    <img src="images/ProfessionalDent_26b.png" width="794" height="73" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="1" height="73" alt=""></td>
                                </tr>
                                <tr>
                                  <td>
                                    <img src="images/spacer.gif" width="123" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="65" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="209" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="72" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="49" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="74" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="90" height="1" alt=""></td>
                                  <td>
                                    <img src="images/spacer.gif" width="112" height="1" alt=""></td>
                                  <td></td>
                                </tr>
                              </table>
                              <!-- End Save for Web Slices -->
                              </body>
                            </center>
                         

                  
                     `+print_attach+`
                    </html>`;

                      

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

          }); // submit ajax


    }
    
    


    


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

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


  
   

    




    function get_Branch(){



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

            }); // submit ajax

    }



    function get_Supplier(){

            $.ajax({
                  url : 'models/crul_supplier.php',
                  type : 'POST',
                  data : {type:'get'},
                  dataType : 'json',
                  success : function(response) {
                    //console.log(response)
                      var attach ='<option value="0" selected="selected">'+Translation('All Suppliers')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          
                          attach = attach + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';
                      
                        }
                        $("#supplier_id_fk").html(attach);
                        $('#supplier_id_fk').selectpicker('refresh');

                        $("#edit_customer_id_fk").html(attach);
                        $('#edit_customer_id_fk').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 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+`"    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('الكمية')+`"  required="required">

                            </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();
    
    }

    
    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_Supplier();
    
    get_Branch();


    // 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')+`"   required="required">
                            </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();
          var row_num1 = this.id.split('_');
          var row_num = row_num1[1];
          $("#item_row_"+row_num).remove();
         
          auto_number();
    });

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

    });

    

   




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

          var cnt                                 = $("#total_rows").val();
          
          var product_id_array                    = [];
          var quantity_array                      = [];
          
          var notes_array                         = [];
           
          var check_products                      = [];
          var check_quantity                      = [];
         
         
          var k=1;

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

              var productID       = $("#product_id_fk_"+i).val();
              var quantityField   = $("#purchase_quantity_"+i).val();
              var notes           = $("#sell_item_note_"+i).val();
              

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

                 

                check_products[k]         = Checks('product_id_fk_'+i);
                check_quantity[k]         = Checks('purchase_quantity_'+i,'No');
               
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
               
                k++;

              }
          }
          
          var customer_id_fk              = $("#supplier_id_fk").val();  
          var author                      = "";
          var invoice_date                = $("#invoice_date").val();
         
          var invoice_note                = $("#invoice_note").val();
          
         
        

          var Check4      = true;

          


          

          var Check1      = Checks('supplier_id_fk');
          var Check2      = true;
          
          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(Check1 && Check2  && Check4 && checkheight && checkwidth && checkcolor && CheckPro && checkQty  && checkprice){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_order.php",
                type:"POST",
                dataType: "JSON",
                

                data : {customer_id_fk            :customer_id_fk,
                        
                        invoice_date              :invoice_date,
                        
                        invoice_note              :invoice_note,
                        

                     

                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        
                        sell_item_note            :notes_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 notes_array                         =[];
         
          var check_products                      =[];
          var check_quantity                      =[];
         


          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 notes           = $("#edit_sell_item_note_"+i).val();
              
              

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

              
                

                check_products[k]         = Checks('edit_product_id_fk_'+i);
                check_quantity[k]         = Checks('edit_purchase_quantity_'+i,'No');
               
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                notes_array[k]            = notes;
               
                k++;
              }
          }


          var customer_id_fk              = $("#edit_customer_id_fk").val();  
          var author                      = "";
          var invoice_date                = $("#edit_invoice_date").val();
           
          var invoice_note                = $("#edit_invoice_note").val();
         
             
        

          var Check4      = true;

          


          

          var Check1      = Checks('edit_customer_id_fk');
          var Check2      = Checks('edit_invoice_date');
          var Check3      = true;
          
          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(Check1 && Check2 && Check3 && Check4 && checkheight && checkwidth && checkcolor && CheckPro && checkQty  && checkprice){
            $("#submit_edit_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_order.php",
                type:"POST",
                dataType: "JSON",
                data : {customer_id_fk            :customer_id_fk,
                        
                        invoice_date              :invoice_date,
                        
                        invoice_note              :invoice_note,
                       
                        invoice_id                :catId,

                      
                        product_id                :product_id_array,
                        quantity                  :quantity_array,
                        sell_item_note            :notes_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_order.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": 6,
              "data": null,
              "render": function (data,type,row) {

                  var btns ='';

                  if(IS_VIEW==0){


                          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 href='#' class='text-danger-400' onclick="delete_items(`+row[0]+`)" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                          <i class='icon-trash'></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[6]+`)"  data-popup='tooltip' data-original-title='`+Translation('عرض جميع وصولات الزبون')+`'>`+data+`</a>`;


               },
               "targets": 3
            },

            
           


           
            
            
            

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

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


});



