<div class="page-header">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="<%= root_path %>"><%= t("views.right_panel.button.home") %></a></li>
    <li class="breadcrumb-item"><a href="<%= transactions_sales_path %>"><%= t :sale %></a></li>
    <li class="breadcrumb-item active"><%= t :details %></li>
    <span class="float-right">
      <%= link_to 'Back', transactions_sales_path %>
    </span>
  </ol>
</div>
<div class="row">
  <div class="col-lg-12 col-md-12 col-sm-12">
  <!-- Column One -->

    <!-- Nav tabs -->
    <ul class="nav nav-tabs" role="tablist">
      <li class="nav-item">
        <a class="nav-link active" data-toggle="tab" href="#queue" role="tab"><%= t :sale_details %> </a>
      </li>
      <li class="nav-item">
        <a class="nav-link " data-toggle="tab" href="#booking" role="tab"><%= t :order_details %></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#customer" role="tab"><%= t :customer_details %></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#sale_audit" role="tab"><%= t :sale_audits %></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" data-toggle="tab" href="#payment_gateway" role="tab">Payment Gateway Audits</a>
      </li>
    </ul>
    <!-- Nav tabs - End -->

    <div class="tab-content" style="min-height:670px; max-height:670px;">

      <div class="tab-pane active" id="queue" role="tabpanel" style="min-height:670px; max-height:670px; overflow-y:">
        <div class="table-responsive">
          <table class="table table-striped">
            <thead>
              <tr>
                <th><%= t("views.right_panel.detail.receipt_date") %></th>
                <th><%= t("views.right_panel.detail.receipt_no") %></th>
                <th><%= t :cashier %></th>
                <th><%= t("views.right_panel.detail.sales_status") %></th>
                <th><%= t("views.right_panel.detail.receipt_generated_at") %></th>
                <% if @sale.sale_status == "new" || @sale.sale_status == "completed" %>
                  <% if current_login_employee.role == "administrator" || current_login_employee.role == "manager" %>
                    <th>
                      <div class="form-group">
                        <button type="button" class="btn btn-block bg-red waves-effect col-md-5" style="margin-top: 8px;" data-toggle="modal" data-target="#voidModal" <%= (can? :overall_void, :void)? ' ': 'disabled=' %> > Void</button>
                  <% else %>
                    <th>
                      <div class="form-group">
                        <a class="btn btn-block bg-red waves-effect access_modal" data-toggle="modal"  data-type="void" <%= (can? :overall_void, :void)? ' ': 'disabled=' %>> Void</a>
                  <% end %>
                <% end %>
                <% if @sale.sale_status == "new" %>
                  <% if current_login_employee.role == "administrator" %>
                    <%if @membership.discount && @sale.customer.membership_id %>
                          <button type="button" class="btn btn-block bg-blue waves-effect col-md-5" data-toggle="modal" data-target="#paymentModal">Pay</button>
                        </div>
                      </th>
                    <%else%>
                          <button type="button" id="pay" class="btn btn-block bg-blue waves-effect col-md-5">Pay</button>
                        </div>
                      </th>
                    <%end%>
                  <%end%>
                <% end %>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td><%= @sale.receipt_date.strftime("%d-%m-%Y") %></td>
                <td><%= @sale.receipt_no %></td>
                <td><%= @sale.cashier_name rescue '-' %></td>
                <td><%= @sale.sale_status %> </td>
                <td colspan="2"> <%= @sale.requested_at.strftime("%d-%m-%Y %H:%M %p") %> </td>
              </tr>
              <tr style="border-top:2px solid #000">
                <th><%= t :sale %> <%= t("views.right_panel.detail.item_txt") %> <%= t("views.right_panel.detail.name_txt2") %></th>
                <th><%= t("views.right_panel.detail.qty") %></th>
                <th><%= t("views.right_panel.detail.unit_price") %></th>
                <th><%= t("views.right_panel.detail.total_price") %></th>
                <th><%= t("views.right_panel.detail.created_at") %></th>
                <th><%= t("views.right_panel.detail.remark") %></th>
              </tr>
              <% @sale.sale_items.each do |s| %>
                <tr>
                  <td><%=s.product_name rescue ' '%></td>
                  <td><%=s.qty rescue ' '%></td>
                  <td><%= number_format(s.unit_price, :precision => 2, :delimiter => ',') rescue ' '%></td>
                  <td><%= number_format(s.price, :precision => 2, :delimiter => ',') rescue ' '%></td>
                  <td><%=l s.created_at , :format => :short rescue ' ' %></td>
                  <td><%=s.remark rescue ' '%></td>
                </tr>
              <% end %>
              <tr style="border-top:2px solid #000">
                <td colspan=2 style="text-align:center"></td>
                <td><%= t("views.right_panel.detail.total") %></td>
                <td colspan="3"><%= number_format(@sale.total_amount, :precision => 2, :delimiter => ',') rescue ' '%></td>
              </tr>
              <tr>
                <td colspan=2 style="text-align:center"></td>
                <td><%= t("views.right_panel.detail.discount") %></td>
                <td colspan="3"><%= number_format(@sale.total_discount, :precision => 2, :delimiter => ',') rescue ' '%></td>
              </tr>
              <% @sale.sale_taxes.each do |r|%>
                <tr>
                  <td colspan=2 style="text-align:center"></td>
                  <td><%= r.tax_name %> </td>
                  <td colspan="3"><%= number_format(r.tax_payable_amount, :precision => 2, :delimiter => ',') rescue ' '%></td>
                </tr>
              <% end %>
              <tr>
                <td colspan=2 style="text-align:center"></td>
                <td><%= t("views.right_panel.detail.grand_total") %></td>
                <td colspan="3"><%= number_format(@sale.grand_total, :precision => 2, :delimiter => ',') rescue ' '%></td>
              </tr>
              <tr><td colspan="5">&nbsp;<td></tr>
              <tr>
                <td colspan=2 style="text-align:center"></td>
                <td><%= t("views.right_panel.detail.total_pay_amount") %></td>
                <td colspan="3"><%= number_format(@sale.amount_received, :precision => 2, :delimiter => ',') rescue ' '%></td>
              </tr>
              <% @sale_receivables.each do |r|%>
                <tr>
                  <td colspan=2 style="text-align:center"></td>
                  <td> <%= r.payment_method.capitalize rescue ' '%> Payment</td>
                  <td colspan="3"><%= number_format(r.payment_amount, :precision => 2, :delimiter => ',') rescue ' '%></td>
                </tr>
              <% end %>
              <tr>
                <td colspan=2 style="text-align:center"></td>
                <td><%= t("views.right_panel.detail.change") %></td>
                <td colspan="3"><%= number_format(@sale.amount_changed, :precision => 2, :delimiter => ',') rescue ' '%></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="tab-pane" id="booking" role="tabpanel">
        <div class="table-responsive">
          <table class="table table-striped">
            <thead>
              <tr>
                <th><%= t("views.right_panel.detail.order_id") %></th>
                <th><%= t("views.right_panel.header.menu_item") %></th>
                <th><%= t("views.right_panel.detail.qty") %></th>
                <th><%= t("views.right_panel.detail.unit_price") %></th>
                <th><%= t("views.right_panel.detail.option") %></th>
                <th><%= t("views.right_panel.detail.status") %></th>
                <th><%= t("views.right_panel.detail.waiter") %></th>
                <th><%= t("views.right_panel.detail.created_at") %></th>
              </tr>
            </thead>
            <tbody>
              <% @order_items.each do |order_item| %>
                <tr>
                  <td><%= link_to order_item.order_id, transactions_order_path(order_item.order_id) %><%=  %></td>
                  <td><%= order_item.item_name %></td>
                  <td><%= order_item.qty %></td>
                  <td><%= order_item.price %></td>
                  <td><%= order_item.options %></td>
                  <td><%= order_item.order_item_status %></td>
                  <td><%= order_item.item_order_by %> </td>
                  <td><%= order_item.created_at.strftime("%d-%m-%y %I:%M %p") %></td>
                </tr>
              <% end %>
            </tbody>
          </table>
        </div>
      </div>
      <div class="tab-pane" id="customer" role="tabpanel">
        <br>
        <div class="table-responsive">
          <table class="table table-striped">
            <thead>
              <tr>
                <th><%= t("views.right_panel.detail.card_no") %></th>
                <th><%= t("views.right_panel.detail.name") %></th>
                <th><%= t("views.right_panel.detail.company") %></th>
                <th><%= t("views.right_panel.detail.contact_no") %></th>
                <th><%= t("views.right_panel.detail.email") %></th>
                <th><%= t("views.right_panel.detail.nrc_passport_no") %></th>
                <th><%= t("views.right_panel.detail.address") %></th>
                <th><%= t("views.right_panel.detail.dob") %></th>
              </tr>
            </thead>

            <tbody>
              <tr>
                <td><%= @customer.card_no rescue '-'%></td>
                <td><%= @customer.name %></td>
                <td><%= @customer.company rescue '-' %></td>
                <td><%= @customer.contact_no %></td>
                <td><%= @customer.email %></td>
                <td><%= @customer.nrc_no %></td>
                <td><%= @customer.address%></td>
                <td><%= @customer.date_of_birth %></td>
              </tr>
              <tr><td></td></tr>
              <% if @customer.membership_id %>
                <tr>
                  <th colspan="8"><%= t("views.right_panel.detail.membership_transactions") %></th>
                </tr>
                <tr>
                  <th><%= t("views.right_panel.detail.date") %></th>
                  <th><%= t("views.right_panel.detail.redeem") %></th>
                  <th><%= t("views.right_panel.detail.rebate") %></th>
                  <th><%= t("views.right_panel.detail.balance") %></th>
                  <th><%= t("views.right_panel.detail.from_account") %></th>
                  <th><%= t("views.right_panel.detail.status") %></th>
                  <th><%= t("views.right_panel.detail.receipt_no") %></th>
                  <th></th>
                </tr>

                <% if @response["status"] == true %>
                  <% @response["data"].each do |transaction| %>
                    <tr>
                      <td><%= transaction["date"]%></td>
                      <td><%= transaction["redeem"]%></td>
                      <td><%= transaction["rebate"] %></td>
                      <td><%= transaction["balance"] %></td>
                      <td><%= transaction["account_status"] %></td>
                      <td><%= transaction["status"] %></td>
                      <td><%= transaction["receipt_no"] %></td>
                      <td></td>
                    </tr>
                  <% end %>
                <% end %>
              <% end %>
            </tbody>
          </table>
        </div>
      </div>

      <div class="tab-pane" id="sale_audit" role="tabpanel">
        <br>
        <div class="table-responsive">
          <table class="table table-striped">
            <thead>
              <tr>
                <th><%= t("views.right_panel.detail.action") %></th>
                <th><%= t("views.right_panel.detail.action_at") %></th>
                <th><%= t("views.right_panel.detail.approved_at") %></th>
                <th><%= t("views.right_panel.detail.remark") %></th>
              </tr>
            </thead>
            <tbody>
              <% @sale_audits.each do |audit| %>
                <tr>
                  <td><%= audit.action%></td>
                  <td><%=  audit.action_at.strftime("%m-%d-%Y %H:%M %p")%></td>
                  <td><%=  audit.approved_by%></td>
                  <td><%= audit.remark%></td>
                </tr>
              <% end %>
            </tbody>
          </table>
        </div>
      </div>

      <div class="tab-pane" id="payment_gateway" role="tabpanel">
        <br>
        <div class="table-responsive">
          <table class="table table-striped">
            <thead>
              <tr>
                <th>Gateway Name</th>
                <th>Request Method</th>
                <th>Event Type</th>
                <th>Endpoint</th>
                <th>Request Body</th>
                <th>Response Body</th>
              </tr>
            </thead>
            <tbody>
              <% if @payment_gateway_audits.present? %>
                <% @payment_gateway_audits.each do |audit| %>
                  <tr>
                    <td><%= audit.payment_gateway_name %></td>
                    <td><%= audit.request_method %></td>
                    <td><%= audit.event_type %></td>
                    <td><%= audit.endpoint_url %></td>
                    <td colspan="3">
                      <%= audit.request_body %>
                    </td>
                    <td><%= audit.response_body %></td>
                  </tr>
                <% end %>
              <% else %>
                <tr>
                  <td colspan="4">No payment gateway audits found.</td>
                </tr>
              <% end %>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<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 bg-red waves-effect " id="void" active="true">VOID</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>

