<%= form_for(@cash_registers_move, remote: true, html: { class: "form-horizontal", id: "cash_register_move_form" }) do |f| %>
  <%= f.hidden_field(:open_cash_register_id, value: @sale.open_cash_register_id) %>
  <%= f.hidden_field(:sale_id, value: @sale.id) %>
  <div class="portlet-body form">
    <div class="alert alert-danger hidden" id="error_explanation_move"></div>
    <div class="row">
      <!-- div para mostrar total -->
      <div class="col-md-12">
        <div class="note note-success row" style="padding: 0px;">
          <div class="col-md-12">
            <div class="col-md-4" style="padding-left:0px"><h3 class="block">Total:</h3></div>
            <div class="col-md-8 text-center" style="margin-top:10px;padding-right: 0px;">
              <h3 class="pull-right"><%= number_to_currency(@sale.total, precision: 2) %></h3>
            </div>
          </div>
          <div class="col-md-12">
            <div class="col-md-4" style="padding-left:0px"><h4 class="block">Restante:</h4></div>
            <%= hidden_field_tag 'sale_total', @sale.total %>
            <div class="col-md-8 text-center" style="margin-top:10px;padding-right: 0px;">
              <h4 id="display_total" class="pull-right"><%= number_to_currency(@sale.total, precision: 2) %></h4>
            </div>
          </div>
        </div>
      </div>
      <!-- detalles y folio del pago -->
      <div class="col-md-6">
        <span>Folio:</span> <br/>
        <span><%= @sale.sale_code %></span>
        <%= f.hidden_field(:ticket, value: @sale.sale_code) %>
      </div>
      <!-- div fecha -->
      <div class="col-md-6">
        <div class="col-md-6 pull-right" style="padding-left:0px;padding-right:0px;">
            <div class='input-group date' id='datetimepicker2'>
                <input type='text' class="form-control" disabled/>
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
      </div>
      <div class="col-md-12">
        <h4 class="form-section" style="margin-top:5px;margin-bottom:5px"></h4>
      </div>
      <!-- div para agregar cantidad con forma de pago -->
      <div class="col-md-12" style="margin-top:10px">
        <!-- cantidad -->
        <div class="col-md-5">
          <div class="form-group">
            <span class="help-block">monto recibido. </span>
            <div class="input-group col-md-11">
              <span class="input-group-addon"> $ </span>
              <%= f.number_field :received, { class: "form-control mask_decimal first_input"} %>
            </div>
          </div>
        </div>
        <!-- metodo de pago -->
        <div class="col-md-4">
          <div class="form-group">
            <div class="input-group col-md-12">
              <span class="help-block">seleccione forma de pago. </span>
              <%= f.select :payment_method_id, PaymentMethod.vigentes.map { |c| [c.method, c.id] }, { include_blank: "Seleccione", selected: @cash_id}, { class: "form-control" }   %>
            </div>
          </div>
        </div>

        <div class="col-md-3" style="margin-top: 30px;">
          <button id="addrowBtn" type="button" class="btn green pull-right" onclick="addRow()">Agregar pago</button>
        </div>
        <!--  datos de la tarjeta cuando aplica -->
        <div class="col-md-12" id="card_info" style="display: none;">
          <div class="form-group">
            <%= f.label :cardnumber, { class: "col-md-3 control-label" } do %> Tarjeta: <span class="required">*</span>
            <% end %>
            <div class="col-md-8">
              <%= f.text_field :cardnumber, { class: "form-control input-small", maxlength: 4 } %>
              <span class="help-block">Últimos 4 dígitos de la tarjeta. </span>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-12">
        <table class="table table-striped table-hover table-bordered" id="payments_table">
          <thead>
            <tr>
              <th> Recibido </th>
              <th> Cobro </th>
              <th> Forma de pago </th>
              <th> Info. adicional </th>
              <th> Acciones </th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
      </div>
      <!-- div para mostrar total -->
      <div class="col-md-offset-6 col-md-6">
        <div class="note note-success row" style="padding: 0px;">
          <div class="col-md-12">
            <div class="col-md-4" style="padding-left:0px"><h4 class="block pull-left">Cambio:</h4></div>
            <div class="col-md-8 text-center" style="margin-top:10px;padding-right: 0px;">
              <h4 id="display_change" class="pull-right"></h4>
            </div>
          </div>
        </div>
      </div>
      <div class="col-md-12">
        <% if @sale.cash? %>
          <span class="help-block">Este botón se habilita cuando se cubre en su totalidad el monto de la venta. </span>
        <% end %>
        <button type="button" class="btn green btn-block" id="save_move" disabled onclick="confirmPayments()">Cobrar</button>
      </div>
    </div>
