<div class="container-fluid">
<div class="row">

 <div class="col-lg-4 col-md-6 col-sm-6">
       <!-- <div class="card-columns" style="padding-top:10px; column-gap: 1.2rem;"> -->
         <% @sale_array.each do |sale| %>
         <div class="card tables receipt_block" data-id="<%= sale.id %>">
           <% if sale.id == @sale.id %>
             <div class="card-block selected-item">
                <%= sale.receipt_no %>
             </div>
           <% else %>
             <div class="card-block">
                <%= sale.receipt_no %>
             </div>
           <% end %>
         </div>
         <% end %>
  </div>

  <div class="col-lg-7 col-md-5 col-sm-5">
     <div class="card"  >
       <div class="card-header">
          <div><strong id="order-title">INVOICE DETAILS </strong></div>
       </div>
       <div class="card-block">
         <div class="card-title row">
           <div class="col-lg-6 col-md-6 col-sm-6">
             &nbsp; Receipt No: <span id="receipt_no">
                 <%= @sale.receipt_no rescue '' %>
             </span>
           </div>
           <div class="col-lg-6 col-md-6 col-sm-6 text-right">
             Date:  <span id="receipt_date"><%= @sale.created_at.strftime("%d/%m/%Y - %I:%M %p") rescue '-'%></span>&nbsp;
           </div>
         </div>
         <div class="card-title row customer_detail">
           <div class="col-lg-6 col-md-6 col-sm-6">
            <% if @status_sale == 'sale' %>
              <p class="hidden customer-id"><%= @sale.customer_id rescue '' %></p>
               &nbsp; Customer : <%= @sale.customer.name rescue '-' %>
             <%else%>
               <p class="hidden customer-id"><%= @customer.customer_id rescue "" %></p>
               &nbsp; Customer : <%= @customer.name rescue "-" %>
             <%end%>
           </div>

         </div>
         <div id="order-detail-slimscroll" data-height="160">
            <div class="card-text" style="">
           <table class="table table-striped" id="order-items-table">
             <thead>
               <tr>
                 <th>#</th>
                 <th class="item-name">Items</th>
                 <th class="item-attr">QTY</th>
                 <th class="item-attr">Price</th>
               </tr>
             </thead>
             <tbody>
               <%
                 count = 0
                 sub_total = 0
                 if @status_sale == "sale"
                  @sale.sale_items.each do |sale_item|
                    count += 1
                  sub_total = sub_total + sale_item.price
               %>
               <input type="hidden" id="sale_id" value="<%= @sale.sale_id %>">
               <%
               # Can't check for discount
                # unless sale_item.price == 0
                %>
               <tr>
                 <td><%= count %></td>
                 <td class='item-name'><%= sale_item.product_name %></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
                   end
                 end

                 if @status_order == 'order' && @status_sale != 'sale'
                    unless @order_items.nil?
                       count = 0
                    @order_items.each do |order_item |
                        count += 1
                    sub_total = sub_total + order_item.price

                unless order_item.price == 0 %>
               <tr>
                 <td><%= count %></td>
                 <td class='item-name'><%= order_item.item_name %></td>
                 <td class='item-attr'><%= order_item.qty %></td>
                 <td class='item-attr'><%= number_format(order_item.qty*order_item.price, precision: precision.to_i ) %></td>
               </tr>
               <%
                     end
                    end
                   end
                 end
               %>
             </tbody>
           </table>
             </div>
         </div>
         <div class="card-footer">
           <table class="table" id="order-charges-table" border="0">
             <tr>
               <td class="charges-name"><strong>Sub Total:</strong></td>
               <td class="item-attr"><strong id="order-sub-total"><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 id="order-discount">(<%= number_format(@sale.total_discount, precision: precision.to_i ) rescue 0%>)</strong></td>
             </tr>
             <tr>
               <td class="charges-name"><strong>Tax:</strong></td>
               <td class="item-attr"><strong id="order-Tax"><%= number_format(@sale.total_tax, precision: precision.to_i ) rescue 0%></strong></td>
             </tr>
              <tr>
               <td class="charges-name"><strong>Rounding Adj:</strong></td>
               <td class="item-attr"><strong id="order-round-adj"><%= number_format(@sale.rounding_adjustment, precision: precision.to_i ) rescue 0%></strong></td>
             </tr>
             <tr>
               <td class="charges-name"><strong>Grand Total:</strong></td>
               <td class="item-attr"><strong id="order-grand-total"><span id="grand_total"><%= number_format(@sale.grand_total, precision: precision.to_i ) rescue 0%></span></strong></td>
             </tr>
              <tr class="rebate_amount"></tr>
           </table>
         </div>
       </div>
     </div>
  </div>

 <!-- Column Three -->
 <div class="col-lg-1 col-md-1 col-sm-1">
   <button id="back" type="button" class="btn btn-block btn-lg bg-default"> <i class="material-icons">reply</i> <%= t("views.btn.back") %>
  <% if ENV["SERVER_MODE"] == "cloud" %>
    <button type="button" id="first_bill" class="btn btn-block bg-blue waves-effect">First Bill</button>
  <% else %>
    <%if @membership.discount && @sale.customer.membership_id %>
      <button type="button" class="btn btn-block bg-blue waves-effect" data-toggle="modal" data-target="#paymentModal">First Bill</button>
    <%else%>
      <button type="button" id="first_bill" class="btn btn-block bg-blue waves-effect">First Bill</button>
    <%end%>
  <% end %>
   <button type="button" id="pay" class="btn bg-blue btn-block">Pay</button>

   <% if current_login_employee.role == "cashier" %>
    <a class="btn btn-block bg-deep-purple waves-effect access_modal" data-toggle="modal"  data-type="foc"> FOC</a>
    <a class="btn btn-block bg-red waves-effect access_modal" data-toggle="modal"  data-type="void"> Void</a>
  <% else %>
     <button type="button" class="btn bg-deep-purple btn-block" data-toggle="modal" data-target="#focModal" <%= (can? :foc, :payment)? ' ': 'disabled=' %> active="true"> FOC </button>
   <button type="button" data-toggle="modal" data-target="#voidModal" class="btn bg-danger btn-block" <%= (can? :overall_void, :void)? ' ': 'disabled=' %> > Void </button>
  <% end %>
 </div>
