<style>
    .processing-indicator {
        display: flex;
        gap: 6px;
    }

    .processing-dot {
        width: 10px;
        height: 10px;
        background: #2196F3;
        border-radius: 50%;
        animation: bounce 1.4s infinite ease-in-out;
    }

    .processing-dot:nth-child(2) {
        animation-delay: 0.2s;
    }

    .processing-dot:nth-child(3) {
        animation-delay: 0.4s;
    }

    @keyframes bounce {
        0%, 80%, 100% {
            transform: translateY(0);
        }
        40% {
            transform: translateY(-12px);
        }
    }

  #fullpage-loading {
    display: none;
    position: fixed;
    z-index: 9999;
    top: 0; left: 0;
    width: 100vw; height: 100vh;
    background: rgba(0, 0, 0, 0.712);
    align-items: center;
    justify-content: center;
  }

</style>

<div class="container-fluid h-100">
<% if !@print_settings.nil? %>
    <% if @print_settings.precision.to_i > 0
        precision = @print_settings.precision
    else
        precision = 0
    end
    #check delimiter
    if @print_settings.delimiter
        delimiter = ","
    else
        delimiter = ""
    end
    %>
<% end %>

<div id="fullpage-loading" style="display:none; position:fixed; z-index:9999; top:0; left:0; width:100vw; height:100vh; background:rgba(0,0,0,0.35); align-items:center; justify-content:center;">
  <div>
    <div style="display:flex; gap:10px; justify-content:center;">
      <div class="processing-dot"></div>
      <div class="processing-dot"></div>
      <div class="processing-dot"></div>
    </div>
    <div style="color:white; text-align:center; margin-top:1rem; font-size:1.2rem;">Please Wait...</div>
  </div>
</div>

<div class="row clearfix h-100">
    <% if @error %>
        <input type="hidden" name="error_message" id="error_message" value="<%= json_escape(@error.to_json) %>">
    <% end %>

    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 d-flex flex-column h-100">
    <div class="card h-100" style="margin-bottom: 15px">
        <div class="card-header m-l-5 m-r-5">
        <div id="order-title">
            <div class="row p-l-5 p-r-5">
            <div class="col-lg-6 col-md-6 col-sm-6"><strong>Receipt No :</strong> <span id="receipt_no"><%=@sale_data.receipt_no rescue ' '%></span></div>
            <div class="col-lg-6 col-md-6 col-sm-6 text-left"><strong>Receipt Date :</strong> <span id="receipt_date"><%=@sale_data.receipt_date.strftime("%d/%m/%Y-%I:%M %p") rescue '-' %></span></div>
            </div>
            <div class="row p-l-5 p-r-5">
            <div class="col-lg-6 col-md-6 col-sm-6"><strong>Table No :</strong> <%=@table_no%></div>
            <span class="hidden" id="dining"><%if !@dining.nil?%><%= @dining.id%><%end%></span>
            <div class="col-lg-6 col-md-6 col-sm-6 text-left"><strong>Sale ID :</strong> <span id="sale_id"><% if @sale_data %><%=@sale_data.sale_id %><% end %></span></div>
            </div>

            <div class="row p-l-5 p-r-5">

            <div class="col-lg-6 col-md-6 col-sm-6 text-left"><strong>Checkin Time : </strong> <%if !@checkin_time.nil?%><%= @checkin_time.strftime("%I:%M %p") %>
            <%end%></div>
            </div>
        </div>
        </div>

        <div class="card-block m-l-5 m-r-5 m-t--10 d-flex flex-column h-100">
        <div class="card-title">
            <div class="card-text">
            <table class="table" id="append-table">
                <tr>
                <!-- <tr> -->
                <th>#</th>
                <th class="item-name">Items</th>
                <th class="item-attr">QTY</th>
                <th class="item-attr">Price</th>
                <!-- </tr> -->
                </tr>
            </table>
            </div>
        </div>
        <div id="foodcourt-slimscroll" class="h-100">
            <!-- <div id="table-details" class="card-text" style="min-height:400px; max-height:400px; overflow-x:scroll"> -->
            <div id="table-details" class="card-text m-t--10" >
            <table class="table summary-items" id="append-table">
                <tbody>
                <% sub_total = 0
                count = 0
                %>
                <% @sale_data.sale_items.each do |sale_item|
                    count += 1
                    %>

                    <% sub_total += sale_item.price%>
                    <tr>
                    <td><%= count %></td>
                    <td class="item-name"><%=sale_item.product_name%>@<%=number_with_precision( sale_item.unit_price, precision: precision.to_i )%></td>
                    <td class="item-attr"><%=sale_item.qty%></td>
                    <td class="item-attr"><%=(number_with_precision(sale_item.price, precision: precision.to_i ))%></td>
                </tr>
                <%end %>
            </tbody>
            </table>
        </div>
        </div>
    </div>
    <div class="card-footer ">
        <table class="table m-t--10 ">
        <tfooter>
            <tr>
            <td class="charges-name"><strong>Sub Total</strong></td>
            <td class="item-attr"><strong><span id="sub-total"><%=number_with_precision(sub_total, precision: precision.to_i)%></span></strong></td>
            </tr>
            <tr>
            <%if @sale_data.discount_type == 'member_discount'%>
            <td class="charges-name"><strong>Member Discount:</strong></td>
            <%else%>
            <td class="charges-name"><strong>(Discount)</strong></td>
            <%end%>
            <td class="item-attr"><strong><span>(<%= number_with_precision(@sale_data.total_discount, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i ) %>)</span></strong></td>
            </tr>
            <tr>
            <td class="charges-name">
                <strong>
                <% if !@account_arr.empty? %>
                Tax
                (<% @i = 0
                @account_arr.each do |ct| %>
                    <%=ct.tax_name%>
                    <% if @account_arr.count != @i+1%>
                    +       <% @i =+1 %>
                    <%end%>
                <%end %>)
                <% else %>
                No Tax
                <% end %></strong><br>
                <%if @changable_tax %>
                <% if @current_user.role == 'cashier' %>
                    <button class="btn btn-link waves-effect bg-info access_modal" data-type = 'change_tax' >Change Tax</button>
                <% else %>
                    <button class="btn btn-link waves-effect bg-info change_tax">Change Tax</button>
                <% end %>
                <% end %>
            </td>

            <td class="item-attr"><strong><span id="total_tax"><%= number_with_precision(@sale_data.total_tax, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i )%></span></strong></td>
            </tr>
            <tr>
            <td class="charges-name"><strong>Rounding Adj:</strong></td>
            <td class="item-attr"><strong><%= number_with_precision(@sale_data.rounding_adjustment, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i )%></strong></td>
            </tr>
            <tr>
            <td class="charges-name"><strong>Grand Total</strong></td>
            <td class="item-attr"><strong><span><%= number_with_precision(@sale_data.grand_total, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i )%></span></strong></td>
            </tr>
            <%if @balance > 0%>
            <tr>
            <td class="charges-name"><strong><%= @accountable_type %></strong></td>
            <td class="item-attr"><strong><span><%=number_with_precision(@balance, precision: precision.to_i )%></span></strong></td>
            </tr>
            <% end %>
            <% if !@individual_total[0].nil? %>
            <tr>
                <td class="charges-name">
                    <strong>Split Bill for <%= @individual_total[0]['total_customer'] %> persons</strong>
                </td>
                <td></td>
            </tr>
            <tr>
                <td class="charges-name">
                    <strong>Amount Due (per person)</strong>
                </td>
                <td class="item-attr"><strong><span><%= number_with_precision(@individual_total[0]['per_person_amount'], precision: precision.to_i )%></span></strong></td>
            </tr>
            <% end %>
        </tfooter>
        </table>
    </div>
