<div class="container-fluid m-top-100">
  <div id="loading_wrapper" style="display:none;">
    <div id="loading"></div>
  </div>

  <div class="row clearfix">
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
      <div class="card">
        <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.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.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 %><%=@sale.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">
                <strong>Customer :</strong>
                <% if @cashier_type == 'quick_service' || @cashier_type == 'food_court' %>
                  <button type="button" class="btn bg-info waves-effect" id='customer_name'><%= @sale.customer.name%></button>
                <% else %>
                  <span id="customer_name"><%= @sale.customer.name%></span>
                <% end %>
                <span class="hidden" id="membership_id"><%= @sale.customer.membership_id%></span>
                <span class="hidden" id="member_discount"><%= @member_discount%></span></div>
              <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">
          <div class="card-title">
            <div id="table-details" 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="order-detail-slimscroll" data-height="300">
            <!-- <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" id="append-table">
                <tbody>
                  <% sub_total = 0
                  count = 0
                  %>
                  <% @sale.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_format( sale_item.unit_price, precision: precision.to_i )%></td>
                     <td class="item-attr"><%=sale_item.qty%></td>
                    <td class="item-attr"><%=(number_format(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_format(sub_total, precision: precision.to_i)%></span></strong></td>
            </tr>
            <tr>
              <%if @sale.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_format(@sale.total_discount, precision: precision.to_i ) rescue number_format(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 @sale_payment && @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_format(@sale.total_tax, precision: precision.to_i ) rescue number_format(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_format(@sale.rounding_adjustment, precision: precision.to_i ) rescue number_format(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_format(@sale.grand_total, precision: precision.to_i ) rescue number_format(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_format(@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_format(@individual_total[0]['per_person_amount'], precision: precision.to_i )%></span></strong></td>
              </tr>
            <% end %>
          </tfooter>
        </table>
      </div>
     <!-- <div> -->
  <!-- <INPUT TYPE="Button" class='btn btn-primary' VALUE="Reprint" onClick="" style='width:120px'/>
  <INPUT TYPE="Submit" class='btn btn-primary' VALUE="CANCEL" action="origami/index" style='width:120px'/> -->
  <!-- </div> -->
</div>
</div>

<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5">
  <div class="card">
    <div class="card-header">
      <div class="row m-l-5 m-r-5">
        <div class="col-md-8"><strong class='amount_balance'>Amount Due <% if !@sale_payment %>( Credit )<% end %></strong></div>
        <div class="col-md-4">
          <strong>
            <span id="grand_total" class="hidden">
              <%= number_format(@amount_due, precision: precision.to_i ) rescue number_format(0, precision: precision.to_i)%>
            </span>
            <span id="amount_due">
              <%= number_format(@amount_due, precision: precision.to_i ) rescue number_format(0, precision: precision.to_i)%>
            </span>
          </strong>
        </div>
      </div>

      <div class="row payment cash-color p-l-5 p-r-5">
        <div class="col-md-8">Cash</div>
        <div class="col-md-4" id="cash" >
            <%= number_format(@cash, precision: precision.to_i ) rescue number_format(0, precision: precision.to_i ) %>
        </div>
      </div>
      <% if @sale_payment && @cashier_type != "food_court" %>
        <div class="row payment credit-color p-l-5 p-r-5" id="credit_payment" >
          <div class="col-md-8">Credit</div>
          <div class="col-md-4" id="credit"><%= number_format(@credit, precision: precision.to_i ) rescue number_format(0, precision: precision.to_i ) %></div>
        </div>
      <% else %>
        <div class="col-md-4 hidden" id="credit">0</div>
      <% end %>
      <div class="row payment other-payment-color p-l-5 p-r-5" id="card_payment" >
        <div class="col-md-8">Other Payments</div>
        <div class="col-md-4" id="other_payment_amount">
          <%= number_format(@other_payment, precision: precision.to_i) rescue number_format(0, precision: precision.to_i) %>
        </div>
      </div>
    </div>
    <div class="card-block">
      <div class="card-title">
        <% @other_payments.each do |payment| %>
        <div class="row payment others-color p-l-5 p-r-5">
          <div class="col-md-8"><%= payment[0] %></div>
          <div class="col-md-4 <%= payment[0].parameterize %> is_card"><%= number_format(payment[1], precision: precision.to_i ) rescue number_format(0, precision: precision.to_i ) %></div>
        </div>
        <% end %>

        <div class="row m-l-5 m-r-5">
          <div class="col-md-8"><strong class='amount_balance'>Balance</strong></div>
          <div class="col-md-4"><strong><span id='balance'><%= number_format(@sale.grand_total, precision: precision.to_i ) rescue number_format(0, precision: precision.to_i ) %></span></strong></div>
        </div>
        <!-- <br> -->
      </div>
    </div>

    <div class="card-footer">
      <div class="row m-l-5 m-r-5">
       <div class="col-lg-6 col-md-6 col-sm-6">
         <div class="row bottom">
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="1" data-type="num">1</div>
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="2" data-type="num">2</div>
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="3" data-type="num">3</div>
         </div>
         <div class="row bottom">
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="4" data-type="num">4</div>
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="5" data-type="num">5</div>
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="6" data-type="num">6</div>
         </div>
         <div class="row bottom">
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="7" data-type="num">7</div>
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="8" data-type="num">8</div>
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="9" data-type="num">9</div>
         </div>
         <div class="row bottom">
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="0" data-type="num">0</div>
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="." data-type="num">.</div>
           <div class="col-md-4 cashier_number border-top border- border-left" data-value="00" data-type="num">00</div>
         </div>
         <div class="row bottom">
           <div class="col-md-4 cashier_number border-top border- border-left green" data-type="nett">Nett</div>
           <div class="col-md-4 cashier_number border-top border- border-left red" data-type="del">Del</div>
           <div class="col-md-4 cashier_number border-top border- border-left orange" data-type="clr">Clr</div>
         </div>
       </div>
       <div class="col-lg-6 col-md-6 col-sm-6">
         <div class="row bottom">
           <div class="cashier_number border-top border- border-left payment-long payment-left" data-value="1000" data-type="add">1000</div>
           <div class="cashier_number border-top border- border-left payment-long" data-value="3000" data-type="add">3000</div>
         </div>
         <div class="row bottom">
           <div class="cashier_number border-top border- border-left payment-long payment-left" data-value="5000" data-type="add">5000</div>
           <div class="cashier_number border-top border- border-left payment-long" data-value="10000" data-type="add">10000</div>
         </div>
          <div class="row bottom">
           <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%>">
           <div class="pay border-top border- border-left purple payment-left" id="pay">Pay</div>
          </div>
       </div>
     </div>
   </div>
 </div>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
  <button type="button" class="btn btn-block btn-default waves-effect" id='back'>
    <i class="material-icons">reply</i>
     Back
  </button>
  <button type="button" class="btn btn-block btn-default waves-effect" id='refresh'>
    <!-- <i class="material-icons">reply</i> -->
     Refresh
  </button>
   <!--   -->
  <% if current_login_employee.role == "cashier" %>
    <% if @other_payment <= 0 && @sale_payment %>
      <%if @sale.total_discount == 0 %>
        <a class="btn btn-block bg-deep-purple waves-effect access_modal" data-toggle="modal"  data-type="foc"> FOC</a>
      <% end %>
    <%end %>
    <% if @sale_payment %>
      <a class="btn btn-block bg-red waves-effect access_modal" data-toggle="modal"  data-type="void"> Void</a>
      <% if @other_payment <= 0 %>
        <%if @sale.total_discount == 0 %>
          <a class="btn btn-block bg-deep-purple waves-effect access_modal" data-toggle="modal"  data-type="waste"> Waste</a>
          <a class="btn btn-block bg-deep-purple waves-effect access_modal" data-toggle="modal"  data-type="spoile"> Spoile</a>
        <% end %>
      <% end %>
    <% end %>
  <% else %>
    <% if @other_payment <= 0 && @sale_payment%>
      <%if @sale.total_discount == 0 %>
        <button type="button" class="btn bg-deep-purple btn-block" data-toggle="modal" data-target="#focModal" <%= (can? :foc, :payment)? ' ': 'disabled=' %> active="true"> FOC </button>
      <%end %>
    <%end %>
    <% if @sale_payment %>
      <button type="button" class="btn bg-red btn-block" data-toggle="modal" data-target="#voidModal" <%= (can? :overall_void, :void)? ' ': 'disabled=' %> > Void </button>
      <% if @other_payment <= 0 %>
        <%if @sale.total_discount == 0 %>
          <button type="button" class="btn btn-block bg-deep-purple waves-effect " data-status="waste" value="waste" id="btn_waste" onclick="waste_and_spoilage('waste')">Waste</button>
          <button type="button" class="btn btn-block bg-deep-purple waves-effect " data-status="spoile" value="spoile" id="btn_spoile" onclick="waste_and_spoilage('spoile')">Spoile</button>
        <% end %>
      <% end %>
    <% end %>
  <% end %>

<% if (@cashier_type=="quick_service" || @cashier_type=="food_court") && @sale_payment %>
<hr>

 <button type="button" id="survey" class="btn btn-block bg-blue waves-effect"><%= t("views.right_panel.detail.survey") %></button>
 <button type="button" id="customer" class="btn btn-block bg-blue waves-effect" >Customer</button>
 <% if current_login_employee.role == "cashier" %>
  <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 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>
  <!-- Waiter Buttons -->
  <%end %>
</div>
<input type="hidden" id="server_mode" value="<%= ENV["SERVER_MODE"] %>">
</div>

<%= print_settings %>

<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>

<!-- pdf light box -->
<div class="modal fade" id="pdfModal"  tabindex="-1" role="dialog" >
  <div class="modal-dialog modal-md " role="document">
    <div class="modal-content">
      <div class="modal-header">
      <h6 class="modal-title">
        <span id="pdfModalLabel"></span>
        <span id="changed_amount" class="p-l-120"></span>
      </h6>
      </div>
      <div class="modal-body" style="height: 400px;">
        <input type="hidden" name="sale_receipt_no" id="sale_receipt_no">
        <input type="hidden" name="filename" id="filename">
        <input type="hidden" name="printer_name" id="printer_name">
        <div class="text-center">
          <iframe id="receipt_pdf" src="" class="pdf-iframe" scrolling="no"></iframe>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="mr-2 m-t-5 btn-lg btn-block bg-red waves-effect print_receipt" id="print_receipt">  Print
        </button>
        <button type="button" class="btn-lg btn-block bg-blue waves-effect btn_pdf_close" data-dismiss="modal">
          CLOSE
        </button>
      </div>
    </div>
  </div>
</div>

<!-- customer light box -->
<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="paypar_account_no" id="paypar_account_no" />
        <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>

<div id="sxModal">
  <div id="sxModal-Content">
    <h3>Card Tap</h3>
  </div>
  <div class="m-r-20" align="right">
      <button type="button" class="btn btn-lg btn-link bg-red waves-effect btn_cancel">Cancel</button>
  </div>
</div>

<!-- customer light box -->
<div class="modal fade m-t-40" id="is_paymemberModal" 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_paymemberModalLabel">Are you Member?</h1> -->
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="paypar_account_no" id="paypar_account_no" />
        <input type="hidden" name="qr_code" id="qr_code" />
        <div class="row text-center m-t-20" align="center">
          <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"></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 btn_paymal_member">Card</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_paymal_qr_code">QR Code</button>
          </div> -->
        </div>
      </div>
      <div class="modal-footer"></div>
    </div>
  </div>
</div>

<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 other_payments = <%= raw @other_payments %>;
var payment_methods = <%= raw @payment_methods %>;

// console.log(pdf_view)
$(document).ready(function(){
    $("#sxModal").hide();

    var paymalcount = other_payments.some(x => x[0] == 'paymal') ? other_payments.find(x => x[0] == 'paymal')[1] : 0.0;
    if(cashier_type == "food_court" && paymalcount == 0.0){
      $("#is_paymemberModal").modal({show : true, backdrop : false, keyboard : false});
    }
    setHeaderBreadCrumb(_PAYMENTS_);

    /* replace url type*/
    if(!trans_flag){
      localStorage.setItem("trans_flag", trans_flag);
      var sale_id = $('#sale_id').text();
      window.location.replace('/origami/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();
    }

    // if ($("#server_mode").val() != "cloud") { // first bill not used in cloud
    payment_type = checkReceiptNoInFirstBillData(receipt_no,"payment")

    console.log(payment_type)
    // console.log(parseInt(jQuery.inArray("MPU", payment_type)))
    if (member_id && member_discount) {
      if(parseInt(jQuery.inArray("Credit", payment_type)) == -1){
        $("#credit_payment").hide();
      } else{
        $("#credit_payment").show();
      }

      if(payment_type && payment_methods.some(x => payment_type.indexOf(x) >= 0)){
        $("#card_payment").show();
      } else{
       $("#card_payment").hide();
      }
    }
    // }
    /* end check first bill or not*/

    var dining_id = "<%= @sale.bookings[0].dining_facility_id %>";

    $("#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 = '/origami/table/'+ dining_id;
        }else{
          window.location.href = '/origami/'+cashier_type+'/pending_order/'+sale_id;
        }
      }

    });

    $("#refresh").on('click', function(){
      window.location.reload();
    })

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

    update_balance();
    //checkChangableTax
    checkChangableTax();

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

    $('#credit_payment').click(function() {
      var sale_id = $('#sale_id').text();
      window.location.href = '/origami/sale/'+ sale_id  +"/"+cashier_type+"/payment/credit_payment"
      return false;
    });

    $('#card_payment').click(function() {
      localStorage.setItem("cash",$('#cash').text() );
      var sale_id = $('#sale_id').text();
      var url_param = "payment";
      if(location.pathname.includes("credit_payment")){
        url_param = "credit_payment";
      }
      if(cashier_type != "food_court"){
        window.location.href = '/origami/sale/'+ sale_id  + "/"+cashier_type+"/"+url_param+"/others_payment";
        return false;
      }else{
        if(paymalcount == 0.0){
          $("#is_paymemberModal").modal({show : true, backdrop : false, keyboard : false});
        }
      }
    });

    $('#pay').click(function() {
      sub_total = $('#sub-total').text();
      member = $('#membership_id').text();
      if (payment_type && payment_type.length > 0 && parseInt(jQuery.inArray("Credit", payment_type)) == -1 && !other_payments.some(x => payment_type.indexOf(x[0]) >= 0 && x[1] > 0) && sub_total != 0.0 && member) {
        swal("Oops","Please Pay with " + payment_methods.find(x => payment_type.indexOf(x) >= 0) + " Payment","warning");
      } else if (payment_type && payment_type.length > 0 && parseInt(jQuery.inArray("Credit", payment_type)) != -1 && $('#credit').text() == 0 && sub_total != 0.0 && member) {
        swal("Oops","Please Pay with Credit Payment","warning");
      } else {
        $( "#loading_wrapper").show();
        if($('#balance').text() > 0){
          swal ( "Oops", "Insufficient Amount!" ,  "error" );
          $("#loading_wrapper").hide();
        }else{
          $(this).off("click");
          var sale_id   = $('#sale_id').text();
          // var item_row  = $('.is_card');

          //  payment
            var cash   = $('#cash').text();
            var credit = $('#credit').text();
            var card   = $('#card').text();
            var kbz_amt = "<%= @kbz_pay_amount %>";
            var is_kbz = false;
            if (kbz_amt > 0) {
              is_kbz = true
            }

            var tax_type = localStorage.getItem("tax_type") ? localStorage.getItem("tax_type") : 'all';
            if (credit <= 0 && (!location.pathname.includes("credit_payment"))) {
              calculate_member_discount(sale_id,tax_type);
            }

            // $("#pdfModal").on('shown.bs.modal', function () {
            //   $('#pdfModal').focus() }).modal({show : true, backdrop : false, keyboard : false});
            /* check credit payment or not*/
            if(location.pathname.includes("credit_payment")){
              var url = "<%= origami_credit_payment_cash_path %>";
            }else{
              var url = "<%= origami_payment_cash_path %>";
            }

            $.ajax({type: "POST",
              url: url,
              data: "cash="+ cash + "&sale_id=" + sale_id + "&type=" + cashier_type + "&tax_type=" + tax_type + "&is_kbz=" + is_kbz,
              success:function(result){
                /* start delete receipt no in first bill*/
                console.log(result);
                if(($("#receipt_no").html()!=undefined) && ($("#receipt_no").html()!="")){
                  var receipt_no = ($("#receipt_no").html()).trim();
                  deleteReceiptNoInFirstBillData(receipt_no);
                }
                /* end delete receipt no in first bill*/

                localStorage.removeItem("cash");
                if (result.status) {
                  var msg = result.message;
                }
                else{
                  var msg = '';
                }

                $("#changed_amount").text("");
                if($('#balance').text() < 0){
                  <% if precision.to_i > 0 %>
                    $("#changed_amount").text('Changed amount  ' + parseFloat($('#balance').text() * (-1)).toFixed(<%= precision %>));
                  <% else %>
                    $("#changed_amount").text('Changed amount  ' + parseFloat($('#balance').text() * (-1)));
                  <% end %>
                }

                if(location.pathname.includes("credit_payment") || pdf_view != 1){
                  payment_success_alert();
                } else {
                  //PDF lightbox data;
                  var pdfPath = "/en/pdfjs/minimal?file=" + result.filename.substring(6)
                  $("#sale_receipt_no").val(result.receipt_no);
                  $("#filename").val(result.filename);
                  $("#printer_name").val(result.printer_name);
                  $("#receipt_pdf").attr("src", pdfPath);
                  $("#pdfModal").modal({show : true, backdrop : false, keyboard : false});
                  $("#pdfModalLabel").text("Sale Completed");
                }

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

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

    // $('#void').on('click',function () {
    //   if ($(this).attr('active') === "true") {
    //         var sale_id = $('#sale_id').text();
    //         var remark  = $("#remark").val();
    //         var ajax_url = "/origami/sale/" + sale_id + '/void';
    //         $.ajax({
    //           type: 'POST',
    //           url: ajax_url,
    //           data: "remark="+ remark + "&sale_id=" + sale_id,
    //           success: function () {
    //              window.location.href = '/origami/';
    //           }
    //         })
    //   }else{
    //     swal("Oops","You are not authorized for void","warning")
    //   }
    // });

  });

  // 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 = '/origami/' + 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 = '/origami/' + 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 = '/origami/' + sale_id +"/"+cashier_type+ '/other_charges'
    }
    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 = '/origami/' + sale_id + "/"+cashier_type+'/discount'
      }
      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 = '/origami/table/' + dining_id + "/sale/" + sale_id + "/"+cashier_type+"/edit";
      }else{
        window.location.href = "/origami/table/sale/" + sale_id + "/"+cashier_type+"/edit";
      }

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

  $(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 others = other_payments.map(x => x[1]).reduce((acc, v) => acc + v, 0);
          var othertotal = parseFloat(credit1) + parseFloat(others);
          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;
    }
  });


  function update_balance(){
    var cash = $('#cash').text();
    var credit = $('#credit').text();
    var others = other_payments.map(x => x[1]).reduce((acc, v) => acc + v, 0);

    var amount_due = $('#amount_due').text();
    var total = parseFloat(cash) + parseFloat(credit) + parseFloat(others);

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

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

    show_hide_btn($('#balance').text());
  }

  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) {
   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: "/origami/" + 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){
        }
      });
    }
  }

  //print pdf function
  // $(".print_receipt").on('click',function(){
  $("#print_receipt").on('click touchstart', function(event){
    $(this).off("click touchstart touchend");
    print_receipt();
  });

  function print_receipt() {
    if($('#pay').is(":visible")) {
      $('#pay').prop("disabled",true);
    }
    $("#loading_wrapper" ).show();

    var sale_id   = $('#sale_id').text();
    var filename = $("#filename").val();
    var printer_name = $("#printer_name").val();
    var receipt_no = $("#sale_receipt_no").val();
    var params = { 'filename':filename, 'receipt_no':receipt_no, 'printer_name':printer_name };
      $.ajax({
        type: "POST",
        url: "/origami/sale/"+sale_id+"/"+cashier_type+"/payment/print",
        data: params,
        success:function(result){
          if (!$('#print_settings').data('action-cable')) {
            // For Server Print - from jade
            if ($("#server_mode").val() == "cloud") {
              if(typeof code2lab != 'undefined'){
                code2lab.printFile(result.filepath.substr(6), result.printer_url);
              }
            }
          }

          if (pdf_view ==1) {
            var flag = localStorage.getItem("trans_flag");
            localStorage.removeItem("trans_flag");
            if((flag!=null) && (flag != "true")){
              window.location.href = "/transactions/sales/"+sale_id;
            }else{
              if (cashier_type=="cashier") {
                window.location.href = '/origami';
              }else{
                window.location.href = '/origami/'+cashier_type;
                if (cashier_type=="quick_service"){
                  customer_display_view(null,"reload");
                }
              }
            }
          }else{
            payment_success_alert();
          }

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

  function payment_success_alert(){
    var title = "Payment Successful!";
    if($('#balance').text() < 0){
     var text  = 'Changed amount  ' + $('#balance').text() * (-1);
    }else{
      $('#pay').text("Pay");
      var text  = 'Thank You !';
    }
    var sale_id   = $('#sale_id').text();
    swal({
          title: "Payment Successful!",
          text: text,
          html: true,
          closeOnConfirm: false,
          closeOnCancel: false,
          allowOutsideClick: false
         }, function () {
          var flag = localStorage.getItem("trans_flag");
          localStorage.removeItem("trans_flag");
          if((flag!=null) && (flag != "true")){
            window.location.href = '/transactions/sales/'+sale_id;
          }else{
            if (cashier_type=="cashier") {
              window.location.href = '/origami';
            }else {
              window.location.href = '/origami/'+cashier_type;
              if(cashier_type=="quick_service"){
                customer_display_view(null,"reload");
              }
            }
          }
       });
  }


  $(".btn_pdf_close").on('click',function(){
    var flag = localStorage.getItem("trans_flag");
    if((flag!=null) && (flag != "true")){
      var sale_id   = $('#sale_id').text();
      window.location.href = "/transactions/sales/"+sale_id;
    }else{
      if (cashier_type=="cashier") {
        window.location.href = '/origami';
      }else{
        window.location.href = '/origami/'+cashier_type;
      }
    }

  });

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

  // Read Card Reader
  $(".btn_member").on('click', function(){
    $("#is_memberModal").hide();
    $("#sxModal").show();
    getCardNo();
  });

  // 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 (cashier_type == "food_court") {
        send_account();
      } else {
        get_customer();
      }
    }
    $("#sxModal").hide();
  }

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

    if(sale_id != 0 && customer_mamber_card_no != 0){
      $('#loading_wrapper').show();
      $.ajax({
        type: "POST",
        url: "/origami/"+sale_id+"/get_customer" ,
        data: { filter : customer_mamber_card_no ,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);
          }
          $('#loading_wrapper').hide();
        }
      });
    }
  }

  function send_account() {
    var 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 payment_amount = parseFloat($("#grand_total").text());

    var customer_mamber_card_no = $("#paypar_account_no").val();
    if (customer_mamber_card_no == 0) {
      customer_mamber_card_no = $("#membership_id").text() || 0;
    }
    if(sale_id != 0 && customer_mamber_card_no !=0){
      $.ajax({
        type: "POST",
        url: "/origami/"+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 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:  "<%=origami_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){
                  swal({
                    title: "Information!",
                    text: result.message,
                    html: true,
                    closeOnConfirm: false,
                    closeOnCancel: false,
                    allowOutsideClick: false
                  }, function () {
                    window.location.href = '/origami/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 = '/origami/sale/'+ sale_id +"/"+cashier_type + "/payment";
                  });
                }
              }
            });
          }else{
            swal({
              title: 'Oops',
              text: data.message.toString(),
              type: 'error',
              html: true,
              closeOnConfirm: false,
              closeOnCancel: false,
              allowOutsideClick: false
            }, function () {
              window.location.href = '/origami/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 = '/origami/sale/'+ sale_id +"/"+cashier_type + "/payment";
      });
    }
  }

  // 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: "/origami/"+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 + ')';
    }

    swal({
      title: "Confirmation !",
      text: 'Are You Sure to assign this customer' + customer + '!',
      showCancelButton: true,
      confirmButtonColor: "green",
      confirmButtonText: "Yes!",
      cancelButtonClass: 'btn btn-danger',
      closeOnConfirm: false,
    }, function () {
      $('#loading_wrapper').show();
      $.ajax({
        type: "POST",
        url: "/origami/"+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 = '/origami/sale/'+sale_id+'/'+cashier_type+'/payment/';
          }else{
            swal("Alert!", "Record not found!", "error");
            location.reload();
          }
        }
      });
    });
  }

  $("#sxModal .btn_cancel").on('click',function(){
    $("#sxModal").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 = "/origami/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();
                  if (dining_id) {
                    window.location.href = '/origami/table/' + dining_id + "/sale/" + sale_id + "/"+cashier_type+"/edit";
                  }else{
                    window.location.href = "/origami/table/sale/" + sale_id + "/"+cashier_type+"/edit";
                  }
               }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: "/origami/payment/"+cashier_type+"/foc",
          data: params,
          success:function(result){
            customer_display_view(null,"reload");
            if (cash >= 0) {
              swal({
               title: "Information!",
               text: 'Thank You !',
              }, function () {
                if (!$('#print_settings').data('action-cable')) {
                  // 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 = '/origami';
                  }else{
                    window.location.href = '/origami/'+cashier_type;
                  }
                }
              });
            }
          }
        });
      }
    });
  });

 $('#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 = "/origami/sale/" + sale_id +'/'+cashier_type+ '/void';
        $.ajax({
          type: 'POST',
          url: ajax_url,
          data: "remark="+ remark + "&sale_id=" + sale_id+ "&access_code=" + access_code,
          success: function (result) {result
            customer_display_view(null,"reload");
            if (!$('#print_settings').data('action-cable')) {
              // 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 = '/origami';
              }else{
                window.location.href = '/origami/'+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 = "/origami/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)
            if (!$('#print_settings').data('action-cable')) {
              // 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 = '/origami';
              }else{
                window.location.href = '/origami/'+cashier_type;
                if(cashier_type=="quick_service"){
                  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) {
        $.ajax({
          type: "POST",
          url: "/origami/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.href = '/origami/sale/'+sale_id+'/'+cashier_type+'/payment';
            }
          }
        });
      }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!="")){
      $("#is_memberModal").modal({show : true, backdrop: false, keyboard : false});
    }
  });

  // Read Card Reader - Paymal payment for FoodCourt
  $(".btn_paymal_member").on('click', function (){
    $("#is_paymemberModal").hide();
    $("#sxModal").show();
    getCardNo();
  });

  // 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: "/origami/"+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:  "<%=origami_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 = '/origami/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 = '/origami/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 = '/origami/sale/'+ sale_id +"/"+cashier_type + "/payment";
              });
            }
          }
        });
      }
    },100);
  });

  function show_hide_btn(balance) {
    // show discount when balance is greater than 0
    // if(parseFloat(balance) > 0){
    //   $("#discount").show();
    //   $("#edit").show();
    // }else{
    //   $("#discount").hide();
    //   $("#edit").hide();
    // }
  }
</script>
