<%= 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>
            <%= hidden_field_tag 'sale_total', @sale.total %>
            <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-6" style="padding-left:0px"><h4 class="block">Adeudo:</h4></div>
            <%= hidden_field_tag 'reserve_debt', @sale.reserve_debt %>
            <div class="col-md-6 text-center" style="margin-top:10px;padding-right: 0px;">
              <h4 id="display_debt" class="pull-right"><%= number_to_currency(@sale.reserve_debt, precision: 2) %></h4>
            </div>
          </div>
        </div>
      </div>
      <!-- detalles y folio del pago -->
      <div class="col-md-12">
        <h4 class="form-section" style="margin-bottom: 15px;margin-top: 15px;">Pagos anteriores</h4>
        <div class="table-scrollable table-scrollable-borderless">
            <table class="table table-hover table-light">
                <thead>
                    <tr class="uppercase">
                      <th>#</th>
                      <th>Metodo de pago</th>
                      <th>Monto</th>
                      <th>Info. Adicional</th>
                    </tr>
                </thead>
                <tbody>
                  <% @payments.each_with_index do |payment, key| %>
                    <tr>
                      <td> <%= key + 1 %> </td>
                      <td> <%= payment.payment_method.method %> </td>
                      <td> <%= number_to_currency(payment.quantity, precision: 2) %> </td>
                      <td> <%= payment.cardnumber %> </td>
                    </tr>
                  <% end %>
                </tbody>
            </table>
        </div>
      </div>
      <div class="col-md-12">
        <h4 class="form-section" style="margin-top:15px;margin-bottom:15px">Nuevo pago</h4>
        <!-- div fecha -->
        <div class="col-md-12" style="margin-bottom:15px;padding-right:0px">
          <div class="col-md-4 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" style="padding:0px">
          <!-- recibido -->
          <div class="col-md-4">
            <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>
          <!-- cantidad -->
          <div class="col-md-4">
            <div class="form-group">
              <span class="help-block">monto a ABONAR. </span>
              <div class="input-group col-md-11">
                <span class="input-group-addon"> $ </span>
                <%= f.number_field :quantity, {:class=>"form-control mask_decimal"} %>
              </div>
            </div>
          </div>
          <!-- metodo de pago -->
          <div class="col-md-2">
            <div class="form-group">
              <span class="help-block">forma de pago. </span>
              <div class="input-group col-md-12">
                <%= 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>
          <!-- boton agregar -->
          <div class="col-md-2" style="padding-right:0px; margin-top:30px">
            <button type="button" class="btn green pull-right" onclick="addRow()">Agregar</button>
          </div>
        </div>
        <!--  datos de la tarjeta cuando aplica -->
        <div class="col-md-offset-6 col-md-6" id="card_info" style="display: none;">
          <div class="form-group">
            <%= f.label :cardnumber, {:class=>"col-md-2 control-label "} do %> Tarjeta: <span class="required">*</span>
            <% end %>
            <div class="col-md-6">
              <%= 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 cambio -->
      <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">
       <span class="help-block">Este botón se habilita cuando se registre un pago. </span>
        <button type="button" class="btn green btn-block" disabled id="save_move" onclick="saveMoves()">Aceptar</button>
      </div>
    </div>
  </div>
<% end %>
<script type="text/javascript">
  $('#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();
      $('#cash_registers_move_received').attr('disabled', true);
      $('#cash_registers_move_received').val("");
    } else {
      $("#card_info").fadeOut();
      $("#cash_registers_move_cardnumber").val("");
      $('#cash_registers_move_received').attr('disabled', false);
    }
  });

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

  function addRow() {
    debt = parseFloat($('#reserve_debt').val());
    quantity = parseFloat($('#cash_registers_move_quantity').val());
    received = parseFloat($('#cash_registers_move_received').val());
    payment_method = $('#cash_registers_move_payment_method_id option:selected').val();

    if (((quantity <= debt && quantity > 0) && (received >= quantity && payment_method == "2")) || (payment_method == "1" && quantity > 0) ) {
      $('#cash_register_move_form').submit();
    } else if (quantity > debt || quantity == 0) {
      toastr["error"]("El monto a abonar no puede ser mayor al adeudo, ni puede ir en ceros");
    } else if ((received <= 0 || quantity > received) && payment_method == "2") {
      toastr["error"]("La cantidad recibida no puede ir en ceros, ni se puede abonar más de lo recibido");
    }
  }

  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();
        calculateChange();
      }
    });
  }

  function saveMoves() {
    $.ajax({
      type: "POST",
      url: "/add_payments_to_reserve/" + $('#cash_registers_move_sale_id').val(),
      dataType: "script",
      success: function(xhr, status, error) { }
    });
  }

  function unlockConfirmPayment() {
    totalInTable = 0;
    var debt = parseFloat($('#reserve_debt').val());

    $('#payments_table tbody tr').each(function() {
      totalInTable += parseFloat($(this).find("td:nth-child(2) input").val());
    });

    // $('#display_debt').html(formatter.format(debt - totalInTable));
    $('#display_debt').html(accounting.formatMoney(debt - totalInTable));

    if ($("#save_move").prop('disabled')) {
      $("#save_move").attr('disabled', false);
    } else if (!$("#save_move").prop('disabled') && $('#payments_table tbody tr').length == 0) {
      $("#save_move").attr('disabled', true);
    }
  }

  function calculateChange() {
    var total = parseFloat($('#reserve_sale_percent').val());
    var received_cash = parseFloat($('#cash_registers_move_received').val());
    totalInTable = 0;

    $('#payments_table tbody tr').each(function() {
      if ($(this).find("td:nth-child(3) input").val() == <%= @cash_id %>) {
        totalInTable += parseFloat($(this).find("td:nth-child(2) input").val());
      }
    });

    var change = received_cash - totalInTable;
    if (change > 0 && totalInTable > 0) {
      // $('#display_change').html(formatter.format(change));
      $('#display_change').html(accounting.formatMoney(change));

    } else {
      // $('#display_change').html(formatter.format(0));
      $('#display_change').html(accounting.formatMoney(0));
    }
  }
</script>