</div>
</div>

<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5 d-flex flex-column h-100" style="padding-right: 10px;">
  <div class="card h-100" style="margin-bottom: 15px">
    <div class="card-header">
    <div class="d-flex justify-content-center align-items-center">
        <img src="/image/mmqr.webp" alt="MMQR Payment" style="max-width: 120px; margin-bottom: 10px;">
    </div>
    <hr>
      <div class="row m-l-5 m-r-5 m-t-20" style="padding-bottom: 14px;">
        <div class="col-md-8"><strong class='amount_balance' style="font-size: 30px">Amount Due: <% if !@sale_payment.nil? %>( Credit )<% end %></strong></div>
        <div class="col-md-4 text-right">
          <strong>
            <span id="grand_total" class="hidden">
              <% if @sale_payment.nil? %>
                <%= number_with_precision(@sale_data.grand_total, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i)%>
              <% else %>
                <%= number_with_precision(@sale_payment[0].payment_amount, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i)%>
              <% end %>
            </span>
            <span id="amount_due" style="font-size: 30px">
              <% if @sale_payment.nil? %>
                <%= number_with_precision(@sale_data.grand_total, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i ) %>
              <% else %>
                <%= number_with_precision(@sale_payment[0].payment_amount, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i)%>
              <% end %>
            </span>
          </strong>
        </div>
      </div>
    </div>

    <div class="card-block">
      <input type="hidden" name="server_mode" value="<%=ENV["SERVER_MODE"]%>" id="server_mode">
      <input type="hidden" name="display_type" id="display_type" value="<%= @display_type%>">
      <button type="button" class="btn btn-block btn-lg waves-effect btn_qrpay pay" style="background-color: #ffc107;">[ Complete Payment With MMQR ]</button>
    </div>
  </div>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
  <%= link_to '/foodcourt/app_orders', class: 'btn btn-block btn-default waves-effect', :id => 'foodcourt_back', style: "padding-top: 0;" do%>
    <i class="material-icons">reply</i>
    BACK
  <% end %>
  <button type="button" class="btn btn-block btn-default waves-effect" id='refresh'>
     Refresh
  </button>
  <% if @sale_payment.nil? %>
    <hr>
    <% if current_login_employee.role == "cashier" %>
      <a class="btn btn-block bg-red waves-effect access_modal" data-toggle="modal"  data-type="void"> Void</a>
      <a class="btn btn-block bg-blue waves-effect access_modal" data-toggle="modal"   data-type="edit">Edit</a>
    <% else %>
      <button type="button" class="btn bg-red btn-block" data-toggle="modal" data-target="#voidModal" <%= (can? :overall_void, :void)? ' ': 'disabled=' %> > Void </button>
      <button type="button" class="btn btn-block bg-blue waves-effect" id='edit' <%= (can? :edit, :sale_edit)? ' ': 'disabled=' %> active="true">Edit</button>
    <% end %>
    <button type="button" id="discount" class="btn btn-block bg-blue waves-effect" <%= (can? :index, :discount)? ' ': 'disabled=' %> active="true">Discount</button>
    <button type="button" id="other-charges" class="btn btn-block bg-blue waves-effect">Charges</button>
  <%end %>
</div>
<input type="hidden" id="server_mode" value="<%= ENV["SERVER_MODE"] %>">
<div class="modal fade" id="voidModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      <h4 class="modal-title" id="voidModalLabel">Please Enter Reason for Void</h4>
      </div>
      <div class="modal-body">
         <input type="textarea" name="remark" class="form-control col-md-12 remark" id="remark">
      </div>
      <div class="modal-footer ">
        <div class="row p-r-20">
          <div class="col-md-5">
            <button type="button" class="btn btn-link  p-t-5 p-b-5 bg-red waves-effect " id="void" active="true">VOID</button>
          </div>
          <div class="col-md-5">
            <button type="button" class="btn btn-link  p-t-5 p-b-5 bg-blue waves-effect" data-dismiss="modal">CLOSE</button>
          </div>
        </div>

      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="focModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      <h4 class="modal-title" id="focModalLabel">Please Enter Reason for FOC</h4>
      </div>
      <div class="modal-body">
         <input type="textarea" name="remark" class="form-control col-md-12 remark" id="foc_remark">
      </div>
      <div class="modal-footer ">
        <div class="row p-r-20">
          <div class="col-md-5">
            <button type="button" class="btn btn-link bg-red waves-effect " id="foc" active="true">FOC</button>
          </div>
          <div class="col-md-5">
            <button type="button" class="btn btn-link bg-blue waves-effect" data-dismiss="modal">CLOSE</button>
          </div>
        </div>

      </div>
    </div>
  </div>