<% end %>
<script type="text/javascript">
  // var received_cash = 0;
  var totalInTable = 0;

  // no dejar que cierren el modal porque la venta ya se creó
  <% if @sale.cash? %>
    $('#closemodal').removeAttr('data-dismiss');
    if (window.location.pathname == "/sales/new") {
      $( "#closemodal" ).click(function() {
        if (window.confirm("Está seguro que desea SALIR?, al salir SE CANCELARÁ LA VENTA")) {
          $.ajax({
            type: "DELETE",
            url: "/sales/" + <%= @sale.id %> ,
            dataType: "json",
            data: {
              return_cash: true
            },
            success: function(xhr, status, error) {
              window.location = "<%= new_sale_path %>";
            }
          });
        }
      });
    }
  <% end %>

  $('#datetimepicker2').datetimepicker({
    icons: {
      date: "fa fa-calendar"
    },
    format: "DD/MM/YYYY",
    defaultDate: new Date()
  });

  $('#cash_registers_move_payment_method_id').on('change', function() {
    if ($(this).val() != <%= @cash_id %>) {
      $("#card_info").fadeIn();
    } else {
      $("#card_info").fadeOut();
      $("#cash_registers_move_cardnumber").val("");
    }
  });

  $("#cash_register_move_form").bind('ajax:complete', function() {
    calculatePendingTotal();
    calculateChange();
    $('#cash_registers_move_received').val('');
  });


  function addRow() {
    $('#cash_register_move_form').submit();
  }

  function unlockConfirmPayment() {
    var total = parseFloat($('#sale_total').val());
    totalInTable = 0;
    $('#payments_table tbody tr').each(function() {
      totalInTable += parseFloat($(this).find("td:nth-child(2) input").val());
    });
    if (totalInTable >= total) {
      $('#save_move').attr('disabled', false);
    } else {
      $('#save_move').attr('disabled', true);
      $('#addrowBtn').attr('disabled', false);
    }
  }

  function deleteCashMove(input) {
    var idText = input.closest('tr').attr('id');
    var cashMoveId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
    $.ajax({
      type: "DELETE",
      url: "/cash_registers_moves/" + cashMoveId,
      dataType: "json",
      data: "",
      success: function(xhr, status, error) {
        input.closest('tr').remove();
        unlockConfirmPayment();
        calculatePendingTotal();
        calculateChange();
      }
    });
  }

  function confirmPayments() {
    $.ajax({
      type: "POST",
      url: "/confirm_payments/",
      data: {
        sale_id: $('#cash_registers_move_sale_id').val()
      },
      dataType: "script",
      success: function(xhr, status, error) {
      }
    });
  }

  function calculatePendingTotal() {
    totalInTable = 0;
    var total = parseFloat($('#sale_total').val());
    $('#payments_table tbody tr').each(function() {
      totalInTable += parseFloat($(this).find("td:nth-child(2) input").val());
    });
    // $('#display_total').html(formatter.format(total - totalInTable));
    $('#display_total').html(accounting.formatMoney(total - totalInTable));

    if (totalInTable >= total) {
      $('#addrowBtn').attr('disabled', true);
    }
  }

  function calculateChange() {
    var total = parseFloat($('#sale_total').val());
    var received_cash = parseFloat($('#cash_registers_move_received').val());
    totalInTable = 0;
    var cash = 0;
    var card = 0;
    $('#payments_table tbody tr').each(function() {
      totalInTable += parseFloat($(this).find("td:nth-child(2) input").val());
      if ($(this).find("td:nth-child(3) input").val() == <%= @cash_id %>) {
        cash += parseFloat($(this).find("td:nth-child(1) input").val());
      } else {
        card += parseFloat($(this).find("td:nth-child(2) input").val());
      }
    });
    rest = totalInTable - card;
    if(cash + card == total || cash - rest <= 0 ){
      $('#display_change').html(accounting.formatMoney(0));
    } else {
      $('#display_change').html(accounting.formatMoney(cash - rest));
    }
  }
</script>