</div>
</div>

<%= print_settings %>

<!-- membership paymentmodal -->
<input type="hidden" id="server_mode" value="<%= ENV["SERVER_MODE"] %>">
<span class="hidden" id="member_discount"><%= @membership.discount%></span>
<span class="hidden" id="membership_id"><%= @sale.customer.membership_id rescue 0%></span>
<div class="modal fade" id="paymentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="paymentModalLabel">Choose Payment</h4>
            </div>
            <div class="modal-body">
               <select class="form-control show-tick payment_method" multiple="true"  id="payment_method" >
                 <option value="Cash">Cash</option>
                 <option value="Credit">Credit</option>
                <% @payment_methods.each do |pay| %>
                  <option value="<%= pay.payment_method %>">
                    <%= pay.payment_method %>
                  </option>
                <%end %>

                </select>
            </div>
            <div class="modal-footer  p-r-30">
                <button type="button" class="btn btn-link btn-danger waves-effect" data-dismiss="modal">CLOSE</button>
                &nbsp;  &nbsp;
               <button type="button" class="btn btn-link bg-blue waves-effect choose_payment">SAVE</button>
            </div>
        </div>
    </div>
</div>
<!-- membership paymentmodal -->

<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="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>
<script>
$(document).ready(function(){
  /* start check first bill or not*/
    var receipt_no = "";
    if(($("#receipt_no").html()!=undefined) && ($("#receipt_no").html()!="")){
      receipt_no = ($("#receipt_no").html()).trim();
    }

    discount="<%= @membership.discount%>"
    if ($("#server_mode").val() != "cloud") { // first bill not used in cloud
      if (discount) {
        if(checkReceiptNoInFirstBillData(receipt_no,"")){
          $("#pay").show();
        }else{
          $("#pay").hide();
        }
      }
    }
  /* end check first bill or not*/

  $(".tables").on('click', function(){
      var dining_id = $(this).attr("data-id");
      window.location.href = '/origami/table/<%= @table.id %>/table_invoice/' + dining_id;
  })
});

   // Print for first bill
    $("#first_bill").on('click', function () {
      swal({
        title: "Alert",
        text: "Are you sure want to print First Bill?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, print it!",
        closeOnConfirm: false
      }, function (isConfirm) {
         $('.confirm').off("click touchstart touchend");
         $('.confirm').attr("disabled","disabled");
        if (isConfirm) {

          var sale_id = '<%= @sale.id %>';
          var ajax_url = "/origami/sale/" + sale_id + "/first_bill";

          $.ajax({
          type: "GET",
          url: ajax_url,
          success: function (result) {
            receipt_no = ($("#receipt_no").html()).trim();
            if((receipt_no!=undefined) && (receipt_no!=""))
              createReceiptNoInFirstBillData(receipt_no,"");
              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);
                  }
                }
              }
            location.reload();
            }
          });
        }
      });
    });

  $(".choose_payment").on('click', function () {
    $( "#loading_wrapper").show();

      var sale_id = '<%= @sale.id %>';
      type = $('.payment_method').val();
      if(parseInt(jQuery.inArray("Credit", type)) == -1){
        if (parseInt(jQuery.inArray("MPU", type)) != -1 || parseInt(jQuery.inArray("VISA", type)) != -1 || parseInt(jQuery.inArray("JCB", type)) != -1 || parseInt(jQuery.inArray("Master", type)) != -1 || parseInt(jQuery.inArray("UNIONPAY", type)) != -1 || parseInt(jQuery.inArray("Redeem", type)) != -1) {
           calculate_member_discount(sale_id,"Card");

        }else{
          calculate_member_discount(sale_id,"Cash");
        }
      }
      var ajax_url = "/origami/sale/" + sale_id + "/first_bill";
      $.ajax({
          type: "GET",
          url: ajax_url,
          success: function (result) {
            $( "#loading_wrapper" ).hide();
            receipt_no = ($("#receipt_no").html()).trim();
            if((receipt_no!=undefined) && (receipt_no!=""))
              createReceiptNoInFirstBillData(receipt_no,type);

            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);
                }
              }
            }
            location.reload();
          }
      });
  });

  function calculate_member_discount(sale_id,type) {
    var sub_total = $('#sub-total').text();
     if (type == "Cash") {
       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 },
      async: false,
      success:function(result){
      }
    });
  }