</div>

<div class="modal fade" id="is_memberModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-md" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title" id="is_memberModalLabel">Are you member?</h1>
      </div>
      <div class="modal-body">
        <input type="hidden" name="qr_code" id="qr_code" />
        <div class="row text-center m-t-20">
          <% if !@customer_lists.nil? %>
            <% @customer_lists.each do |cus| %>
              <% if cus.customer_id != @customer.id %>
                <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
                  <button type="button" class="btn btn-lg btn-link bg-primary waves-effect btn_customer_assign" data-id='<%= cus.customer_id %>'><%= cus.name %></button>
                </div>
              <% end %>
            <% end %>
          <% end %>
        </div>
        <div class="row text-center m-t-20">
          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <button type="button" class="btn btn-lg btn-link bg-primary waves-effect btn_member">Card Member</button>
          </div>

          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <button type="button" class="btn btn-lg btn-link bg-primary waves-effect btn_qr_code">QR Code</button>
          </div>
        </div>
        <div class="row clearfix"></div>
        <div class="row text-center m-t-20">
          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <button type="button" class="btn btn-lg btn-link bg-green waves-effect btn_customer_yes">Yes</button>
          </div>

          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <button type="button" class="btn btn-lg btn-link bg-red waves-effect" data-dismiss="modal">No</button>
          </div>
        </div>
      </div>
      <div class="modal-footer"></div>
    </div>
  </div>
</div>

<div class="modal fade" id="AccessCodeModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
      <h4 class="modal-title" id="AccessCodeModalLabel">Enter Access Code</h4>
      <button type="button" class="close" id="close" data-dismiss="modal" aria-hidden="true" style="font-size: 20px;color:#111;">&times;</button>
      </div>
      <div class="modal-body" style="padding: 0px 25px 15px 25px !important">
         <input type="password" id="access_code" class="access_code form-control col-md-12 ">
        <div class="row bottom p-l-15 p-r-15 m-t-10">
             <div class="col-md-3 access_number border-top border-left" data-value="1" data-type="num">1</div>
             <div class="col-md-3 access_number border-top border-left" data-value="2" data-type="num">2</div>
             <div class="col-md-3 access_number border-top border-left" data-value="3" data-type="num">3</div>
             <div class="col-md-3 access_number border-top border-left" data-value="4" data-type="num">4</div>
           </div>
           <div class="row bottom p-l-15 p-r-15">
             <div class="col-md-3 access_number border-top border-left" data-value="5" data-type="num">5</div>
             <div class="col-md-3 access_number border-top border-left" data-value="6" data-type="num">6</div>
             <div class="col-md-3 access_number border-top border-left" data-value="7" data-type="num">7</div>
             <div class="col-md-3 access_number border-top border-left" data-value="8" data-type="num">8</div>
           </div>
           <div class="row bottom p-l-15 p-r-15">
             <div class="col-md-3 access_number border-top border-left" data-value="9" data-type="num">9</div>
             <div class="col-md-3 access_number border-top border-left" data-value="0" data-type="num">0</div>
             <div class="col-md-3 access_number border-top border-left orange" data-type="clr">Clr</div>
             <div class="col-md-3 access_number ok border-top border-left blue" data-type="ok" data-action="">OK</div>

           </div>
      </div>
    </div>
  </div>
</div>

<!-- change tax modal -->
<div class="modal fade" id="change_taxModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-md" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title" id="change_taxModalLabel">TAX</h1>
        <button type="button" class="close" id="close" data-dismiss="modal" aria-hidden="true" style="font-size: 20px;color:#111;">&times;</button>
      </div>
      <div class="modal-body">
          <% if !@tax_arr.empty? %>
            <% if @tax_arr.count > 1 %>
            <div class="row text-center">
              <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
                  <button type="button" class="btn btn-lg tax-btn-box btn-link bg-primary waves-effect" name="tax_type" data-value="all">
                  <% @i = 0
                  @tax_arr.each do |tax| %>
                    <%= tax %>
                    <% if @tax_arr.count != @i+1%>
                      + <% @i =+1 %><br>
                    <%end%>
                  <% end %>
                  </button>
              </div>

              <% @tax_arr.each_with_index do |tax, tax_index| %>
                <% if (tax_index+1)%2 == 0 %>
                  <div class="row clearfix"></div>
                <% end %>
                  <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
                    <button type="button" class="btn btn-lg tax-btn-box btn-link bg-primary waves-effect" name="tax_type" data-value="<%= tax %>">
                      <%= tax %>
                    </button>
                  </div>
              <% end %>
            <% else %>
            <div class="row clearfix"></div>
            <div class="row text-center">
              <% @tax_arr.each do |tax| %>
                <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
                  <button type="button" class="btn btn-lg tax-btn-box btn-link bg-primary waves-effect" name="tax_type" data-value="<%= tax %>"><%= tax %></button>
                </div>
              <% end %>
            <% end %>
          <% end %>
            <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
              <button type="button" class="btn btn-lg tax-btn-box btn-link bg-primary waves-effect" name="tax_type" data-value="no_tax">No Tax</button>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer"></div>
    </div>
  </div>
</div>

<%= render "layouts/read_modal" %>

