var table 
    
    var HTML_VIEW_PAY = '';
    var print_page =  `
                        <script>
                          window.print();
                          window.onload = function() { window.print(); }
                        </script>
                        `;
    var HTML_Table = `
                      <!DOCTYPE html>
                      <html lang="ar" dir="rtl">
                      <head>
                        <meta charset="utf-8">
                        <meta http-equiv="X-UA-Compatible" content="IE=edge">
                        <style>

                          .print {  
                            -webkit-print-color-adjust: exact;
                          }
                          
                          .table0_td {
                            
                            border:none;
                            padding:0in 0pt 0in 0pt;
                            height:9.95pt
                            
                          }
                          
                          .table0_td1 {
                            
                            border:none;
                            border-bottom:solid #984806 1.0pt;
                            padding:0in 0pt 0in 0pt;
                            height:9.95pt
                            
                          }
                          
                          
                          
                          .table1_td {
                            
                            border:solid #20295b  1.0pt;
                            border-left-color: white;
                            background:#067db1;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in
                            
                          }
                          
                          .last_td {
                            border-left-color: #984806 !important;
                          }
                          
                          .table1_td1 {
                            
                            border:solid #984806 1.0pt;
                            border-top:none;
                            background:white;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in
                            
                          }
                          
                          .table2_td {
                            
                            border:solid #20295b  1.0pt;
                            border-left-color: white;
                            background:#067db1;
                            padding:0pt 0pt 0pt 0pt;
                            height:.1in;
                            
                          }
                          
                          .td_head {
                            text-align: center;
                            
                            color : white;
                            height: .3in;
                          }
                          
                          .td_body {
                            text-align: center;
                            
                            color : black;
                            height: .2in;
                            border:solid #984806 1.0pt;
                          }
                          
                          #inv_table tr:nth-child(odd) {
                            background-color: #d9ebf9;
                          }
                          
                          @font-face {
                            font-family: "Noto Kufi Arabic";
                            src: url(assets/custom_font/NotoKufiArabic-Regular.ttf) format("truetype");
                            }
                          
                          .badge {
                            display: inline-block;
                            min-width: 10px;
                            padding: 3px 7px;
                            font-size: 12px;
                            font-weight: 500;
                            color: #fff;
                            line-height: 1.5384616;
                            vertical-align: middle;
                            white-space: nowrap;
                            text-align: center;
                            
                            border-radius: 10px;
                          } 
                          
                          .badge {
                            padding: 1px 1px 1px 1px;
                            font-size: 10px;
                            letter-spacing: 0px;
                            vertical-align: baseline;
                            
                          }
                          
                          .bg-pink-400 {
                            background-color: #EC407A;
                            border-color: #EC407A;
                            color: #fff;
                          }
                          
                          .col-sm-4 {
                            width: 33.33333333%;
                          }

                          .col-sm-6 {
                            width: 40%;
                          }
                          
                          .col-sm-3 {
                            width: 25%;
                          }

                        </style>

                      </head>

                      <body class="print" style=" font-family: 'Noto Kufi Arabic', Times, serif;">
                        <div align=center>
                      `;

    

    function edit_items(itemid){
          
          $("#edit_objid").val(itemid);

          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_purchase.php',
                type : 'POST',
                data : {type:'get_edit_purchase', id : itemid},
                dataType : 'json',
                success : function(response) {
                  
                  resp = response;
                  $("#edit_purchase_number").val(response.purchase[0].purchase_number);
                  $("#edit_purchase_date").val(response.purchase[0].purchase_date);
                  $("#edit_stock_id_fk").val(response.purchase[0].stock_id_fk).selectpicker('refresh');
                  $("#edit_branch_id_fk").val(response.purchase[0].branch_id_fk).selectpicker('refresh');
                  $("#edit_supplier_id_fk").val(response.purchase[0].supplier_id_fk).selectpicker('refresh');
                  $("#edit_purchase_note").val(response.purchase[0].purchase_note);

                  total_rows = response.purchase.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 class="multi_lang">`+Translation('المادة')+`</th>
                                      <th class="multi_lang">`+Translation('الكمية')+`</th>
                                      <th class="multi_lang">`+Translation('Barcode')+`</th>
                                      <th class="multi_lang">`+Translation('تاريخ النفاذ')+`</th>
                                      <th class="multi_lang">`+Translation('سعر الشراء')+`</th>
                                      <th class="multi_lang">`+Translation('الكلفة بعد المصاريف')+`</th>
                                      
                                     
                                      <th class="multi_lang">`+Translation('سعر البيع')+`</th>
                                      <th class="multi_lang">`+Translation('الكلفة الاجمالية')+`</th>
                                      <th class="multi_lang">`+Translation('ملاحظات')+`</th>
                                      <th></th>
                                    </tr>
                                  </thead>
                                  <tbody id="edit_purchase_item_body" >
                                
                                  `;
                     
                  // show sell item details  
                  for(var i=0 ; i < total_rows;i++){

                        
                      // compute total row price

                      var total_row_price = 0;

                      var total_area    = '';
                      var itm_wdth      = '';
                      var readonly_attr = 'readonly';
                      

                      attach = attach + `     
                                        <tr  id="edit_item_row_`+i+`" >
                                          <td width="5%" id="edit_num_`+i+`">`+i+`</td>
                                          <td width="12%">
                                           
                                            <select  class="form-control multi_lang" name="edit_product_id_fk_`+i+`" id="edit_product_id_fk_`+i+`" data-width="100%"   data-live-search="true">

                                            </select>

                                          </td>
                                          <td width="8%">
                                            <input type="number" id="edit_purchase_quantity_`+i+`" value="`+response.purchase[i].purchase_quantity+`" name="edit_purchase_quantity_`+i+`"  class="form-control" placeholder="`+Translation('الكمية')+`"  onchange="edit_calc_total_item_cost(`+i+`);">
                                          </td>

                                          <td width="8%">
                                            <input type="text" id="edit_purchase_barcode_`+i+`" value="`+response.purchase[i].barcode+`" name="edit_purchase_barcode_`+i+`"  class="form-control" placeholder="`+Translation('Barcode')+`"  >
                                          </td>

                                          <td width="10%" >
                                            <input id="edit_purchase_expire_`+i+`" name="edit_purchase_expire_`+i+`" type="text" class="form-control daterange-single text-center" value="`+response.purchase[i].expire_date+`" placeholder="`+Translation('تاريخ النفاذ')+`" >
                                          </td>
                                          
                                          <td width="8%">
                                            <input id="edit_cost_`+i+`" value="`+response.purchase[i].cost_price+`" name="edit_cost_`+i+`" type="text" class="form-control" placeholder="`+Translation('سعر شراء ')+`" onchange="edit_calc_total_item_cost(`+i+`);" >
                                          </td>
                                          <td width="8%">
                                            <input id="edit_cost_expenses_`+i+`" name="edit_cost_expenses_`+i+`" value="`+response.purchase[i].cost_expenses+`"  type="text" class="form-control" placeholder="`+Translation('السعربعد التكلفة')+`" readonly="readonly" >
                                          </td>
                                          <td width="8%">
                                            <input id="edit_sell_price_`+i+`" name="edit_sell_price_`+i+`" value="`+response.purchase[i].sell_price+`"  type="text" class="form-control" placeholder="`+Translation('سعر البيع')+`" >
                                          </td>
                                          <td width="9%" id="edit_total_item_cost_`+i+`">`+currency_format_display(response.purchase[i].total_row_price)+`</td>
                                          <td width="10%">
                                            <textarea type="text" id="edit_purchase_item_note_`+i+`" name="edit_purchase_item_note_`+i+`" class="form-control" placeholder="`+Translation('ملاحظات')+`" >`+(response.purchase[i].purchase_item_note)+`</textarea>
                                          </td>
                                          <td width="6%">
                                            <button class="btn btn-link btn-xs btn_add_item" onclick="Add_Rows('edit_')">
                                              <i  class="icon-add text-blue"></i>
                                            </button>
                                            <button class="btn btn-link btn-xs btn_remove_item" id="edit_row_`+i+`" >
                                              <i  class="icon-subtract text-danger-600"></i>
                                            </button>
                                            
                                          </td>
                                        </tr>
                                              
                                              `;
                        
                        
                       
                  } // for i



                  footers =`  
                                  </tbody>
                                  <tfoot>
                                    <tr class="bg-teal-400">
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      <th></th>
                                      
                                      <th>
                
                                        <input type="text" id="edit_total_expenses" name="edit_total_expenses"  class="form-control text-center stop_enter" value="`+(response.purchase[0].total_expenses)+`" placeholder="`+Translation('المصاريف')+`" onchange="edit_calc_cost_expenses();">
                                      </th>
                                      <th></th>
                                      <th id="edit_purchase_total">`+currency_format_display(response.purchase[0].total_price)+`</th>
                                      <th></th>
                                      <th></th>
                                    </tr>
                                  </tfoot>
                                </table>
                              </div>

                            </div>`;

                      

                     
                },
                complete: function() {

                      HTML_VIEW_PAY = HTML_Table + 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.purchase[i].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_purchase.php",
                  type:"POST",
                  data: {"type":"delete","obj_id":itemid} ,
                  dataType : "JSON",
                  complete:function(){
                    //hideLoader();
                  },
                  beforeSend:function(){
                    //showLoader("Deleting Purchase");
              },
                  success: function(res) {
                    if(res.is_success == true){
                      
                      swal({
                                  title: Translation("تم الحذف"),
                                  text: Translation(res.data),
                                  confirmButtonColor: "#66BB6A",
                                  type: "success"
                              });
                      $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                    }else{
                      swal({
                                  title: Translation("خطأ"),
                                  text: Translation(res.data),
                                  confirmButtonColor: "#2196F3",
                                  type: "error"
                              });
                    }
                  }
              });
              }
          }); // /confirm
    }



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

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

                                            <table class="purchase_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">
                                             `+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.purchase[0].purchase_auto_number+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_phone"> `+response.purchase[0].purchase_date+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_supplier"> `+response.purchase[0].supplier_full_name+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.purchase[0].purchase_number+` </span>
                                              </td>
                                             </tr>
                                            </table>
                                            <br>
                                            `;

                      attach =  `
                                  <table class="purchase_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:73.5pt;'  class="table2_td ">
                                   `+Translation('Barcode')+` 
                                    </td>
                                    <td width=74 style='width:200.5pt;' class="table2_td ">
                                   `+Translation('تاريخ النفاذ')+` 
                                    </td>
                                    <td width=74 style='width:55.5pt;' class="table2_td">
                                   `+Translation('سعر شراء الوحدة')+` 
                                    </td>
                                     <td width=74 style='width:55.5pt;' class="table2_td">
                                   `+Translation('الكلفة بعد المصاريف')+` 
                                    </td>
                                     <td width=74 style='width:55.5pt;' class="table2_td">
                                   `+Translation('سعر البيع')+` 
                                    </td>
                                    <td width=87 style='width:65.25pt;' class="table2_td">
                                   `+Translation('الكلفة الاجمالية')+` 
                                    </td>
                                    <td width=152 style='width:70.85pt;' class="table2_td last_td">
                                   `+Translation('ملاحظات')+` 
                                    </td>
                                    
                                    
                                   </tr>`;
                     
                      // show sell item details                       
                      for(var i=0 ; i < response.purchase.length;i++){

                        // compute and format discount
                        var disss = 0;
                        

                        // compute total row price

                        var total_row_price = 0;

                       
                        total_row_price = response.purchase[i].purchase_quantity * response.purchase[i].cost_expenses ;
                        total_row_price = currency_format_display(total_row_price);
                        
                        var Det = '';


                        var total_area    = '';
                        
                        


                        

                         
                        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  id="inv_product"> `+response.purchase[i].product_name+` </span>
                                                    </td>
                                                    <td width=64 style='width:48.3pt;'>
                                                      <span  id="inv_quantity"> `+response.purchase[i].purchase_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:65.5pt; font-family: Times, serif;' >
                                                      <span  id="inv_total_row"> `+response.purchase[i].barcode+` </span>
                                                    </td>
                                                    <td align="left" width=74 style='width:95.5pt; text-align:left !important;' >
                                                      <span  id="inv_total_row"> `+response.purchase[i].expire_date+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details"> `+currency_format_display(response.purchase[i].cost_price)+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details"> `+currency_format_display(response.purchase[i].cost_expenses)+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details"> `+currency_format_display(response.purchase[i].sell_price)+` </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+(total_row_price)+`  </span>
                                                    </td>
                                                    <td width=152 style='width:103.85pt;' class="last_td">
                                                      <span  id="inv_unit_price"> `+(response.purchase[i].purchase_item_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=8 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; text-align: right !important;'>
                                 `+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.purchase[0].total_expenses)+`
                                  </td>

                                  
                                 </tr>

                                 <tr style='page-break-inside:avoid;height:.1in'>
                                  <td width=517 colspan=8 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; text-align: right !important;'>
                                 `+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.purchase[0].total_price)+`
                                  </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; text-align: right !important;'>
                                    <span id="inv_note">`+Translation('ملاحظة')+` : `+response.purchase[0].purchase_note+` </span>
                                  </td>
                                 </tr>
                                 
                                 <tr style='page-break-inside:avoid;height:.1in; background-color: white'>
                                  <td width=517 colspan=9  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; text-align: left !important;'>
                                 `+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);
                      
                        $("#invoice_show").html(HTML_VIEW_PAY);
                        $("#inv_numb").val(itm);

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

          }); // submit ajax


    }

    

    function show_files(itemid) {

             

      var attach =  `
                      <div class="col-lg-3 col-sm-6">
                        <div class="thumbnail">
                          <div class="thumb">
                            <img src="`+itemid+`" alt="">
                            <div class="caption-overflow">
                              <span>
                                <a href="`+itemid+`" target="_blank" data-popup="lightbox" class="btn border-white text-white btn-flat btn-icon btn-rounded"><i class="icon-plus3"></i></a>
                                
                              </span>
                            </div>
                          </div>

                          <div class="caption">
                            <h6 class="no-margin"><a href="#" class="text-default">File No : `+1+`</a> <a href="#" class="text-muted"><i class="icon-three-bars pull-right"></i></a></h6>
                          </div>
                        </div>
                      </div>` ;


                    
                    $("#file_attach").html(attach);
                    $('#show_files').modal('toggle');
                



    }




    


    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+'" data-branch-id-fk="'+response[i][3]+'" value="'+response[i][0]+'">'+response[i][1]+'</option>';
                          aaa = aaa + '<option  value="'+response[i][0]+'">'+response[i][1]+'</option>';

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

            }); // submit ajax

    }

    function 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="" selected="selected">'+Translation('تحديد المورد')+'</option>';
                      var aaa='';
                        for(var i=response.length-1 ; i >= 0;i--){
                          var tp =response[i][2];
                          
                          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>';

                        }
                        $("#supplier_id_fk").html(attach);
                        $("#edit_supplier_id_fk").html(attach);
                        $('#supplier_id_fk').selectpicker('refresh');
                        $("#edit_supplier_id_fk").selectpicker('refresh');
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

    }

    // make products as searchable list

    function get_products(row_num){
          
          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get'},
                  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--){
                          
                          var tp =response[i][2];
                          var bc =response[i][3];
                          var tpo =response[i][4];
                          attach = attach + '<option data-sell-price="'+response[i][5]+'"  value="'+response[i][0]+'" >'+response[i][1]+'</option>';
                        }
                        $("#product_id_fk_"+row_num).html(attach);
                        $('#product_id_fk_'+row_num).selectpicker('refresh');

                        $("#edit_product_id_fk_"+row_num).html(attach);
                        // $("#edit_stock_id_fk").selectpicker('refresh');
                  },
                  complete: function() {
                         //  me.data('requestRunning', false);
                  }

            }); // submit ajax

          

         

    }


    function edit_get_products(row_num,selc=null){
         
          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get'},
                  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--){
                          
                          var tp =response[i][2];
                          var bc =response[i][3];
                          var tpo =response[i][4];
                          attach = attach + '<option  data-sell-price="'+response[i][5]+'"  value="'+response[i][0]+'" >'+response[i][1]+'</option>';
                          // attach = attach + '<option  data-subtext="'+Translation('الرمز : ')+tp+' || '+Translation('الباركود : ')+bc+'  || '+Translation('النوع : ')+tpo+'" value="'+response[i][0]+'" data-forgin-code="'+response[i][2]+'" data-type="'+response[i][4]+'">'+response[i][1]+'</option>';
                        }
                        $("#edit_product_id_fk_"+row_num).html(attach);
                        $('#edit_product_id_fk_'+row_num).selectpicker('refresh');

                        if(selc !=null){
                          $('#edit_product_id_fk_'+row_num).val(selc).selectpicker('refresh');
                        }

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

            }); // submit ajax

          

         

    }



    function get_Category(){

      $.ajax({
                      url : 'models/crul_category.php',
                      type : 'POST',
                      data : {type:'get'},
                      dataType : 'json',
                      success : function(response) {
                        console.log(response)
                          var attach ='<option value="" selected="selected">'+Translation('اسم الصنف')+'</option>';
                          
                            for(var i=response.length-1 ; i >= 0;i--){
                              
                              attach = attach + '<option value="'+response[i][0]+'">'+response[i][1]+'</option>';
                             

                            }
                            $("#category_id_fk").html(attach);
                            $("#edit_category_id_fk").html(attach);
                            $("#product_category_id_fk").html(attach);
                            $('#category_id_fk').selectpicker('refresh');
                            $("#edit_category_id_fk").selectpicker('refresh');
                            $("#product_category_id_fk").selectpicker('refresh');
                      },
                      complete: function() {
                             //  me.data('requestRunning', false);
                      }

                }); // submit ajax

    }


    


    





  
    function calc_total_item_cost(id){
          
          var row_num = id;

          // set cost_expenses valaue
          calc_cost_expenses();

          // var total_item_cost = $("#purchase_quantity_"+row_num).val() * $("#cost_expenses_"+row_num).val();
          // $("#total_item_cost_"+row_num).html(currency_format_display(total_item_cost));

          
          // calc_total_purchase_price();
          
          
    }


    function edit_calc_total_item_cost(id){
          // var row_num1 = id.split('_');
          var row_num = id;
          
          edit_calc_cost_expenses();
          
    }


    function calc_total_purchase_price(){
          // footer of table purchase_total
          var purchase_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).html();
            
              cost = td_cost.split(" ");
             
              rep_cost =cost[0].replace(/,/g,'');
              if(isNaN(rep_cost) || rep_cost == ''){
                rep_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(rep_cost).toFixed(2);
            }
            
          }
          // console.log(purchase_total +" TT");
          $("#purchase_total").html(currency_format_display(purchase_total))
    }

    function edit_calc_total_purchase_price(){
          // footer of table purchase_total
          var purchase_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).html();
            
              cost = td_cost.split(" ");
              rep_cost =cost[0].replace(/,/g,'');
              // console.log(rep_cost +" rep_cost");
              if(isNaN(rep_cost) || rep_cost == ''){
                rep_cost =0;
              }
              purchase_total = +purchase_total + +parseFloat(rep_cost).toFixed(2);
            }
            
          }
          // console.log(purchase_total +" TT");
          $("#edit_purchase_total").html(currency_format_display(purchase_total))
    }


    function calc_cost_expenses(){
          
          var total_expens  = $("#total_expenses").val();
          var curnt_row_num = $("#total_rows").val();
          var total_qty     = 0;

          if(total_expens >0){

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

              if($("#purchase_quantity_"+i).length > 0){
                var qty = $("#purchase_quantity_"+i).val();
                total_qty = +total_qty + +qty;
              }
              
            }

            var single_expenses = total_expens / total_qty;

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

              if($("#cost_expenses_"+i).length > 0){
                var curnt_val = $("#cost_"+i).val();
                var new_val   = +curnt_val + +single_expenses;
                new_val       = round(new_val,4);
                $("#cost_expenses_"+i).val(new_val);
                
              }
              
            }

          }else{

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

              $("#cost_expenses_"+i).val($("#cost_"+i).val());
              
              
            }


          }


          calc_cost_all();


          
          
    }

    function edit_calc_cost_expenses(){
          
          var total_expens  = $("#edit_total_expenses").val();
          var curnt_row_num = $("#edit_total_rows").val();
          var total_qty     = 0;

          if(total_expens >0){

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

              if($("#edit_purchase_quantity_"+i).length > 0){
                var qty = $("#edit_purchase_quantity_"+i).val();
                total_qty = +total_qty + +qty;
              }
              
            }

            var single_expenses = total_expens / total_qty;

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

              if($("#edit_cost_expenses_"+i).length > 0){
                var curnt_val = $("#edit_cost_"+i).val();
                var new_val   = +curnt_val + +single_expenses;
                new_val       = round(new_val,4);
                $("#edit_cost_expenses_"+i).val(new_val);
                
              }
              
            }

          }else{

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

              $("#edit_cost_expenses_"+i).val($("#edit_cost_"+i).val());
              
              
            }


          }


          edit_calc_cost_all();


          
          
    }

    function calc_cost_all(){
          
          var total_expens  = $("#total_expenses").val();
          var curnt_row_num = $("#total_rows").val();
          var total_qty     = 0;


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

              if($("#purchase_quantity_"+i).length > 0){
                var total_item_cost = $("#purchase_quantity_"+i).val() * $("#cost_expenses_"+i).val();
                $("#total_item_cost_"+i).html(currency_format_display(total_item_cost));

                
              }
              
            }

            calc_total_purchase_price();

          
          
    }

    function edit_calc_cost_all(){
          
          var total_expens  = $("#edit_total_expenses").val();
          var curnt_row_num = $("#edit_total_rows").val();
          var total_qty     = 0;


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

              if($("#edit_purchase_quantity_"+i).length > 0){
                var total_item_cost = $("#edit_purchase_quantity_"+i).val() * $("#edit_cost_expenses_"+i).val();
                $("#edit_total_item_cost_"+i).html(currency_format_display(total_item_cost));

                
              }
              
            }

            edit_calc_total_purchase_price();

          
          
    }


    function print_invoice(typ,payment=null){
      if(typ=='Print'){
        window.open().document.write(HTML_VIEW_PAY+print_page);
      }else if(typ=='PDF'){
        var nn = $("#inv_numb").val();
        pdf_generator(HTML_VIEW_PAY,nn,'pay')
      }else{
        window.open().document.write(HTML_VIEW_PAY);
      }
    }

    function pdf_generator(HTML,INV_NO,payment){

                $.ajax({
                      url : 'models/crul_purchase.php',

                      type : 'POST',
                      data : {type:'PDF',html:HTML,inv_no:INV_NO,pay:payment},
                      dataType : 'json',
                      success : function(response) {
                            console.log(response)
                            if(response.is_success == true) {

                                    noty({
                                        width: 200,
                                        text: Translation('تم توليد ملف الـ PDF بنجاح'),
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'top',
                                    });
                                    var LINKS = '<a class="btn btn-labeled btn-labeled-left heading-btn btn-info" href="'+response.data+'" target="_blank" style="float: right;"> '+Translation('Download')+' <b><i class="icon-file-download"></i></b> </a>';
                                    if(payment !=null){
                                      $("#link_pdf_pay").append(LINKS);
                                    }else{
                                      $("#link_pdf").append(LINKS);
                                    }

                                  
                                  $("#pdf").attr('disabled',false);
                                  $("#pdf_pay").attr('disabled',false);
                                  $("#print").attr('disabled',false);
                                  $("#print_pay").attr('disabled',false);
                            } else {

                               noty({
                                     width: 200,
                                     text: Translation(response.message),
                                     type: 'error',
                                     dismissQueue: true,
                                     timeout: 3000,
                                     layout: 'top',
                               });

                                  $("#pdf").attr('disabled',false);
                                  $("#pdf_pay").attr('disabled',false);
                                  $("#print").attr('disabled',false);
                                  $("#print_pay").attr('disabled',false);
                            }
                      },
                      complete: function() {
                            //   me.data('requestRunning', false);
                      }

                }); // submit ajax
    }

   

    // general function for adding rows to new purchase and edited purchase
    function Add_Rows(edit=null){
      
      if(edit == null || edit ==''){
        edit = '';
      }else{
        edit = 'edit_';
      }

      
      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+`</td>
                            <td >
                              
                              <select class="form-control multi_lang stop_enter" name="`+edit+`product_id_fk_`+CNT+`" id="`+edit+`product_id_fk_`+CNT+`" data-width="100%"   data-live-search="true">

                              </select>

                            </td>
                            
                            <td >
                              <input type="number" value="1" id="`+edit+`purchase_quantity_`+CNT+`" name="`+edit+`purchase_quantity_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('الكمية')+`"  onchange="`+edit+`calc_total_item_cost(`+CNT+`);">
                            </td>
                            <td >
                              <input type="text" value="" id="`+edit+`purchase_barcode_`+CNT+`" name="`+edit+`purchase_barcode_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('Barcode')+`"  >

                            </td>

                            <td >
                              <input type="text" value="" id="`+edit+`purchase_expire_`+CNT+`" name="`+edit+`purchase_expire_`+CNT+`"  class="form-control text-center daterange-single stop_enter" placeholder="`+Translation('تاريخ النفاذ')+`"  >

                            </td>

                            <td >
                              <input type="text" value="" id="`+edit+`cost_`+CNT+`" name="`+edit+`cost_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('سعر شراء الوحدة')+`"  onchange="`+edit+`calc_total_item_cost(`+CNT+`);">

                            </td> 

                            <td >
                              <input type="text" value="" id="`+edit+`cost_expenses_`+CNT+`" name="`+edit+`cost_expenses_`+CNT+`"  class="form-control text-center stop_enter" placeholder="`+Translation('الكلفة بعد المصاريف')+`"  readonly="readonly">

                            </td> 
                            
                            <td >
                              <input id="`+edit+`sell_price_`+CNT+`" name="`+edit+`sell_price_`+CNT+`" type="text" class="form-control text-center stop_enter" placeholder="`+Translation('سعر البيع')+`"  >
                            </td>
                            <td width="9%" id="`+edit+`total_item_cost_`+CNT+`"> 0 $</td>
                            <td width="10%">
                              <input type="text" id="`+edit+`purchase_item_note_`+CNT+`" name="`+edit+`purchase_item_note_`+CNT+`" class="form-control submit_enter" placeholder="`+Translation('ملاحظات')+`" >
                            </td>
                            <td width="6%">
                              <button class="btn btn-link btn-xs btn_add_item " onclick="Add_Rows('`+edit+`')" >
                                <i  class="icon-add text-blue"></i>
                              </button>
                              <button class="btn btn-link btn-xs btn_remove_item" id="`+edit+`row_`+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);

            // we should call get_product to load all products for this row

            if(edit == null || edit ==''){
              get_products(CNT);
              $('.daterange-single').daterangepicker({ 
                  singleDatePicker: true,
                  locale: {
                      format: 'YYYY-MM-DD'
                  }
              });
            }else{
              edit_get_products(CNT);
            }

            auto_number();
            // $(".stop_enter").autotab();
            

            
    }

    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++;
          }
          
        }

    }