$('#pay').on('click',function() {
   var sale_id = '<%= @sale.id %>';

   // var url = '<%= @calculate_rouding_adj_path %>';

   // $.ajax({
   //    type: "GET",
   //      url: url,
   //      success:function(result){
   //          // console.log(result);
   //      }
   //  });
   window.location.href = '/origami/sale/'+ sale_id + "/cashier/payment";
});

$('#back').on('click',function(){
  var lookup_split_bill = '<%= @split_bill %>';
  if(lookup_split_bill == '1'){
    window.location.href = '/origami/table/<%= @table.id %>/cashier/split_bills';
  }else{
    window.location.href = '/origami/table/<%= @table.id %>';
  }

});

$('#void').on('click',function () {
  var access_code  = localStorage.getItem("access_code");
    if ($(this).attr('active')=== "true") {
      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) {
          var sale_id = $('#sale_id').val();
          var remark  = $("#remark").val();
          var ajax_url = "/origami/sale/" + sale_id + '/cashier/void';
          $.ajax({
              type: 'POST',
              url: ajax_url,
              data: "remark="+ remark + "&sale_id=" + sale_id + "&access_code=" + access_code ,
              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);
                    }
                  }
                }
                window.location.href = '/origami';
              }
          });
        }
      });
    }else{
      swal("Opps","You are not authorized for void","warning");
    }
});

$('#foc').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 = '';
  if($('.receipt_block > div').hasClass('selected-item')){
    sale_id = $('.receipt_block > div.selected-item').parent().attr('data-id');
  }
  var params = { 'cash':cash,'sale_id':sale_id,'sub_total':sub_total,'remark':remark,'type':'cashier','access_code':access_code };
  // console.log(sale_id);
  if(sale_id != ''){
    if ($(this).attr('active')=== "true") {
        $.ajax({
          type: "POST",
          url: "/origami/payment/cashier/foc",
          data: params,
          success:function(result){
            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);
                    }
                  }
                }
                window.location.href = '/origami';
              });
            }
          }
        });
    }else{
      swal("Oops","You are not authorized for foc","warning")
    }
  }
});
$(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) {
            if (result.status == true) {
              createAccessCode(code);
              if (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 {
              swal("Opps",result.message,"warning")
            }
          }
      });
  }
</script>