<script type="text/javascript">
// //control borwser back
window.location.hash="no-back-button";
window.location.hash="Again-No-back-button";//again because google chrome don't insert first hash into history
window.onhashchange=function(){window.location.hash="";}
var cashier_type = "<%= @cashier_type %>";
var customer_id = "<%= @customer.id %>";
var customer_name = "<%= @customer.name %>";
var pdf_view = '<%=@pdf_view%>';
var trans_flag = <%= @trans_flag %>;
var paymalcount = <%= @paymalcount %>;
var customer_paypar_account = '<%= @sale_data.customer.paypar_account_no %>';
// console.log(pdf_view)
$(document).ready(function(){

  $.post('/foodcourt/customer_view', {
    data: {
      items: <%= raw @sale_data.sale_items.to_json %>,
      subtotal: <%= number_with_precision(@sale_data.total_amount, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i) %>,
      total_discount: <%= number_with_precision(@sale_data.total_discount, precision: precision.to_i) rescue number_with_precision(0, precision: precision.to_i) %>,
      total_tax: <%= number_with_precision(@sale_data.total_tax, precision: precision.to_i) rescue number_with_precision(0, precision: precision.to_i) %>,
      grand_total: <%= number_with_precision(@sale_data.grand_total, precision: precision.to_i ) rescue number_with_precision(0, precision: precision.to_i) %>,
    },
    status: "reload_and_update"
  }, function(result) {}, 'json');


    $("#read_modal").modal('hide');
    /* replace url type*/
    if(!trans_flag){
      localStorage.setItem("trans_flag", trans_flag);
      var sale_id = $('#sale_id').text();
      window.location.replace('/foodcourt/sale/'+sale_id+'/cashier/payment');
    }
    /* replace url type*/
    /* start check first bill or not*/
        var member_id = $('#membership_id').text();
        var member_discount = $('#member_discount').text();
        var receipt_no = "";
        if(($("#receipt_no").html()!=undefined) && ($("#receipt_no").html()!="")){
          receipt_no = ($("#receipt_no").html()).trim();
        }
        $("#card_payment").show();
    var dining_id = "<%= @sale_data.bookings[0].dining_facility_id %>";

    $("#foodcourt_back").on('click', function() {
      localStorage.removeItem('cash');
      customer_display_view(null,"reload");
      // var sale_id = $('#sale_id').text();
      // var flag = localStorage.getItem("trans_flag");
      // if((flag!=null) && (flag != "true")){
      //   window.location.href = '/transactions/sales/'+sale_id;
      // }else{
      //   if (cashier_type=="cashier") {
      //       window.location.href = '/foodcourt/table/'+ dining_id;
      //   }else{
      //     window.location.href = '/foodcourt/'+cashier_type+'/pending_order/'+sale_id;
      //   }
      // }

    });

    if(localStorage.getItem("cash") != null && localStorage.getItem("cash") != 'null'){
      $('#cash').text(localStorage.getItem("cash"));
    }
    update_balance();
    //checkChangableTax
    checkChangableTax();

    // Disable click event cash to prevent
    $(".payment .cash-color").off('click');

    window.customer_display_view = function(data,status) {
     url = '/foodcourt/customer_view';
      $.ajax({
        type: "POST",
        url: url,
        data: {"data":data,"status":status},
        dataType: "json",
        success:function(result){
        }
      });
    }

  });

  // bind survey to order or sale
  $("#survey").on('click', function () {
    var sale = $('#sale_id').text();
    if (sale) {
      var sale_id = sale
    } else {
      var sale_id = $('#dining').text();
    }
    //var table_id = $('.tables').attr("data-id");
     window.location.href = '/foodcourt/' + sale_id +"/"+ cashier_type + "/surveys";
  });

  // bind customer to order or sale
  $("#customer").on('click', function () {
    var sale = $('#sale_id').text();
    if (sale) {
      var sale_id = sale
    } else {
      var sale_id = $('#save_order_id').attr('data-order');
     }
    var table_id = $('.tables').attr("data-id");
    window.location.href = '/foodcourt/' + sale_id + "/"+cashier_type+"/customers/payment";
  });

  // Add Other Charges
  $('#other-charges').click(function () {
    var sale = $('#sale_id').text();
    if (sale != "") {
      var sale_id = sale
    } else {
      var sale_id = $('#save_order_id').attr('data-order');
    }
    if (sale_id != "") {
      window.location.href = '/foodcourt/' + sale_id +"/"+cashier_type+ '/other_charges?payment_type=qr'
    }
    else {
      swal ( "Oops" ,  "Please select an table!" ,  "warning" );
    }
    return false;
  });
  // Discount for Payment
  $('#discount').click(function () {
    if ($(this).attr('active')=== "true") {
      var sale = $('#sale_id').text();
      if (sale != "") {
        var sale_id = sale
      } else {
        var sale_id = $('#save_order_id').attr('data-order');
      }

      if (sale_id != "") {
        window.location.href = '/foodcourt/' + sale_id + "/"+cashier_type+'/discount?payment_type=qr'
      }
      else {
        swal ( "Oops" ,  "Please select an table!" ,  "warning" );
      }
    }else{
      swal("Oops","You are not authorized for Discount","warning")
    }
    return false;
  });

  $('#edit').on('click', function () {
    var dining_id = $('#dining').text();
    var sale_id = $('#sale_id').text();
    if ($(this).attr('active')=== "true") {
      if (dining_id) {
        window.location.href = '/foodcourt/table/' + dining_id + "/sale/" + sale_id + "/"+cashier_type+"/edit?payment_type=qr";
      }else{
        window.location.href = "/foodcourt/table/sale/" + sale_id + "/"+cashier_type+"/edit?payment_type=qr";
      }

    }else{
      swal("Oops","You are not authorized for void","warning")
    }
  });

 <% if @cash_exist%>
  $(document).on('click', '.cashier_number', function(event){
    if(event.handled !== true) {
      var original_value;
      original_value = parseFloat($('#cash').text());

      var input_type = $(this).attr("data-type");

      switch (input_type) {
        case 'num':
        var input_value = $(this).attr("data-value");
        if (original_value == "0.0"){
          $('#cash').text(input_value);
          update_balance();
        }else{
          if($('#cash').text() == '0'){
            $('#cash').text("");
          }
          $('#cash').append(input_value);
          update_balance();
        }
        break;
        case 'add':
          var input_value = $(this).attr("data-value");
          amount = parseInt(input_value) + parseInt(original_value);
          $('#cash').text(amount);
          update_balance();
          break;
        case 'del' :
          var cash=$('#cash').text();
          if(cash.length == 1)
            $('#cash').text("0.0");
        else
          $('#cash').text(cash.substr(0,cash.length-1));
          update_balance();
          break;
        case 'clr':
          $('#cash').text("0.0");
          update_balance();
          break;
        case 'nett':
          var credit1 = $('#credit').text();
          var card1 = $('#others').text();
          var paypar1 = $('#ppamount').text();
          var visa1 = $('#visacount').text();
          var jcb1 = $('#jcbcount').text();
          var master1 = $('#mastercount').text();
          var unionpay1 = $('#unionpaycount').text();
          var paymal1 = $('#paymalcount').text();
          var alipay1 = $('#alipaycount').text();
          var junctionpay1 = $('#junctionpaycount').text();
          var dingapay1 = $('#dingacount').text();
          var giftvoucherpay1 = $('#giftvouchercount').text();
          var othertotal = parseFloat(credit1) + parseFloat(card1) + parseFloat(paypar1) + parseFloat(visa1) + parseFloat(jcb1) + parseFloat(master1) + parseFloat(unionpay1) + parseFloat(alipay1) + parseFloat(junctionpay1) + parseFloat(paymal1) + parseFloat(dingapay1) + parseFloat(giftvoucherpay1);
          var total = $('#amount_due').text();
          var amt = 0;
          <% if precision.to_i > 0 %>;
            amt = parseFloat(parseFloat(total) - parseFloat(othertotal)).toFixed(<%= precision %>);
          <% else %>
            amt = parseFloat(parseFloat(total) - parseFloat(othertotal));
          <% end %>
          $('#cash').text(amt);
          update_balance();
        break;
      }
      event.handled = true;
    } else {
      return false;
    }
  });