<%= print_settings %>

<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 Method</h4>
      </div>
      <div class="modal-body">
       <!--  <select class="form-control show-tick payment_method" multiple="true"  id="payment_method" > -->
                 <!-- <option value="Cash">Cash</option> -->
        <div class="row text-center">
          <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
            <button class='btn btn-md waves-effect payment-btn-box payment_btn bg-green' data-type='Credit' data-value='Credit'>Credit</button>
          </div>

          <% @payment_methods.each_with_index do |pay, pay_index| %>
            <%if (pay_index+1)%3 == 0 %>
              <div class="row clearfix"></div>
            <% end %>
            <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
              <button class='btn btn-md payment-btn-box waves-effect payment_btn bg-green' data-type='<%= pay.payment_method %>' data-value='<%= pay.payment_method %>'><%= pay.payment_method %></button>
            </div>
          <%end %>

        </div>

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

<script type="text/javascript">
  // Get Selected Class
  function get_selected_attributes(selected_class) {
    var item_row      = $('.'+selected_class);
    var attribute_arr = [];
    $(item_row).each(function(i){
      value = $(item_row[i]).attr('data-value');
      str = value;
      attribute_arr.push(str);
    });
    return attribute_arr;
  }

  function calculate_member_discount(sale_id,type,tax_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,'cashier_type':'cashier','tax_type':tax_type },
      async: false,
      success:function(result){ }
    });
  }

  function createReceiptNoInFirstBillData(receipt_no,payment) {
    var arr_data = [];
    var json_data = [];
    if(localStorage.hasOwnProperty("receipt_lists") === true){
      arr_data = JSON.parse(localStorage.getItem("receipt_lists"));
      json_data = arr_data.filter(function(e) { return e.receipt_no == receipt_no });
      if (payment) {
        jdata = arr_data.filter(function(e) { return e.receipt_no !== receipt_no });
        jdata.push({'receipt_no':receipt_no,'payment':payment});
         localStorage.setItem("receipt_lists",JSON.stringify(jdata));
      }
    }
    if(((arr_data.length == 0) && (json_data.length == 0)) || ((arr_data.length > 0) && (json_data.length == 0))){
      arr_data.push({'receipt_no':receipt_no,'payment':payment});
      localStorage.setItem("receipt_lists",JSON.stringify(arr_data));
    }
  }

  // click select option icon for add
  $('.payment_btn').on('click', function(event){
    active     = $(this).hasClass('selected-payment');
    value      = $(this).data('value');
    type       = $(this).data('type');
    group      = $(this).data('group');
    payments    = $(".payment_btn");

    if (active) {
      $(this).removeClass('selected-payment');
    }else{
      $(this).addClass('selected-payment');
    }
  }); //End selecct attribute buttom

  $('#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) {
            $('.confirm').prop("disabled",true);
            var sale_id = "<%= @sale.sale_id %>";
            // console.log(sale_id)
            var ajax_url = "/transactions/sales/" + sale_id + '/cashier/void';
            var remark  = $("#remark").val();

            $.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 = '/transactions/sales/';
                }
            });
          }
        });
      }else{
        swal("Opps","You are not authorized for void","warning")
      }
    });

  $(".choose_payment").on('click', function () {
      $("#loading_wrapper").show();
      var sale_id = "<%= @sale.sale_id %>";
      var type    = get_selected_attributes('selected-payment');
      var tax_type = localStorage.getItem("tax_type") ? localStorage.getItem("tax_type") : 'all';

      // console.log(type);

      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 || parseInt(jQuery.inArray("PAYMAL",type))!= -1) {
          if(!location.pathname.includes("credit_payment")){
           calculate_member_discount(sale_id,"Card",tax_type);
          }
        }else{
          if(!location.pathname.includes("credit_payment")){
            calculate_member_discount(sale_id,"Cash",tax_type);
          }
        }
      }

      $( "#loading_wrapper" ).hide();
      receipt_no = "<%= @sale.receipt_no %>";
      if((receipt_no!=undefined) && (receipt_no!=""))
        createReceiptNoInFirstBillData(receipt_no,type);

      window.location = '/origami/sale/'+sale_id+'/transaction/payment';
  });

  $('#pay').on('click', function() {
    var sale_id = "<%= @sale.sale_id %>";
    window.location = '/origami/sale/'+sale_id+'/transaction/payment';
  });
  $(document).on('click', '.access_modal', function(event){
       type = $(this).data("type");
       $(".ok").attr("data-action",type);
       $('#AccessCodeModal').modal('show');
     });

  $(document).on('click', '.access_number', function(event){
       if(event.handled !== true) {
         var original_value = $('#access_code').val();
         var input_type = $(this).attr("data-type");

         switch (input_type) {
             case 'num':
               var input_value = $(this).attr("data-value");
               if (original_value){
                 $('#access_code').val(original_value + input_value);
               }else{
                 $('#access_code').val(original_value + input_value);
               }
               break;
             case 'ok':
               var type = $(this).attr("data-action");
               code = $('#access_code').val();
               check_emp_access_code(code,type)
               break;
             case 'clr':
               $('#access_code').val("");
               break;
         }
         event.handled = true;
       } else {
           return false;
       }
     });

  function createAccessCode(code) {
  localStorage.setItem("access_code",code);
  }
  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 == "void"){
                $('#AccessCodeModal').modal('hide');
                $('#voidModal').modal('show');
              }
            }else{
              swal("Oops",result.message,"warning");
            }
         }
     });
  }
</script>
