<div class="container-fluid">
 <!--  <div class="page-header">
   <ul class="breadcrumb">
    <li class="breadcrumb-item"><a href="<%= dashboard_path %>">Home</a></li>
    <li class="breadcrumb-item active">CRM</li>
     <li class="breadcrumb-item"><a href="<%= dashboard_path %>">Home</a></li>
    <span class="float-right">
      <a href="#" id="back">Back</a>
    </span>
  </ul>
</div> -->


<div class="row">
  <div class="col-lg-8 col-md-8 col-sm-8">
    <div class="card">
      <div class="body">
        <div class="row p-t-20 p-l-20">
          <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <!--  <% path ="/origami/#{@sale_id}/customers" %>
            <%= form_tag path, :id => "filter_form", :method => :get do %>
              <div class="input-append col-md-7 form-group pull-left">
                <input type="text" name="filter" style="margin-right:10px" id="search" placeholder="Search" class="form-control input-sm col-md-9">
                <input type="hidden" name="type" id="type" value="">
                <button type="submit" class="btn btn-primary btn-sm">Search</button>                        
              </div>
            <% end %>
            <button id="member_acc_no" class="btn btn-success btn-sm"><span class="fa fa-credit-card"></span> Member Card</button> -->
              <% path ="/origami/#{@sale_id}/customers" %>
              <%= form_tag path, :id => "filter_form", :method => :get do %>
              <div class="row clearfix">
                <div class="col-lg-5 col-md-5 col-sm-5 col-xs-12">

                 <input type="text" name="filter" style="margin-right:10px" id="search" placeholder="Search" class="form-control input-sm col-md-12">
                 <!-- <input type="hidden" name="type" id="type" value="<%= @dining_facility.type %>"> -->

               </div>
               <div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
                <button type="submit" class="btn bg-blue waves-effect waves-effect">Search</button>
              </div>

              <button type="button" id="member_acc_no" class="btn bg-green btn-sm waves-effect" style="height: 30%;margin-right: 10px;">Member Card</button>

            </div>
            <% end %>
          </div>
        </div>
        <div class="main-box-body clearfix" id="order-detail-slimscroll" style="">
          <div class="table-responsive">
            <table id="origami-crm-table" class="table table-striped" style="width:100%">
              <thead>
                  <tr>
                    <th></th>
                    <th><%= t("views.right_panel.detail.sr_no") %></th>
                    <th><%= t("views.right_panel.detail.name") %></th>
                    <th><%= t("views.right_panel.detail.card_no") %></th>
                    <th style="width:20%"><%= t("views.right_panel.detail.contact_no") %></th>
                    <th style="width:20%"><%= t("views.right_panel.detail.email") %></th>
                    <!-- <th>Paypar No</th> -->
                  </tr>
                </thead>

                <tbody>
                  <% if @crm_customers.count > 0  %> 
                  <% @i = 0 %>
                  <% @crm_customers.each do |crm_customer| %>

                  <tr class="customer_tr" data-ref="<%= crm_customer.customer_id %>">
                   <td>
                     <input type="radio" style="width:20px;" name="checkbox" class="checkbox_check" ></td>
                     <td>
                      <% if crm_customer.customer_id != "CUS-000000000001" && crm_customer.customer_id != "CUS-000000000002" %> 
                      <%= @i += 1 %>
                      <%else%>
                      -
                      <% end %>
                    </td>
                    <td><%= crm_customer.name %></td>
                    <td><%= crm_customer.company rescue '-' %></td>
                    <td style="width:20%;word-break: break-all;"><%= crm_customer.contact_no %></td>
                    <td style="width:20%;word-break: break-all;"><%= crm_customer.email %></td>
                    <!-- <td><%= crm_customer.paypar_account_no %></td> -->

                  </tr>
                  <% end %>
                  <%else%>
                  <tr><td colspan="5"><p style="text-align:center"><strong>There are no record for your search</strong></p></td></tr>
                  <% end %>
                </tbody>
              </table>
              <br>

              <%= paginate @crm_customers %>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- <div class="col-lg-4 col-md-4 col-sm-4" style="min-height:600px; max-height:600px; overflow-x:scroll"> -->
    <div class="col-lg-3 col-md-3 col-sm-3" >
      <div class="card">
      <div class="body" id="custom-slimscroll">
          <%= simple_form_for @crm_customer,:url => crm_customers_path, :method => :post do |f| %>

          <span class="patch_method"></span>
          <input type="hidden" id="sale_id" name="sale_id" value="<%= @sale_id %>" />
          <input type="hidden" id="table_id" name="table_id" value="<%= @dining_facility.id %>" />
          <input type="hidden" id="type" name="type" value="<%= @dining_facility.type %>" />
          <%= f.error_notification %>
          <%= f.hidden_field :id, :class => "form-control col-md-6 " %>    
          <div class="form-group">
            <label><%= t("views.right_panel.detail.salutation") %> :</label><br>
            <label class="font-15"><%= t("views.right_panel.detail.mr") %>
            <%= f.radio_button :salutation,"Mr", :class => "salutation mr", :value=>"Mr"%></label>
            <label class="font-15 m-l-5"><%= t("views.right_panel.detail.miss") %>
            <%= f.radio_button :salutation,"Mrs", :class => "salutation mrs", :value=>"Mrs"%></label>
            <label class="font-15 m-l-5"><%= t("views.right_panel.detail.mrs") %>
            <%= f.radio_button :salutation,"Miss", :class => "salutation miss", :value=>"Miss"%></label>
            <label class="font-15 m-l-5"><%= t("views.right_panel.detail.mdm") %>
            <%= f.radio_button :salutation,"Mdm", :class => "salutation mdm", :value=>"Mdm"%></label>
          </div>

          <div class="form-group <%= (flash["errors"]) ? "has-error" : "" %>">
            <%= f.input :name, :class => "form-control col-md-6 name", :required => true %>

            <% flash.each do |name, msg| %>
            <% str="[\"#{msg['name']}\"]"
            str.gsub!('["', '')
            str.gsub!('"]', '') %>
            <span class="help-block"><%= str %></span>
            <% end -%>
          </div>

          <div class="form-group">
            <label><%= t("views.right_panel.detail.gender") %> :</label><br>
            <label><%= t("views.right_panel.detail.male") %>
            <%= f.radio_button :gender,"Male", :class => "gender male", :value=>"Male", :style=>"width: 30px"%></label>
            <label><%= t("views.right_panel.detail.female") %>
            <%= f.radio_button :gender,"Female", :class => "gender female", :value=>"Female", :style=>"width: 30px"%></label>
          </div>

          <div class="form-group">
            <%= f.input :nrc_no, :label => "NRC No",:class => "form-control nrc_no" %>
          </div>
          <div class="form-group">
            <%= f.input :company, :class => "form-control col-md-6 company"%>

            <%  flash.each do |name, msg| %>
            <% str="[\"#{msg['company']}\"]"
            str.gsub!('["', '')
            str.gsub!('"]', '') %>
            <span class="help-block"><%= str %></span>
            <% end -%>
          </div>
          <div class="form-group <%= (flash["errors"]) ? "has-error" : "" %>">
            <%= f.input :contact_no, :class => "form-control col-md-6 contact_no" ,:required => true%>

            <%  flash.each do |name, msg| %>
            <% str="[\"#{msg['contact_no']}\"]"
            str.gsub!('["', '')
            str.gsub!('"]', '') %>
            <span class="help-block"><%= str %></span>
            <% end -%>
          </div>

          <div class="form-group <%= (flash["errors"]) ? "has-error" : "" %>">
            <%= f.input :email, :class => "form-control col-md-6 email" ,:required => true%>
            <% flash.each do |name, msg| %>
            <% str="[\"#{msg['contact_no']}\"]"
            str.gsub!('["', '')
            str.gsub!('"]', '') %>
            <span class="help-block"><%= str %></span>
            <% end -%>
          </div>

          <div class="form-group">
            <%= f.input :address, :class => "form-control col-md-6 address" %>
          </div>

          <div class="form-group">
            <label><%= t("views.right_panel.detail.sr_no") %></label>
            <input type="text" name="" value="<%=@count_customer%>" class="form-control" readonly="true">
          </div>
          <div class="form-group">
            <label><%= t("views.right_panel.detail.date_of_birth") %></label>
            <%= f.text_field :date_of_birth,:value=>"01-01-1990",:class=>"form-control datepicker"%>
          </div>

          <div class="form-group">
            <label><%= t("views.right_panel.detail.select_customer_type") %></label>
            <select class="form-control col-md-12" id="customer_type" name="customer[customer_type]" style="height: 40px" >
              <%  Lookup.where("lookup_type = ?", "customer_type" ).each do |ct| %>
              <option value="<%= ct.value %>">
                <%= ct.name %></option>
                <%end %>
              </select>            
            </div>

            <div class="form-group">
              <%= f.input :tax_profiles, :collection => @taxes, :input_html => { :multiple => true },  :class => "form-control col-md-6 tax_profiles" %>
            </div>

            <div class="form-group <%= (flash["errors"]) ? "has-error" : "" %>">
              <%= f.input :card_no, :class => "form-control col-md-6 card_no"%>
              <% flash.each do |name, msg| %>
              <% str="[\"#{msg['name']}\"]"
              str.gsub!('["', '')
              str.gsub!('"]', '') %>
              <span class="help-block" style="margin-top:-10px"><%= str %></span>
              <% end -%>
            </div>
            <div class="form-group">
              <label><%= t("views.right_panel.detail.paypar_account_no") %>:</label>
              <div class="input-group">     
                <input type="text" class="form-control" id="paypar_account_no" name="customer[paypar_account_no]" readonly />
                <div class="input-group-addon"><span class="fa fa-credit-card"></span></div>
              </div>
            </div>

            <div class="form-group">
             <label><%= t("views.right_panel.detail.select_membership_group") %></label>
             <select class="form-control col-md-12" name="member_group_id">
              <option value=""><%= t("views.right_panel.detail.select_membership_group") %></option>
              <%  Lookup.where("lookup_type = ?", "member_group_type" ).each do |member| %>
              <option value="<%= member.value %>">
                <%= member.name %></option>
                <%end %>
              </select>
            </div>

            <div class="form-group">
              <%= f.submit t("views.btn.submit"),:class => 'btn btn-primary btn-lg waves-effect', :id => 'submit_customer' %>
              <!--  <%= f.button :submit, "Update",:class => 'btn bg-blue btn-block', :disabled =>'', :id => 'update_customer' %> -->
            </div>
            <%end%>
          </div>
        </div>
      </div>
      <!-- Column Three -->
      <div class="col-lg-1 col-md-1 col-sm-1">
       <button type="button" class="btn btn-default btn-block" id='back'><i class="material-icons">reply</i>Back</button>
     </div>
   </div>

   <div id="sxModal">
    <div id="sxModal-Content"><h3>Card Tap</h3></div>
  </div>