<%end%>

  function update_balance(){
    var cash = $('#cash').text();
    var credit = $('#credit').text();
    var card = $('#others').text();
    var paypar = $('#ppamount').text();
    var visa = $('#visacount').text();
    var jcb = $('#jcbcount').text();
    var master = $('#mastercount').text();
    var unionpay = $('#unionpaycount').text();
    var paymal = $('#paymalcount').text();
    var alipay = $('#alipaycount').text();
    var junctionpay = $('#junctionpaycount').text();
    var dinga = $('#dingacount').text();
    var giftvoucher = $('#giftvouchercount').text();
    var amount_due = $('#amount_due').text();
    var total = parseFloat(cash) + parseFloat(credit) + parseFloat(card) + parseFloat(paypar) + parseFloat(visa) + parseFloat(jcb) + parseFloat(master) + parseFloat(unionpay) + parseFloat(alipay) + parseFloat(junctionpay) + parseFloat(paymal) + parseFloat(dinga) + parseFloat(giftvoucher);

    var result = parseFloat(amount_due) - parseFloat(total);

    <% if precision.to_i > 0 %>
      $('#balance').text(parseFloat(result).toFixed(<%= precision %>));
    <% else %>
      $('#balance').text(parseFloat(result));
    <% end %>
  }

  function customer_display_view(data,status) {
     $.ajax({
        type: "POST",
        url: '../../../customer_view',
        data: {"data":data,"status":status},
        dataType: "json",
        success:function(result){
        }
      });
  }

  function calculate_member_discount(sale_id,tax_type) {
    alert('function called')
   var sub_total = $('#sub-total').text();
   var member_id = $('#membership_id').text();
   var member_discount = $('#member_discount').text();
   var item_row  = $('.is_card');
   if (member_id && member_discount) {
     if (item_row.length < 1) {
       is_card = false
     }else{
      is_card = true
     }
      $.ajax({
        type: "POST",
        url: "/foodcourt/" + sale_id + "/member_discount",
        data: {'sale_id':sale_id, 'sub_total':sub_total,'is_card':is_card,'cashier_type':cashier_type, 'tax_type':tax_type },
        async: false,
        success:function(result){
        }
      });
    }
  }

  $(".btn_customer_yes").on('click',function(){
    var sale_id = $('#sale_id').text();
    window.location.href = "/foodcourt/"+sale_id+"/"+cashier_type+"/customers/payment";
  });

  // Read Card Reader
  $(".btn_member").on('click', function(){
    $("#is_memberModal").hide();
    $("#read_modal").attr('data-for', 'member');
    $("#read_modal").show();
    getCardNo();

    onScan.attachTo(document, {
      onScan: function(sCode) {
        setCardNo(sCode)
      }
    });
  });

  function pay_with_card(cardNo) {
    var sale_id    = $("#sale_id").text() || 0;
    var receipt_no = "";
    if(($("#receipt_no").html() != undefined) && ($("#receipt_no").html()!="")){
      receipt_no = ($("#receipt_no").html()).trim();
    }

    var customer_mamber_card_no = 0;
    var payment_amount = parseFloat($("#grand_total").text());
    customer_mamber_card_no = cardNo;
    if (customer_mamber_card_no == 0) {
      customer_mamber_card_no = $("#membership_id").text() || 0;
    }
    if(sale_id != 0 && customer_mamber_card_no !=0){
      $("#loading_wrapper").show();
      $.ajax({
        type: "POST",
        url: "/foodcourt/"+sale_id+"/send_account" ,
        data: { account_no : customer_mamber_card_no, amount : payment_amount, receipt_no : receipt_no},
        dataType: "json",
        success: function(data) {
          if (data.status == true) {
            var customer_card_balance= data.balance;
            var valid_amount = parseFloat(data.old_balance_amount) - parseFloat(data.reload_amount);
            // $("#valid_amount").val((valid_amount > 0) ? parseFloat(valid_amount) : 0);
              $.ajax({
                type: "POST",
                url:  "<%=foodcourt_payment_paymal_path%>",
                data: {payment_amount:payment_amount,membership_id:0,sale_id:sale_id,transaction_ref:data.transaction_ref,account_no:customer_mamber_card_no},
                success: function(result){
                  if(result.status == true){
                    sub_total = $('#sub-total').text();
                    member = $('#membership_id').text();

                    $( "#loading_wrapper").show();
                    var sale_id   = $('#sale_id').text();
                    // var item_row  = $('.is_card');

                    if(($("#receipt_no").html()!=undefined) && ($("#receipt_no").html()!="")){
                      var receipt_no = ($("#receipt_no").html()).trim();
                      deleteReceiptNoInFirstBillData(receipt_no);
                    }

                    $("#loading_wrapper").hide();

                    var second_display_lookup = $("#display_type").val();
                    if ($('#server_mode').val() != "cloud" && second_display_lookup == 2){
                      customer_display_view(null,"reload");
                    }

                    swal({
                      title: "Payment Successful!",
                      text: "Thank You !",
                      type: 'success',
                      html: true,
                      closeOnConfirm: true,
                      closeOnCancel: false,
                      allowOutsideClick: false
                    },
                    function (isConfirm) {
                      $("#loading_wrapper").show();
                      $('.confirm').attr("disabled","disabled");
                      window.location.href = "<%= foodcourt_food_court_path %>";
                    });
                  } else {
                    var insufficient_message = result.message + '<br> Card balance :  ' + customer_card_balance
                    swal({
                      title: 'Oops',
                      text: insufficient_message,
                      type: 'warning',
                      html: true,
                      closeOnConfirm: false,
                      closeOnCancel: false,
                      allowOutsideClick: false
                    }, function () {
                      window.location.href = '/foodcourt/food_court';
                    });
                    $("#loading_wrapper").hide();
                  }
              }
            });
          }else{
            swal({
              title: 'Oops',
              text: data.message,
              type: 'error',
              html: true,
              closeOnConfirm: false,
              closeOnCancel: false,
              allowOutsideClick: false
            }, function () {
              window.location.href = '/foodcourt/sale/'+ sale_id +"/"+cashier_type + "/payment";
            });
            $("#loading_wrapper").hide();
          }
        }
      });
    }else{
      swal({
        title: 'Oops',
        text: 'Please Check Member',
        type: 'warning',
        html: true,
        closeOnConfirm: false,
        closeOnCancel: false,
        allowOutsideClick: false
      }, function () {
        window.location.href = '/foodcourt/sale/'+ sale_id +"/"+cashier_type + "/payment";
      });
      $("#loading_wrapper").hide();
    }
  }

  function member_card(cardNo) {
    var customer_id = '';
    var customer_name = '';
    var membership_id = '';
    var membership_type = '';
    var sale_id     = $("#sale_id").text() || 0;

    if(sale_id != 0 && cardNo != 0){
      $.ajax({
        type: "POST",
        url: "/foodcourt/"+sale_id+"/get_customer" ,
        data: { filter : cardNo ,type :"card"},
        dataType: "json",
        success: function(data) {
          if (data[0].customer_id == false) {
            swal("Alert!", data[0].message, "error");
          }else{
            customer_id = data[0].customer_id;
            customer_name = data[0].name;
            membership_id = data[0].membership_id;
            membership_type = data[0].membership_type;
            update_sale(membership_id, customer_id, customer_name,sale_id);
          }

        }
      });
    }
  }

  // Read NFC card no from java
  function getCardNo(){
    if(typeof code2lab != 'undefined'){
      code2lab.readNFC();
    }
  }

  // get CardNo from Java
  function setCardNo(cardNo){
    if(cardNo.length == 16){
      $("#paypar_account_no").val(cardNo);
      if ($("#read_modal").attr("data-for") == 'member') {
        member_card(cardNo);
      } else if ($("#read_modal").attr('data-for') == 'payment') {
        pay_with_card(cardNo);
      }
      $("#read_modal").modal('hide');
    }
  }

  // QR Code Reader
  $(".btn_qr_code").on('click', function(e){
    $("#is_memberModal").hide();
    var code = "";
    var customer_id = '';
    var customer_name = '';
    var membership_id = '';
    var membership_type = '';
    setTimeout(function(){
      code=getQRCode();
      $("#qr_code").val(code);
    });

    if(sale_id != 0 && code != ""){
      $.ajax({
        type: "POST",
        url: "/foodcourt/"+sale_id+"/get_customer" ,
        data: { filter : code ,type :"card"},
        dataType: "json",
        success: function(data) {
          if (data[0].customer_id == false) {
            swal("Alert!", data[0].message, "error");
          }else{
            customer_id = data[0].customer_id;
            customer_name = data[0].name;
            membership_id = data[0].membership_id;
            membership_type = data[0].membership_type;
            update_sale(membership_id, customer_id, customer_name,sale_id);
          }

        }
      });
    }
  });

  // Read qrcode from java
  function getQRCode(){
    return code2lab.readQRCode();
  }

  function update_sale(membership_id, customer_id, customer_name, sale_id) {
    var customer="";
    if(customer_name != ""){
      customer = '(' + customer_name + ')';
    }
    $("#loading_wrapper").show();

    $.ajax({
      type: "POST",
      url: "/foodcourt/"+sale_id+"/"+cashier_type+"/customers/update_sale" ,
      data: {customer_id:customer_id,sale_id:sale_id},
      dataType: "json",
      success: function(data) {
        if(data.status == true)
        {
          //change customer detail
          $("#customer_name").html(customer_name);
          $("#membership_id").html(membership_id);
          window.location.href = '/foodcourt/sale/'+sale_id+'/'+cashier_type+'/payment/';
        }else{
          swal("Alert!", "Record not found!", "error");
          location.reload();
        }
      }
    });
  }

  $("#read_modal #close").on('click',function(){
    $("#read_modal").modal('hide');
  });

  $(".btn_customer_assign").on('click', function(){
    var customer_id = $(this).attr('data-id');
    var customer_name = $(this).text();
    var sale_id     = $("#sale_id").text() || 0;
    update_sale("", customer_id, customer_name, sale_id);
  });
  $(document).on('click', '.access_modal', function(event){
      type = $(this).data("type");
      $(".ok").attr("data-action",type)
      $('#AccessCodeModal').modal('show');
  });

  function check_emp_access_code(access_code,type) {
      var url = "/foodcourt/check_emp_access_code/" + access_code ;
      $.ajax({
          type: 'POST',
          url: url,
          data: {},
          success: function (result) {
            // console.log(result)
             if (result.status == true) {
              createAccessCode(code);
               if (type == "edit") {
                  var dining_id = $('#dining').text();
                  var sale_id = $('#sale_id').text();
                    window.location.href = "/foodcourt/table/sale/" + sale_id + "/"+cashier_type+"/edit?payment_type=qr";
               }else if(type == "void"){
                 $('#AccessCodeModal').modal('hide');
                 $('#voidModal').modal('show');
                 // overall_void();
               }else if(type == "waste") {
                 // $('#AccessCodeModal').modal('hide');
                 // $('#focModal').modal('show');
                  waste_and_spoilage("waste")
               }else if(type == "spoile") {
                 // $('#AccessCodeModal').modal('hide');
                 // $('#voidModal').modal('show');
                  waste_and_spoilage("spoile")
               }else if(type == "foc"){
                 $('#AccessCodeModal').modal('hide');
                 $('#focModal').modal('show');
                 // overall_foc();
               }else if(type == "change_tax"){
                  $('#AccessCodeModal').modal('hide');
                  $('#change_taxModal').modal('show');
               }
             }else{
               swal("Oops",result.message,"warning");
             }
          }
      });
  }
  $('#foc').on('click', function () {
    var access_code  = localStorage.getItem("access_code");
    var remark  = $("#foc_remark").val();
    var cash = $('#grand_total').text();
    var sub_total = $('#sub-total').text();
    var sale_id = $('#sale_id').text();
    var params = { 'cash':cash,'sale_id':sale_id,'sub_total':sub_total,'remark':remark,'type':cashier_type,'access_code':access_code };
    swal({
      title: "Alert",
      text: "Are you sure want to FOC this receipt?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Yes, FOC it!",
      closeOnConfirm: false
    }, function (isConfirm) {
      if (isConfirm) {
        $('.confirm').prop("disabled",true);
        $.ajax({
          type: "POST",
          url: "/foodcourt/payment/"+cashier_type+"/foc",
          data: params,
          success:function(result){
            $('#focModal').modal('hide');
            customer_display_view(null,"reload");
            if (cash >= 0) {
              swal({
               title: "Information!",
               text: 'Thank You !',
               type: "success",
             }, function () {
                // For Server Print - from jade
                if ($("#server_mode").val() == "cloud") {
                  if(typeof code2lab != 'undefined'){
                    code2lab.printFile(result.filepath.substr(6), result.printer_url);
                  }
                }
                var flag = localStorage.getItem("trans_flag");
                if((flag!=null) && (flag != "true")){
                  window.location.href = '/transactions/sales/'+sale_id;
                }else{
                  if (cashier_type=="cashier") {
                    window.location.href = '/foodcourt';
                  }else{
                    window.location.href = '/foodcourt/'+cashier_type;
                  }
                }
             });
            }
          }
        });
      }
    });
  });

  function waste_and_spoilage(remark) {
    var access_code  = localStorage.getItem("access_code");
    var sale_id = $('#sale_id').text();
    swal({
      title: "Alert",
      text: "Are you sure want to " + remark +" ?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Yes, " +remark+ " it!",
      closeOnConfirm: false
    }, function (isConfirm) {
      if (isConfirm) {
        $('.confirm').prop("disabled",true);
        var url = "/foodcourt/sale/" + sale_id +'/'+cashier_type+'/waste_and_spoilage';
        $.ajax({
          type: 'POST',
          url: url,
          data: "remark="+ remark + "&sale_id=" + sale_id+ "&access_code=" + access_code,
          success: function (result) {
            // console.log(result)
             // For Server Print - from jade
             if ($("#server_mode").val() == "cloud") {
              if(typeof code2lab != 'undefined'){
                code2lab.printFile(result.filepath.substr(6), result.printer_url);
              }
            }
            var flag = localStorage.getItem("trans_flag");
            if((flag!=null) && (flag != "true")){
              window.location.href = '/transactions/sales/'+sale_id;
            }else{
              if (cashier_type=="cashier") {
                window.location.href = '/foodcourt';
              }else{
                window.location.href = '/foodcourt/'+cashier_type;
                if(cashier_type=="quick_service" || cashier_type == 'food_court'){
                  customer_display_view(null,"reload");
                }
              }
            }
          }
        });
      }
    });
  }

  /* Start function for tax changable */
  $(".change_tax").on("click",function(){
    var balance = parseFloat($("#balance").text());
    var sub_total = parseFloat($("#sub-total").text());
    var total_tax = parseFloat($("#total_tax").text());
    if(balance > 0 && (balance >= total_tax)){
      $("#change_taxModal").modal({show: true, backdrop: false, keyboard: false});
    }
    else{
      swal("Oops","You cann't change tax!","warning");
    }
  });

  $("button[name=tax_type]").on("click", function(){
    var type = $(this).attr("data-value");
    var cashier_type = '<%= @cashier_type %>';
    var sale_id = $('#sale_id').text();
    localStorage.removeItem("tax_type");
    swal({
      title: "Alert",
      text: "Are you sure want to change tax?",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Yes, change it!",
      closeOnConfirm: false
    }, function (isConfirm) {
      if (isConfirm) {
        $('.confirm').prop("disabled",true);
        $.ajax({
          type: "POST",
          url: "/foodcourt/payment/"+cashier_type+"/change_tax",
          data: {sale_id: sale_id, cashier_type: cashier_type, tax_type: type},
          success:function(data){
            if(data.status){
              // console.log(type);
              localStorage.setItem("tax_type", type);
              window.location.reload();
            }
          }
        });
      }else{
        swal.close();
      }
    });
  });
  /* End function for tax changable */

  /* check change tax is available or not*/
  function checkChangableTax(){
    var balance = parseFloat($("#balance").text());
    var sub_total = parseFloat($("#sub-total").text());
    var total_tax = parseFloat($("#total_tax").text());
    if(balance > 0 && (balance >= total_tax)){
      $(".change_tax").show();
    }else{
      $(".change_tax").hide();
    }
  }

  /* customer light-box */
  $("#customer_name").on("click",function(){
    //start customer modal popup
    if((cashier_type=='quick_service' || cashier_type=='food_court') && (customer_id!=undefined) && (customer_id!=null) && (customer_id!="")){
      $("#read_modal").attr('data-for', 'member');
      $("#read_modal").show();
      getCardNo();

      onScan.attachTo(document, {
        onScan: function(sCode) {
          setCardNo(sCode)
        }
      });
    }
  });

  // $("#read_modal").on('shown.bs.modal', function(e) {
  //   if((cashier_type=='quick_service' || cashier_type=='food_court') && (customer_id!=undefined) && (customer_id!=null) && (customer_id!="")){
  //     $("#read_modal").attr('data-for', 'member');
  //     $("#read_modal").show();
  //     getCardNo();

  //     onScan.attachTo(document, {
  //       onScan: function(sCode) {
  //         setCardNo(sCode)
  //       }
  //     });
  //   }
  // });

