var table ,  block = $(".content-wrapper").parent();
    
    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         = "";

          $.ajax({
                url : 'models/crul_purchase.php',
                type : 'POST',
                data : {type:'get_edit_purchase', id : itemid},
                dataType : 'json',
                success : function(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);
                  $("#edit_purchase_note").val(response.purchase[0].purchase_note);

                  var 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('الكمية')+`</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;

                     
                      total_row_price = response.purchase[i].total_length * response.purchase[i].buy_price_per_meter ;
                      total_row_price = currency_format_display(total_row_price);
                      
                      var Det = '';
                      // display sell item details
                      for(var j=0 ; j < response.details.length;j++){
                        var purchase_item_id = response.purchase[i].purchase_item_id;

                        if(purchase_item_id == response.details[j].purchase_item_id_fk){
                          // Det = Det + ` <input types="text"  class="badge bg-pink-400 col-sm-6" value="`+response.details[j].item_length+`" readonly> `;
                          Det = Det + `<input types="text" id="edit_row_`+i+`_roll_`+j+`" class="badge badge-primary col-sm-2" value="`+response.details[j].item_length+`" data-item-status="`+response.details[j].item_status+`" data-item-id="`+response.details[j].purchase_item_detail_id+`" onchange="edit_calc_total_length(`+i+`,`+response.purchase[i].total_quantity+`);">`;
                          
                        }
                      }
                    

                      attach = attach + `     
                                        <tr  id="edit_item_row_`+i+`" >
                                          <td width="5%" id="edit_num_`+i+`">`+i+`</td>
                                          <td width="12%">
                                           
                                            <select value="`+response.purchase[i].product_id_fk+`" class="form-control multi_lang" name="edit_product_id_fk_`+i+`" id="edit_product_id_fk_`+i+`" data-width="100%" placeholder="رمز المادة" onchange="edit_load_products(this.value,this.id);" data-live-search="true">

                                            </select>

                                          </td>
                                          <td width="12%" id="edit_forign_id_`+i+`">`+response.purchase[i].turkish_code+`</td>
                                          <td width="8%">
                                            <input type="number" id="edit_purchase_quantity_`+i+`" value="`+response.purchase[i].total_quantity+`" name="edit_purchase_quantity_`+i+`"  class="form-control" placeholder="`+Translation('الكمية')+`"  onchange="edit_add_qty_input_fields(this.value,this.id);">
                                          </td>
                                          <td id="edit_products_`+i+`">`+Det+`</td>
                                          <td width="7%" >
                                            <input id="edit_total_length_`+i+`" value="`+response.purchase[i].total_length+`" name="edit_total_length_`+i+`" type="text" class="form-control" readonly >
                                          </td>
                                          <td width="8%">
                                            <input id="edit_buy_price_per_meter_`+i+`" value="`+response.purchase[i].buy_price_per_meter+`" name="edit_buy_price_per_meter_`+i+`" type="text" class="form-control" placeholder="`+Translation('سعر شراء المتر')+`" onchange="edit_calc_total_item_cost(this.id);" >
                                          </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></th>
                                      <th id="edit_purchase_total">`+currency_format_display(response.purchase[0].total_purchase_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');
                }

          }); // submit ajax



    }

    function delete_items(itemid) {
        block = $("#list_of_items_tbl");
        // bootstrap modal confirmation box
          swal({
              title: Translation("هل انت متأكد؟!"),
              text: Translation("سوف لن تستطيع استرجاع المعلومات المرتبطة بهذا السجل في حالة المسح"),
              type: "warning",
              showCancelButton: true,
              confirmButtonColor: "#EF5350",
              confirmButtonText: Translation("موافق: امسح!"),
              cancelButtonText: Translation("الغاء الامر"),
              closeOnConfirm: false,
              closeOnCancel: true
          },
          function(isConfirm){
              if (isConfirm) {
                $.ajax({
                  url: "models/crul_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){
                      // get_Products();
                      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:1.6in;' 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>
                                              <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:1.6in;' 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_customer_address"> `+response.purchase[0].purchase_number+` </span>
                                              </td>
                                              <td width=144 style='width:1.5in;' class="table1_td1">
                                              <span  id="inv_customer_address"> `+response.purchase[0].supplier_full_name+` </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('التفاصيل')+` 
                                    </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:95.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].total_length * response.purchase[i].buy_price_per_meter ;
                          total_row_price = currency_format_display(total_row_price);
                        
                        var Det = '';
                        if(detail_show != null){

                          // display sell item details
                          for(var j=0 ; j < response.details.length;j++){
                            var purchase_item_id = response.purchase[i].purchase_item_id;

                            if(purchase_item_id == response.details[j].purchase_item_id_fk){
                              Det = Det + ` <input types="text"  class="badge bg-pink-400 col-sm-6" value="`+response.details[j].item_length+`" readonly> `;
                            }
                          }
                        }

                          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].total_quantity+` </span>
                                                    </td>
                                                    <td width=74 style='width:65.5pt; font-family: Times, serif;' >
                                                      <span  id="inv_total_row"> `+Det+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt;' class="last_td">
                                                      <span  id="inv_total_row"> `+response.purchase[i].total_length+` </span>
                                                    </td>
                                                    <td width=74 style='width:55.5pt; font-family:  Times, serif;'>
                                                      <span  id="inv_details"> `+currency_format_display(response.purchase[i].buy_price_per_meter)+` </span>
                                                    </td>
                                                    <td width=87  style='width:65.25pt;'>
                                                      <span  id="inv_total_length"> `+currency_format_display(response.purchase[i].total_row_price)+`  </span>
                                                    </td>
                                                    <td width=152 style='width:103.85pt;'>
                                                      <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=7 valign=top style='width:388.0pt;border:none;
                                  border-left:solid #984806 1.0pt;background:white;padding:2.15pt 5.75pt 2.15pt 5.75pt;
                                  height:.1in'>
                                 `+Translation('المبلغ الكلي')+` 
                                  </td>
                                  <td width=74 style='width:55.5pt;border-top:none;border-left:solid #984806 1.0pt;
                                  border-bottom:solid #984806 1.0pt;border-right:none;
                                  padding:0pt .1in 0pt .1in;height:.1in'>
                                   `+currency_format_display(response.purchase[0].total_purchase_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'>
                                    <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=7  style='width:388.0pt;border:none;
                                  padding:2.15pt 5.75pt 2.15pt 5.75pt;height:.1in'>
                                  
                                  </td>
                                  <td width=74 style='width:55.5pt;border:none;padding:2.15pt .15in 2.15pt .15in;
                                  height:.1in'>
                                 `+Translation('التوقيع')+` 
                                  </td>
                                 </tr>
                                </table>

                                </div>




                                </body>

                                `+print_attach+`

                                </html>`;

                      

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

                      HTML_VIEW_PAY = HTML_Table + headers + customer_details + attach + attach_other + footers;
                       //  me.data('requestRunning', false);
                      
                        $("#invoice_show").html(HTML_VIEW_PAY);
                        $("#inv_numb").val(itm);

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

          }); // submit ajax


    }

    function Checks(id,types=null,min=null,max=null,badge=null){
        var name = $("#"+id).val();
        var placeholder = $("#"+id).attr('placeholder');
        if(types == null){  // it mean string

              if(min !=null && max !=null){
                  if(name =='' || name.length < min || name.length > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter the Required Field with minimum length of "+ min + " and maximum length " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min !=null && max ==null){
                  if(name ==''  || name.length < min ){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter the Required Field with minimum length of "+ min ,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min ==null && max !=null){
                  if(name ==''  ||  name.length > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter the Required Field with  maximum length of " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else{

                  if(name ==''){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "حقل " + placeholder + " لا يجب ان يبقى فاغ",
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }

              }

        }else if(types == 'No'){  // it mean numbers

              if(min !=null && max !=null){
                  if(name !='' && isNaN(name) || name < min || name > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value between "+ min + " and " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min !=null && max ==null && badge !=null){
                  if(name !='' && isNaN(name) || name < min ){
                    $("#"+id).removeClass('badge-primary');
                    $("#"+id).addClass('badge-warning');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value Greater than "+ min,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).removeClass('badge-warning');
                      $("#"+id).addClass('badge-primary');
                      return true;
                  }


                }else if(min !=null && max ==null){
                  if(name !='' && isNaN(name) || name < min ){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');
                    
                    noty({
                            width: 200,
                            text: "الرجاء قم بادخال قيمة عددية اكبر او تساوي "+ min + " في حقل " + placeholder,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else if(min ==null && max !=null){
                  if(name !='' && isNaN(name) ||  name > max){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value Less than " + max,
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }
              }else{

                  if(name !='' && isNaN(name)){
                    $("#"+id).closest('.form-group').removeClass('has-success');
                    $("#"+id).closest('.form-group').addClass('has-error');

                    noty({
                            width: 200,
                            text: "Please Enter Numeric Value",
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                      });
                    return false;
                  }else{
                      $("#"+id).closest('.form-group').removeClass('has-error');
                      $("#"+id).closest('.form-group').addClass('has-success');
                      return true;
                  }

              }

        }
    }

    

    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

    }


    function get_Stock(){

            $.ajax({
                  url : 'models/crul_stock.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 =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() {
                         //  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];
                          attach = attach + '<option  data-subtext="'+Translation('الرمز الاجنبي : ')+tp+' || '+Translation('الرمز التسلسلي : ')+BC+'" value="'+response[i][0]+'" data-forgin-code="'+response[i][2]+'">'+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

          

         

    }

    var products_array_values =[] ;

    
    function load_products1(val, id){
        var row_num1 = id.split('_');
        var row_num = row_num1[2];
        if(val !=""){

          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_one_product',p_val:val},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response.length==0){
                          $("#product_id_fk_"+row_num).val('');
                          $("#forign_id_"+row_num).html('');
                          noty({
                            width: 200,
                            text: Translation("لا توجد هكذا مادة الرجاء التاكد من الكود"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{
                          $("#product_id_fk_"+row_num).val(response[0][0]);
                          $("#forign_id_"+row_num).html(response[0][2]);
                        }
                  },
                  complete: function() {

                  }

            }); // submit ajax

        }

         

    }

    function edit_load_products1(val, id){
        var row_num1 = id.split('_');
        var row_num = row_num1[3];
        if(val !=""){

          $.ajax({
                  url : 'models/crul_product.php',
                  type : 'POST',
                  data : {type:'get_one_product',p_val:val},
                  dataType : 'json',
                  success : function(response) {
                   
                        if(response.length==0){
                          $("#edit_product_id_fk_"+row_num).val('');
                          $("#edit_forign_id_"+row_num).html('');
                          noty({
                            width: 200,
                            text: Translation("لا توجد هكذا مادة الرجاء التاكد من الكود"),
                            type: 'error',
                            dismissQueue: true,
                            timeout: 3000,
                            layout: 'topRight',
                          });

                        }else{
                          $("#edit_product_id_fk_"+row_num).val(response[0][0]);
                          $("#edit_forign_id_"+row_num).html(response[0][2]);
                        }
                  },
                  complete: function() {

                  }

            }); // submit ajax

        }

         

    }


    function load_products(val, id){
        var row_num1 = id.split('_');
        var row_num = row_num1[3];
        
        var forgin_code = $("#product_id_fk_"+row_num+" option:selected").attr('data-forgin-code');
        $("#forign_id_"+row_num).html(forgin_code);

        // we should show modal for input rolls length 
        var qty = $("#purchase_quantity_"+row_num).val();

        
        add_qty_input_fields(qty,"purchase_quantity_"+row_num);

    }

    function edit_load_products(val, id){
        var row_num1 = id.split('_');
        var row_num = row_num1[4];
        
        var forgin_code = $("#edit_product_id_fk_"+row_num+" option:selected").attr('data-forgin-code');
        $("#edit_forign_id_"+row_num).html(forgin_code);

        var qty = $("#edit_purchase_quantity_"+row_num).val();

        
        edit_add_qty_input_fields(qty,"edit_purchase_quantity_"+row_num);


    }

    


    



    function add_qty_input_fields(qty,id){
      
      var row_num1 = id.split('_');
      var row_num = row_num1[2];

      $("#fields_count").val(qty);
      $("#rows_count").val(row_num);
      $("#part_qty").val(1);  // make defualt vale 1 as reset for each new input

      // to prevent show modal while loading page or refresh


      if(qty >0 && qty !=""){

        // Modal for input rolls lengths
        var attach_input ="";
        for (var i = 1; i <= qty; i++) {
          attach_input = attach_input + `
                                          <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                            <label class="control-label">`+Translation('الطول')+`</label>
                                            <input type="text" id="roll_length_`+i+`" name="roll_length_`+i+`" class="form-control" placeholder="`+Translation('الطول')+`" required="required">
                                            <div class="form-control-feedback">
                                              <i class="icon-pencil-ruler text-muted"></i>
                                            </div>
                                          </div>`;
        }

        $("#input_box_array").html(attach_input);
        $('#add_new_product').modal('toggle');

      }
      
      
      

    }

    // for Editing
    function edit_add_qty_input_fields(qty,id){
      
      var row_num1 = id.split('_');
      var row_num = row_num1[3];

      $("#edit_fields_count").val(qty);
      $("#edit_rows_count").val(row_num);

      if(qty >0 && qty !=""){

        // Modal for input rolls lengths

        // for editing i should read the old value and store its status and length then add the new one if he increase the qty 
        // but if he decrease the qty we can handle it be make one of them empty so we will consider it as removed
        
        var attach_input ="";
        for (var i = 1; i <= qty; i++) {
          attach_input = attach_input + `
                                          <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                            <label class="control-label">`+Translation('الطول')+`</label>
                                            <input type="text" id="edit_roll_length_`+i+`" name="edit_roll_length_`+i+`" class="form-control" placeholder="`+Translation('الطول')+`" required="required">
                                            <div class="form-control-feedback">
                                              <i class="icon-pencil-ruler text-muted"></i>
                                            </div>
                                          </div>`;
        }

        $("#edit_input_box_array").html(attach_input);
        $('#edit_add_new_product').modal('toggle');

      }
      

    }

    function calc_total_length(row_no,qty,edit_=null){

          if(edit_ == null || edit_ ==''){
            edit_ = '';
          }else{
            edit_ = 'edit_';
          }

          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            total_roll_length = +total_roll_length + +$("#"+edit_+"row_"+row_no+"_roll_"+i).val();
          }
          total_roll_length = total_roll_length.toFixed(2);
          $("#"+edit_+"total_length_"+row_no).val(total_roll_length);
          var total_item_cost = total_roll_length * $("#"+edit_+"buy_price_per_meter_"+row_no).val();
          $("#"+edit_+"total_item_cost_"+row_no).html(currency_format_display(total_item_cost));
          calc_total_purchase_price();
    }

    function edit_calc_total_length(row_no,qty){

         
          edit_ = 'edit_';
         

          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            total_roll_length = +total_roll_length + +$("#"+edit_+"row_"+row_no+"_roll_"+i).val();
          }
          $("#"+edit_+"total_length_"+row_no).val(total_roll_length);
          var total_item_cost = total_roll_length * $("#"+edit_+"buy_price_per_meter_"+row_no).val();
          $("#"+edit_+"total_item_cost_"+row_no).html(currency_format_display(total_item_cost));
          edit_calc_total_purchase_price();
    }


    function calc_total_item_cost(id){
          var row_num1 = id.split('_');
          var row_num = row_num1[4];
          
          var total_item_cost = $("#total_length_"+row_num).val() * $("#buy_price_per_meter_"+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 = row_num1[5];
          
          var total_item_cost = $("#edit_total_length_"+row_num).val() * $("#edit_buy_price_per_meter_"+row_num).val();
          $("#edit_total_item_cost_"+row_num).html(currency_format_display(total_item_cost));  
          edit_calc_total_purchase_price();
    }


    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,'');
              // console.log(rep_cost +" rep_cost");
              if(isNaN(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 = 1; 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 =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 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
    }

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
          var pair = vars[i].split("=");
          if (pair[0] == variable) {
            return pair[1];
          }
        }
        return 'not';
    }

    // 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 width="5%" id="`+edit+`num_`+CNT+`">`+CNT+`</td>
                            <td width="12%">
                              
                              <select class="form-control multi_lang" name="`+edit+`product_id_fk_`+CNT+`" id="`+edit+`product_id_fk_`+CNT+`" data-width="100%" placeholder="رمز المادة" onchange="`+edit+`load_products(this.value,this.id);" data-live-search="true">

                              </select>

                            </td>
                            <td width="12%" id="`+edit+`forign_id_`+CNT+`"></td>
                            <td width="8%">
                              <input type="number" value="1" id="`+edit+`purchase_quantity_`+CNT+`" name="`+edit+`purchase_quantity_`+CNT+`"  class="form-control" placeholder="`+Translation('الكمية')+`"  onchange="`+edit+`add_qty_input_fields(this.value,this.id);">
                            </td>
                            <td id="products_`+CNT+`"></td>
                            <td width="7%" >
                              <input id="`+edit+`total_length_`+CNT+`" name="`+edit+`total_length_`+CNT+`" type="text" class="form-control" readonly >
                            </td>
                            <td width="8%">
                              <input id="`+edit+`buy_price_per_meter_`+CNT+`" name="`+edit+`buy_price_per_meter_`+CNT+`" type="text" class="form-control" placeholder="`+Translation('سعر شراء المتر')+`" onchange="`+edit+`calc_total_item_cost(this.id);" >
                            </td>
                            <td width="9%" id="`+edit+`total_item_cost_`+CNT+`"> 0 $</td>
                            <td width="10%">
                              <textarea type="text" id="`+edit+`purchase_item_note_`+CNT+`" name="`+edit+`purchase_item_note_`+CNT+`" class="form-control" placeholder="`+Translation('ملاحظات')+`" ></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_`+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);
            }else{
              // edit_get_products(CNT);
            }
            
    }

$(document).ready(function() {
  
    
    get_Stock();
    get_Supplier();
    get_products(1);
  
    // 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();
         add_qty_input_fields(this.value,this.id);
    });


    $('#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_purchase_price();
    });

    $("#default_val_btn").on('click',function(){
        var qty   =$("#fields_count").val();
        var deflt = $("#default_val").val();
        for (var i = 1; i <= qty; i++) {
          $("#roll_length_"+i).val(deflt);
        }
     })

    $("#default_val_btn_qty").on('click',function(){
        var qty               = $("#fields_count").val();
        var part_qty          = $("#part_qty").val();  // this is as total qty for all part qty
        var curnt_part_qty    = $("#default_val_qty").val();

        var deflt             = $("#default_val").val();

        // now may he want to increase the quantity from the form so we should attach input fields

        if(part_qty >0 && part_qty !=""){

        // Modal for input rolls lengths
        var attach_input ="";
        for (var i = part_qty; i < (+part_qty + +curnt_part_qty); i++) {

          // check if exsist not append just change the value

          if($("#roll_length_"+i).length > 0){
            $("#roll_length_"+i).val(deflt);
          }else{
            attach_input = attach_input + `
                                          <div class="form-group has-feedback has-feedback-left form-group-material col-sm-2">
                                            <label class="control-label">`+Translation('الطول')+`</label>
                                            <input type="text" value="`+deflt+`" id="roll_length_`+i+`" name="roll_length_`+i+`" class="form-control" placeholder="`+Translation('الطول')+`" required="required">
                                            <div class="form-control-feedback">
                                              <i class="icon-pencil-ruler text-muted"></i>
                                            </div>
                                          </div>`;
          }
          
        }

        $("#input_box_array").append(attach_input);
        $("#part_qty").val((+part_qty + +curnt_part_qty));
        $("#fields_count").val((+part_qty + +curnt_part_qty -1))
      }

     })


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

          e.preventDefault();

          var qty = $("#fields_count").val();
          var row_no = $("#rows_count").val();
          var attach_input ="";
          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            
            total_roll_length = +total_roll_length + +$("#roll_length_"+i).val();

            attach_input = attach_input + `<input types="text" id="row_`+row_no+`_roll_`+i+`" class="badge badge-primary col-sm-2" value="`+$("#roll_length_"+i).val()+`" onchange="calc_total_length(`+row_no+`,`+qty+`);">`;
          }
          
          total_roll_length = total_roll_length.toFixed(2);

          $("#products_"+row_no).html(attach_input);
          $("#total_length_"+row_no).val(total_roll_length);
          // update quantity after appending quantity in the moadal
          $("#purchase_quantity_"+row_no).val(qty);

          var total_item_cost = total_roll_length * $("#buy_price_per_meter_"+row_no).val();
          $("#total_item_cost_"+row_no).html(currency_format_display(total_item_cost));
          $('#add_new_product').modal('toggle');

    });




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

    $("#edit_default_val_btn").on('click',function(){
        var qty   =$("#edit_fields_count").val();
        var deflt = $("#edit_default_val").val();
        for (var i = 1; i <= qty; i++) {
          $("#edit_roll_length_"+i).val(deflt);
        }
     })

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

          e.preventDefault();

          var qty = $("#edit_fields_count").val();
          var row_no = $("#edit_rows_count").val();
          var attach_input ="";
          var total_roll_length =0;
          for (var i = 1; i <= qty; i++) {
            
            total_roll_length = +total_roll_length + +$("#edit_roll_length_"+i).val();

            attach_input = attach_input + `<input types="text" id="edit_row_`+row_no+`_roll_`+i+`" class="badge badge-primary col-sm-2" value="`+$("#edit_roll_length_"+i).val()+`" onchange="edit_calc_total_length(`+row_no+`,`+qty+`);">`;
          }
          
          total_roll_length = total_roll_length.toFixed(2)
          $("#edit_products_"+row_no).html(attach_input);
          $("#edit_total_length_"+row_no).val(total_roll_length);
          var total_item_cost = total_roll_length * $("#edit_buy_price_per_meter_"+row_no).val();
          $("#edit_total_item_cost_"+row_no).html(currency_format_display(total_item_cost));
          $('#edit_add_new_product').modal('toggle');

    });


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

          block = $(this).parent();
          // \block

          var cnt               = $("#total_rows").val();
          
          var product_id_array  =[];
          var quantity_array    =[];
          var roll_length_array =[];
          var roll_total_array  =[];
          var unit_price_array  =[];
          var notes_array       =[];
          var check_products    =[];
          var check_quantity    =[];
          var check_price       =[];
          var check_rolls       =[];
          var check_rolls_all   =[];
          var k=1;

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

              var productID     = $("#product_id_fk_"+i).val();
              var quantityField = $("#purchase_quantity_"+i).val();
              var unit_price    = $("#buy_price_per_meter_"+i).val();
              var notes         = $("#purchase_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',1);
                check_price[k]      = Checks('buy_price_per_meter_'+i,'No',0.00000001);
                //console.log(check_quantity)
                product_id_array[k] = productID;
                quantity_array[k]   = quantityField;
                notes_array[k]      = notes;
                unit_price_array[k] = unit_price;

                // now i should check for rolls number and it should equal to quantity
                roll_length_array =[];
                check_rolls       =[];
                for(var j=1; j<=quantityField; j++){
                  check_rolls[j]       = Checks('row_'+i+'_roll_'+j,'No',1,null,'badge');
                  var rolls               = $('#row_'+i+'_roll_'+j).val();
                  console.log(rolls);
                  console.log('#row_'+i+'_roll_'+j);

                  roll_length_array[j] = rolls;
                }
                roll_total_array[k] = roll_length_array;
                check_rolls_all[k]  = check_rolls;
                // end checking rolls number
                console.log(roll_length_array);
                console.log(roll_total_array);
                k++;
              }
          }
          
          var purchase_number  = $("#purchase_number").val();
          var purchase_date    = $("#purchase_date").val();
          var stock_id_fk      = $("#stock_id_fk").val();
          var purchase_note    = $("#purchase_note").val();
          var supplier_id_fk   = $("#supplier_id_fk").val();
          

          var Check1    = Checks('purchase_number');
          var Check2    = Checks('stock_id_fk');
          
          var CheckPro  = true;
          var checkQty  = true;
          var checkrolls  = true;
          var checkprice  = 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;
            }

            for(var n=1;n<=roll_total_array[m];n++){
              if(check_rolls_all[m][n]==false){
                checkrolls = false;
              }
            }

          }




          if(Check1 && Check2 && CheckPro && checkQty && checkrolls && checkprice){
            $("#submit_add_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_quantity:quantity_array,buy_price_per_meter:unit_price_array
                  ,purchase_item_note:notes_array,product_id_fk:product_id_array,
                  item_length:roll_total_array,type:'create'}
            })
            .done(function(res) {
               
                  if(res.is_success == true){

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

                    // $("#product_name").val('');
                    // $("#erbil_code").val('');
                    // $("#turkish_code").val('');
                    // $("#barcode").val('');
                    // $("#product_note").val('');
                    // $(".fileinput-remove-button").trigger('click');

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

    });




    $('#edit_form').submit(function(event) {
            event.preventDefault();
            // block
            block = $(this).parent();
            // \block

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

            var product_id             = $("#edit_product_id").val();
            var quantity               = $("#edit_quantity").val();
            var buy_price              = $("#edit_buy_price").val();
            var created_at             = $("#edit_created_at").val();
            var sell_price             = $("#edit_sell_price").val();
            var sell_price_percentage  = $("#edit_sell_price_percentage").val();
            var average_price          = $("#edit_average_price").val();
            var note                   = $("#edit_note").val();

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


            Check1 = Checks('edit_product_id');
            Check2 = Checks('edit_quantity');
            Check3 = Checks('edit_buy_price');
            Check4 = Checks('edit_sell_price');
            Check5 = Checks('edit_sell_price_percentage');

            if(Check1 && Check2 && Check3 && Check4 && Check5 && Check6){
                //alert("ssss")
                $.ajax({
                    url: "models/crul_purchase1.php",
                    type:"POST",
                       data : {obj_id:catId,product_id:product_id,quantity:quantity,buy_price:buy_price,created_at:created_at,
                        sell_price:sell_price,sell_price_percentage:sell_price_percentage,average_price:average_price,note:note,type:'update'},
                    complete:function(){
                      //hideLoader();
                    },
                    beforeSend:function(){
                      //showLoader("Updating Purchase");
              },
                    success: function(res) {
                      if(res == 0){
                        $("#edit-form-cont").collapse('hide');
                        $("#edit_form")[0].reset();
                        swal({
                            title:"Not Success",
                            text: "Detail:"+res,
                            confirmButtonColor: "#66BB6A",
                            type: "warning"
                        });
                      }else if(res == 1){
                        $("#edit_form")[0].reset();
                        $(".datatable-column-search-inputs").DataTable().ajax.reload(null, false);
                        //$("#edit-form-cont").collapse('hide');
                        get_Products();
                        $('#edit_form_cont').modal('toggle');
                        noty({
                                        width: 200,
                                        text: 'Purchase Successfully Update',
                                        type: 'success',
                                        dismissQueue: true,
                                        timeout: 3000,
                                        layout: 'topRight',
                                  });
                      }else{
                              swal({
                                  title: "Error",
                                  text: "Detail:"+res,
                                  confirmButtonColor: "#66BB6A",
                                  type: "error"
                              });
                          }
                    }
                });
              }
    });



   





});