</div>
<script type="text/javascript">
  $(function() {
      /*$('.datepicker').datepicker({
       setDate: '12-12-1999',
       format : 'dd-mm-yyyy',
       autoclose: true
     });
      $('.datepicker').attr('ReadOnly','true');
      $('.datepicker').css('cursor','pointer');*/

    // Read Card Reader
    $("#paypar_account_no").on('focus', function(e){         
      if($(this).val() == ''){  
        $("#sxModal").show();
        setTimeout(function(){
          getCardNo();
          $("#sxModal").hide();
        },100);  
      }   
    });

    // Read Card Reader
    $("#member_acc_no").on('click', function(e){  
      var cardNo = ""; 
      var customer_id = '';
      var customer_name = '';
      var sale_id     = $("#sale_id").val() || 0;
      var customer_mamber_card_no = 0;
      $("#sxModal").show();   
      setTimeout(function(){
        getCardNo();
        $("#sxModal").hide();        
        customer_mamber_card_no = $("#search").val();

        if(sale_id != 0 && customer_mamber_card_no != 0){    
          $.ajax({
            type: "POST",
            url: "get_customer" ,
            data: { filter : customer_mamber_card_no ,type :"card"},
            dataType: "json",
            success: function(data) {
              if (data[0].customer_id == false) {
                $.alert({
                 title: 'Alert!',
                 content: data[0].message,
                 type: 'red',
                 typeAnimated: true,
                 btnClass: 'btn-danger',
               });
              }else{
                customer_id = data[0].customer_id;
                customer_name = data[0].name;
                update_sale(customer_id, customer_name,sale_id);
              }

            }
          });                
        }
      },100);
    });
  });


  // Read NFC card no from java
  function getCardNo(){
    code2lab.readNFC();
  }

  // get CardNo from Java
  function setCardNo(cardNo){
    if(cardNo.length == 16){
      $("#paypar_account_no").val(cardNo);
      $("#search").val(cardNo);
      $("#type").val("card")
    }
  }

  $(document).on('click',".customer_tr",function(){
     // if(this.checked){
      $(this).closest('tr').find('.checkbox_check').prop( "checked", true );
      var sale_id     = $("#sale_id").val() || 0;
      var customer_id = $(this).attr('data-ref');
      var customer_name = $(this).children("td:nth-child(3)").text();

      if(sale_id != 0){
              // var url = "/"+customer_id;
              update_sale(customer_id, customer_name,sale_id);
            }else{

              var url = "customers/"+customer_id;
            }

              // Need To Clean?
              $.ajax({
                type: "GET",
                url: url,
                data: {},
                dataType: "json",
                success: function(data) {
                  var taxes = JSON.stringify(data.tax_profiles);  
                  var parse_taxes = JSON.parse(taxes);  
                  $.each(parse_taxes, function(i, value){
                    $("#customer_tax_profiles option[value='" + value + "']").attr("selected","selected");
                  });
                  
                  $('#customer_id').val(data.id);
                  $('#customer_name').val(data.name);
                  $('#customer_company').val(data.company);
                  $('#customer_contact_no').val(data.contact_no);
                  $('#customer_email').val(data.email);
                  $('#customer_date_of_birth').val(data.date_of_birth);
                  $('#customer_membership_type').val(data.membership_type);
                  $('.select > option[value="'+data.membership_id+'"]').attr('selected','selected');
                  $('.membership_authentication_code').val(data.membership_authentication_code);
                  $('#customer_card_no').val(data.card_no);
                  $('#customer_type').val(data.customer_type);
                  $('#customer_salutation').val(data.salutation);
                  $('#customer_nrc_no').val(data.nrc_no);
                  $('#paypar_account_no').val(data.paypar_account_no);

                  if (data.gender == 'Male') {
                    $('.male').prop( "checked", true )
                  }else{
                    $('.female').prop( "checked", true )
                  }

                  if (data.salutation == 'Mr') {
                    $('.mr').prop( "checked", true )
                  } else if(data.salutation == 'Miss') {
                    $('.miss').prop( "checked", true )
                  }else if(data.salutation == 'Mrs'){
                    $('.mrs').prop( "checked", true )
                  }else{
                    $('.mdm').prop( "checked", true )
                  }

                  $('#update_customer').removeAttr('disabled').val('');
                  $('#update_customer').attr('value', 'Update');
                    // $('#submit_customer').attr('disabled','disabled');

                    $("#new_customer").attr('class', 'simple_form edit_customer');
                    var id = "edit_customer_"+$('#customer_id').val();
                    $("#new_customer").attr('id', id);
                    $(".edit_customer").attr('action', '/crm/customers/' + $('#customer_id').val());
                    $(".edit_customer").attr('action', '/crm/customers/' + $('#customer_id').val());
                    $(".patch_method").append('<input type="hidden" name="_method" value="patch">');
                    //$(".edit_customer").attr('method', 'PATCH');
                  }
                });
          // }else{

          // }
        })

  function update_sale(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 () {
      $.ajax({
        type: "POST",
        url: "update_sale" ,
        data: {customer_id:customer_id,sale_id:sale_id},
        dataType: "json",
        success: function(data) {
          if(data.status == true)
          {
            var id       = $("#table_id").val();
            var type     = $("#type").val();
            if (type=="Table") {
              window.location.href = '/origami/table/'+id
            }else{
             window.location.href = '/origami/room/'+id
           }
          }else{
            swal("Alert!", "Record not found!", "error");
            location.reload();
          }
        }
      });        
    });
  }

  $('#back').on('click',function(){
    var id       = $("#table_id").val()
    var type     = $("#type").val()
    if (type=="Table") {
      window.location.href = '/origami/table/'+id
    }else{
     window.location.href = '/origami/room/'+id
   }
 })

</script>