function initDynamicQrPay() {
    var sale_id = $("#sale_id").text() || 0;
    window.location.href = `/foodcourt/${sale_id}/qrpay/init`;
}

  // Read Card Reader - Paymal payment for FoodCourt
  $(".btn_qrpay").on('click', function (){
    initDynamicQrPay();
  });

  // QR Code Reader
  $(".btn_paymal_qr_code").on('click', function(e){
    $("#is_paymemberModal").hide();
    var code = "";
    var sale_id     = $("#sale_id").text() || 0;
    var receipt_no = "";
    if(($("#receipt_no").html()!=undefined) && ($("#receipt_no").html()!="")){
      receipt_no = ($("#receipt_no").html()).trim();
    }
    var payment_amount = parseFloat($("#grand_total").text());
    setTimeout(function(){
      code=getQRCode();
      if(sale_id != 0 && code != ""){
         $.ajax({
          type: "POST",
          url: "/foodcourt/"+sale_id+"/send_account" ,
          data: { account_no : code, amount : payment_amount, receipt_no : receipt_no},
          dataType: "json",
          success: function(data) {
            if (data.status == true) {
              var valid_amount = parseFloat(data.old_balance_amount) - parseFloat(data.reload_amount);
              // $("#valid_amount").val((valid_amount > 0) ? parseFloat(valid_amount) : 0);

                $.ajax({
                type: "POST",
                url:  "<%=foodcourt_payment_paymal_path%>",
                data: {payment_amount:payment_amount,membership_id:0,sale_id:sale_id,transaction_ref:data.transaction_ref,account_no:code},
                success: function(result){
                  if(result.status == true){
                    swal({
                      title: "Information!",
                      text: result.message,
                      html: true,
                      closeOnConfirm: false,
                      closeOnCancel: false,
                      allowOutsideClick: false
                    }, function () {
                      window.location.href = '/foodcourt/sale/'+ sale_id  + "/"+cashier_type+"/payment";
                    });
                  }else{
                    swal({
                      title: 'Oops',
                      text: result.message,
                      type: 'warning',
                      html: true,
                      closeOnConfirm: false,
                      closeOnCancel: false,
                      allowOutsideClick: false
                    }, function () {
                      window.location.href = '/foodcourt/sale/'+ sale_id +"/"+cashier_type + "/payment";
                    });
                  }
                }
              });
            }else{
              swal({
                title: 'Oops',
                text: 'Please Check Member',
                type: 'warning',
                html: true,
                closeOnConfirm: false,
                closeOnCancel: false,
                allowOutsideClick: false
              }, function () {
                window.location.href = '/foodcourt/sale/'+ sale_id +"/"+cashier_type + "/payment";
              });
            }
          }
        });
      }
    },100);
  });
  $('#void').on('click', function () {
      var access_code  = localStorage.getItem("access_code");
     swal({
       title: "Alert",
       text: "Are you sure want to void?",
       type: "warning",
       showCancelButton: true,
       confirmButtonColor: "#DD6B55",
       confirmButtonText: "Yes, void it!",
       closeOnConfirm: false
     }, function (isConfirm) {
       if (isConfirm) {
         $('.confirm').prop("disabled",true);
         var sale_id = $('#sale_id').text();
         var remark  = $("#remark").val();
         var ajax_url = "/foodcourt/sale/" + sale_id +'/food_court/void';
         $.ajax({
           type: 'POST',
           url: ajax_url,
           data: "remark="+ remark + "&sale_id=" + sale_id+ "&access_code=" + access_code,
           success: function (result) {
             customer_display_view(null,"reload");
                 // For Server Print - from jade
                 if ($("#server_mode").val() == "cloud") {
                   if(typeof code2lab != 'undefined'){
                     code2lab.printFile(result.filepath.substr(6), result.printer_url);
                   }
                 }
                window.location.href = '/foodcourt/food_court';
              }
            })
       }
     });
   });
</script>