$(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': '&larr;', 'previous': '&rarr;' }
        },
        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({
        
        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";
          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": 8,
              "data": null,
              "render": function (data,type,row) {

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

                                        <li class='text-primary-600'>
                                            <a href='#' class='text-orange-400' onclick="show_purchase(`+row[0]+`)"  data-popup='tooltip' data-original-title='`+Translation('عرض وصل الشراء بدون تفاصيل')+`'>
                                                <i class='icon-file-text2'></i>
                                            </a>
                                        </li>
                                        <!--
                                        <li class='text-primary-600'>
                                            <a href='#' class='text-primary-400' onclick="edit_items(`+row[0]+`,'`+row[2]+`','`+row[3]+`','`+row[6]+`','`+row[12]+`','`+escape(row[7])+`')" data-popup='tooltip' data-original-title='`+Translation('تعديل')+`'>
                                                <i class='icon-pencil7'></i>
                                            </a>
                                        </li>
                                        -->
                                        <li class='text-danger-600'>
                                            <a href='#' class='text-danger-400' onclick="delete_items(`+row[0]+`,'`+row[12]+`')" data-popup='tooltip' data-original-title='`+Translation('حذف')+`'>
                                                <i class='icon-trash'></i>
                                            </a>
                                        </li>
                                        
                                    </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
            },
            
            

           
        ],
        "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>`);   
         $("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();
        });
    });


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


});