$(document).ready(function() {
  
    
    get_Stock();
    get_Branch();
    get_Supplier();
    get_products(1);

    get_Category();


    $("#purchase_item_body").on('change','select[id^="product_id_fk_"]', function(e){
      var id = ($(this).attr('id'));
      var sell_price = $("#"+id+' option:selected').attr('data-sell-price');
      var ids = id.split('_');
      // console.log(ids)
     $("#sell_price_"+ids[3]).val(sell_price);

    });



    $("#edited_purchase_contain").on('change','select[id^="edit_product_id_fk_"]', function(e){
      var id = ($(this).attr('id'));
      var sell_price = $("#"+id+' option:selected').attr('data-sell-price');
      var ids = id.split('_');
      console.log(ids)
     $("#edit_sell_price_"+ids[4]).val(sell_price);

    });


    $("#purchase_item_body").on("keypress",".barcode", function (e) {
          
          if (e.keyCode == 13 || e.which ==13) {
           
            e.preventDefault();
           
          }
    })


    // add new tab when reach the end of row
    $("#purchase_item_body").on("keyup",".btn_add_item", function (e) {
         
          if (e.keyCode == 9 || e.which ==9) {
           
            e.preventDefault();
            
            Add_Rows();
          }
    });

    // submit form when enter pressed in note field
    $("#purchase_item_body").on("keypress",".submit_enter", function (e) {
         
          if (e.keyCode == 13 || e.which ==13) {
           
            e.preventDefault();

            $('#add_form').submit();
           
          }
    });

    
  
    // to prevent default show modal on page load

    $('#product_id_fk_1').change(function(e) {
      e.preventDefault();
         // load_products(this.value,this.id);
    });

    $('#purchase_quantity_1').change(function(e) {
      e.preventDefault();
         calc_total_item_cost(1);
    });


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

    

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

    $('#purchase_item_body').on('click','.btn_add_item',function(e) {
      e.preventDefault();
         // alert("ss")
    });

    $('#edited_purchase_contain').on('click','.btn_add_item',function(e) {
      e.preventDefault();
         // alert("dd")
    });

   

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

 
  



    $("#edited_purchase_contain").on('click','.btn_remove_item',function(e){
          e.preventDefault();
          // console.log(this.id);
          // alert("RR")
          var row_num1 = this.id.split('_');
          var row_num = row_num1[2];
          $("#edit_item_row_"+row_num).remove();
          edit_calc_total_item_cost();
    });


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

      var category_id_fk            = $("#category_id_fk").val();
      
      var product_name              = $("#product_name").val();
      var product_type              = $("#product_type").val();
      var product_code              = $("#product_code").val();
      var barcode                   = $("#barcode").val();
      var made_in                   = $("#made_in").val();     
      var product_note              = $("#product_note").val();
      var color                     = $("#color").val();
      var image_path                = $("#image_path").val();
      var product_min_notification  = $("#product_min_notification").val();
      


      var Check1 = true;
      var Check2 = true;
      var Check3 = true;
      var Check4 = true;
      var Check5 = true;
      var Check6 = true;

      

      
      Check2 = Checks('product_name');
      Check3 = Checks('product_type');
      // Check4 = Checks('product_code');
      
      var formData = new FormData(this);

      

      formData.append("type", 'create');



      if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
            $("#submit_add_product").attr('disabled',true);
            $.ajax({
                url: "models/crul_product.php",
                type:"POST",
                dataType : "JSON",
                data:formData,
                cache:false,
                contentType: false,
                processData: false
            })
            .done(function(res) {

                if(res.is_success == true){

                    $("#add_product_form")[0].reset();
                    $("#category_id_fk").val('').selectpicker('refresh');
                    $('#add_product_form_cont').modal('toggle');

                    noty({
                            width: 200,
                            text: Translation(res.data),
                            type: 'success',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                    var lst_row = $("#total_rows").val();
                    
                    get_products(lst_row);
                    $("#submit_add_product").attr('disabled',true);
                    
                }else{
                    swal({
                        title: Translation("خطأ"),
                        text: Translation(res.data),
                        confirmButtonColor: "#66BB6A",
                        type: "warning"
                    });
                    //$("#add-form-cont").collapse('hide');
                }
                $("#submit_add_product").attr('disabled',false);
            })
            .fail(function(err) {
                $("#submit_add_product").attr('disabled',false);
                 swal({
                    title: Translation("خطأ"),
                    text: (err),
                    confirmButtonColor: "#66BB6A",
                    type: "error"
                });
                
            })
            .always(function() {
                console.log("complete");
            });
        }

    });


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

          var cnt                     = $("#total_rows").val();
          
          var product_id_array        =[];
          var quantity_array          =[];
          var barcode_array           =[];
          var expire_array            =[];
          var unit_price_array        =[];
          var cost_expenses_array     =[];
          var sell_price_array        =[];
          var notes_array             =[];
          var check_products          =[];
          var check_quantity          =[];
          var check_price             =[];
          var check_sell_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 barcode           = $("#purchase_barcode_"+i).val();
              var expire            = $("#purchase_expire_"+i).val();
              var unit_price        = $("#cost_"+i).val();
              var cost_expense      = $("#cost_expenses_"+i).val();
              var sell_price        = $("#sell_price_"+i).val();
              var notes             = $("#purchase_item_note_"+i).val();

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

                check_products[k]         = Checks('product_id_fk_'+i);
                check_quantity[k]         = Checks('purchase_quantity_'+i,'No',1);
                check_price[k]            = Checks('cost_'+i,'No',0);
                check_sell_price[k]       = Checks('sell_price_'+i,'No',0);
                
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                barcode_array[k]          = barcode;
                expire_array[k]           = expire;
                cost_expenses_array[k]    = cost_expense;
                unit_price_array[k]       = unit_price;
                sell_price_array[k]       = sell_price;
                notes_array[k]            = notes;
                
                
                k++;
              }
          }
          
          var purchase_number         = $("#purchase_number").val();
          var purchase_date           = $("#purchase_date").val();
          var stock_id_fk             = $("#branch_id_fk option:selected").attr('data-stock-id-fk');

          var purchase_note           = $("#purchase_note").val();
          var supplier_id_fk          = $("#supplier_id_fk").val();
          var purchase_transaction    = $("#purchase_transaction").val();
          var branch_id_fk            = $("#branch_id_fk").val();
          var total_expenses          = $("#total_expenses").val();
          var total_paid              = $("#total_paid").val();
          

          var Check1    = Checks('purchase_number');
          var Check2    = Checks('stock_id_fk');
          var Check3    = Checks('supplier_id_fk');
          var Check4    = Checks('branch_id_fk');
          
          var CheckPro  = true;
          var checkQty  = true;
          
          var checkprice  = true;
          var checksell   = 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(check_sell_price[m]==false){
              checksell = false;
            }

          }


          var formData = new FormData(this);
          
          formData.append("type", 'create');
          formData.append("purchase_number", purchase_number);
          formData.append("purchase_date", purchase_date);
          formData.append("stock_id_fk", stock_id_fk);
          formData.append("purchase_note", purchase_note);
          formData.append("supplier_id_fk", supplier_id_fk);
          formData.append("purchase_transaction", purchase_transaction);
          formData.append("total_expenses", total_expenses);
          formData.append("branch_id_fk", branch_id_fk);
          formData.append("product_id_fk", product_id_array);
          formData.append("purchase_quantity", quantity_array);
          formData.append("barcode", barcode_array);
          formData.append("expire_date", expire_array);
          formData.append("cost_price", unit_price_array);
          formData.append("cost_expense", cost_expenses_array);
          formData.append("sell_price", sell_price_array);
          formData.append("purchase_item_note", notes_array);
          formData.append("total_paid", total_paid);
          

          if(Check1 && Check2 && Check3 && Check4 && CheckPro && checkQty  && checkprice && checksell){
            $("#submit_add_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_purchase.php",
                type:"POST",
                dataType: "JSON",
                data:formData,
                cache:false,
                contentType: false,
                processData: false
                // data : {purchase_number         : purchase_number,
                //         purchase_date           : purchase_date,
                //         stock_id_fk             : stock_id_fk,
                //         purchase_note           : purchase_note,
                //         supplier_id_fk          : supplier_id_fk,
                //         purchase_transaction    : purchase_transaction,
                //         total_expenses          : total_expenses,
                //         branch_id_fk            : branch_id_fk,
                        
                       
                //         product_id_fk           : product_id_array,
                //         purchase_quantity       : quantity_array,
                //         barcode                 : barcode_array,
                //         expire_date             : expire_array,
                //         cost_price              : unit_price_array,
                //         cost_expense            : cost_expenses_array,
                //         sell_price              : sell_price_array,
                //         purchase_item_note      : notes_array,
                //         type                    : 'create'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

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

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

    });




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

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

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


          var product_id_array        =[];
          var quantity_array          =[];
          var barcode_array           =[];
          var expire_array            =[];
          var unit_price_array        =[];
          var cost_expenses_array     =[];
          var sell_price_array        =[];
          var notes_array             =[];
          var check_products          =[];
          var check_quantity          =[];
          var check_price             =[];
          var check_sell_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 barcode           = $("#edit_purchase_barcode_"+i).val();
              var expire            = $("#edit_purchase_expire_"+i).val();
              var unit_price        = $("#edit_cost_"+i).val();
              var cost_expense      = $("#edit_cost_expenses_"+i).val();
              var sell_price        = $("#edit_sell_price_"+i).val();
              var notes             = $("#edit_purchase_item_note_"+i).val();

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

                check_products[k]         = Checks('edit_product_id_fk_'+i);
                check_quantity[k]         = Checks('edit_purchase_quantity_'+i,'No',1);
                check_price[k]            = Checks('edit_cost_'+i,'No',0);
                check_sell_price[k]       = Checks('edit_sell_price_'+i,'No',0);
                
                product_id_array[k]       = productID;
                quantity_array[k]         = quantityField;
                barcode_array[k]          = barcode;
                expire_array[k]           = expire;
                cost_expenses_array[k]    = cost_expense;
                unit_price_array[k]       = unit_price;
                sell_price_array[k]       = sell_price;
                notes_array[k]            = notes;
             
                
                k++;
              }
          }
          
          

          var purchase_number         = $("#edit_purchase_number").val();
          var purchase_date           = $("#edit_purchase_date").val();
          var stock_id_fk             = $("#edit_branch_id_fk option:selected").attr('data-stock-id-fk');
          var purchase_note           = $("#edit_purchase_note").val();
          var supplier_id_fk          = $("#edit_supplier_id_fk").val();
          var purchase_transaction    = $("#edit_purchase_transaction").val();
          var branch_id_fk            = $("#edit_branch_id_fk").val();
          var total_expenses          = $("#edit_total_expenses").val();
          

          var Check1                  = Checks('edit_purchase_number');
          var Check2                  = Checks('edit_stock_id_fk');
          var Check3                  = Checks('edit_supplier_id_fk');
          var Check4                  = Checks('edit_branch_id_fk');
          
          var CheckPro                = true;
          var checkQty                = true;
          
          var checkprice              = true;
          var checksell               = 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(check_sell_price[m]==false){
              checksell = false;
            }

          }




          if(Check1 && Check2 && Check3 && CheckPro && checkQty  && checkprice && checksell){
            $("#submit_edit_btn").attr('disabled',true);
            $.ajax({
                url: "models/crul_purchase.php",
                type:"POST",
                dataType: "JSON",
                data : {
                        purchase_number         : purchase_number,
                        purchase_date           : purchase_date,
                        stock_id_fk             : stock_id_fk,
                        purchase_note           : purchase_note,
                        supplier_id_fk          : supplier_id_fk,
                        purchase_transaction    : purchase_transaction,
                        total_expenses          : total_expenses,
                        branch_id_fk            : branch_id_fk,
                        
                       
                        product_id_fk           : product_id_array,
                        purchase_quantity       : quantity_array,
                        barcode                 : barcode_array,
                        expire_date             : expire_array,
                        cost_price              : unit_price_array,
                        cost_expense            : cost_expenses_array,
                        sell_price              : sell_price_array,
                        purchase_item_note      : notes_array,
                        item_id                 : item_id,
                        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() {},
                                            },
                              });

                    
               
                }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");
                $("#submit_edit_btn").attr('disabled',false);

            });
          }


          
    });



   





});







$(function() {
//var singleSelect = $('.datatable-column-search-inputs').DataTable();
    
  $(".touchspin-basic").TouchSpin({
        min: 1,
        max: 10000000,
        step: 1,
        buttondown_class: "btn btn-xs",
        buttonup_class: "btn btn-xs"
    });

  $('.daterange-single').daterangepicker({ 
        singleDatePicker: true,
        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_id = getQueryVariable("id");

   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_purchase.php",
        "data": function(d){
          d.type = "load";
          d.branch_id = BRANCH_ID;
          if(query_id !='not'){
            d.id =query_id ;
          }
        }
        },
        drawCallback: function() {
                  $('[data-popup=tooltip]').tooltip();
                  $('[data-popup=popover-custom]').popover({
                    template: '<div class="popover  border-teal-400"><div class="arrow"></div><h3 class="popover-title bg-teal-400"></h3><div class="popover-content"></div></div>'
                  });

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

                    var btn ='';

                    if(IS_VIEW==0){
                      btn = ` <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>
                                  </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>
                                  </a>
                              </li>`;
                    }


                            return  `<ul class='icons-list '>
                                        
                                        <li class='text-primary-600'>
                                            <a  class='text-purple-600' onclick="show_purchase(`+row[0]+`,null,'Detail')" data-popup='tooltip'  data-original-title='`+Translation('عرض تفاصيل وصل الشراء')+`'>
                                                <i class='icon-stack-text'></i>
                                            </a>
                                        </li>

                                        
                                        `+btn+`
                                        
                                        
                                    </ul>`;
                        }
          },


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


                        // return  `<a href='index.php?p=purchase&id=`+row[0]+`'  data-popup='tooltip' data-original-title='`+Translation('عرض تفاصيل وصل الشراء')+`'>`+data+`</a>`;
                        return  `<a onclick="show_purchase(`+row[0]+`,null,'Detail')"  data-popup='tooltip' data-original-title='`+Translation('عرض تفاصيل وصل الشراء')+`'>`+data+`</a>`;


               },
               "targets": 1
            },
            {
                "render": function(data, type, row){

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

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

                    return currency_format_display(data);
                },
                "targets": 6
            },
            
            {
                "render": function(data, type, row){

                      if(data == null || data ==''){
                        
                        return  ` <img  src="assets/images/placeholder.jpg" class="img-rounded img-lg">   `;
                      }else{
                        return  `<a  onclick="show_files('`+row[10]+`')"> <img src="`+data +`" width="100" class="img-rounded img-l">  </a>`;

                      }
                   
                      
                   
                },
                "targets": 10
            },
            
            

           
        ],
        "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"
                                      href="javascript:;"
                                      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>`);  
          }

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


});



