<%= form_for(@cash_out, :remote => true, :html => {:class=>"form-horizontal", :id=> "cash_out_form"}) do |f| %>
  <div class="portlet-body form">
    <div class="alert alert-danger hidden" id="error_explanation"></div>
  <div class="col-md-12">
    <%= hidden_field_tag 'open_cash_register_id', @opened_cash_register.id %>
    <%= hidden_field_tag 'cash_payment_id', @cash_payment_method_id %>
    <div class="form-group">
      <%= f.label :received_by_id, "Recibe", {:class=>"col-md-3 control-label"} do %> Recibe
      <span class="required">*</span>
      <% end %>
      <div class="input-group col-md-6 select2-bootstrap-prepend">
        <%= f.collection_select :received_by_id, User.where(:pointsale_id => current_user.pointsale_id), :id, :userid, {:prompt => "Seleccione" },
        {:class => "form-control select2"} %>
      </div>
    </div>
    <h4 class="form-section" style="margin:0px 0px 30px 0px"> Resumen</h4>
    <div class="col-md-4" style="padding-left: 0px">
      <ul class="list-group">
        <li class="list-group-item list-group-item"> Efectivo inicial
          <span class="pull-right label label-info"><%= number_to_currency(@initial_cash, precision: 2) %></span>
        </li>
        <li class="list-group-item list-group-item"> Ventas de contado
          <span class="pull-right label label-info"><%= number_to_currency(@cash_sales, precision: 2) %></span>
        </li>
        <li class="list-group-item list-group-item"> Apartados<br>(anticipos, abonos y liquidaciones)
          <span class="pull-right label label-info"><%= number_to_currency(@reserved_sales, precision: 2) %></span>
        </li>
        <li class="list-group-item list-group-item"> Abonos a crédito
          <span class="pull-right label label-info"><%= number_to_currency(@credit_sales, precision: 2) %></span>
        </li>
        <li class="list-group-item list-group-item"> Total de egresos
          <span class="pull-right label label-info"><%= number_to_currency(@expenses_total, precision: 2) %></span>
        </li>
      </ul>
    </div>
    <div class="col-md-offset-2 col-md-6" style="padding-right:0px">
        <div class="form-group credit_limits">
          <%= f.label :physical_cash, {:class=>"col-md-4 control-label"} do %>Efectivo en caja<span class="required">*</span> <% end %>
          <div class="col-md-8">
            <div class="input-group">
              <span class="input-group-addon"> $ </span>
              <%= f.text_field :physical_cash, {:class=>"form-control mask_decimal"} %>
            </div>
            <span class="help-block">Es el dinero que se tiene físicamente en caja. </span>
          </div>
        </div>
        <div class="form-group credit_limits">
          <%= f.label :received_cash, {:class=>"col-md-4 control-label"} do %>Retiro de efectivo<span class="required">*</span> <% end %>
          <div class="col-md-8">
            <div class="input-group">
              <span class="input-group-addon"> $ </span>
              <%= f.text_field :received_cash, {:class=>"form-control mask_decimal", :oninput => "receivedAndFundCash()", :disabled => true} %>
            </div>
          </div>
        </div>
        <div class="form-group credit_limits">
          <%= f.label :cash_fund, {:class=>"col-md-4 control-label"} do %>Fondo de caja<span class="required">*</span> <% end %>
          <div class="col-md-8">
            <div class="input-group">
              <span class="input-group-addon"> $ </span>
              <%= text_field_tag :cash_fund_display, '', class: "form-control mask_decimal", disabled: true %>
                <!-- < %= f.hidden_field(:cash_fund) %> -->
              <%= f.hidden_field :cash_fund, {:class=>"form-control mask_decimal"} %>
            </div>
          </div>
        </div>
        <div class="form-group credit_limits">
          <%= f.label :observations, {:class=>"col-md-4 control-label"} do %>Observaciones<span class="required" id="required_observations"></span> <% end %>
          <div class="col-md-8">
            <div class="input-group">
              <span class="input-group-addon"> <i class="fa fa-comment-o"></i> </span>
                <%= f.text_area :observations, {:class=>"form-control", :rows=>5 } %>
            </div>
          </div>
        </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="table-scrollable">
            <table class="table table-hover table-striped table-bordered" id="payment_methods_table">
                <thead>
                    <tr>
                        <th> # </th>
                        <th> Método de pago </th>
                        <th> Total de ingresos (ventas) </th>
                        <th> Total de egresos (gastos) </th>
                        <th>Total (ventas y efectivo inicial)</th>
                    </tr>
                </thead>
                <tbody>
                  <% @payments.each_with_index do |payment, key| %>
                    <tr id="payment_<%= payment['payment_method_id']%>">
                      <td> <%= key +1 %> </td>
                      <td> <%= payment["method"] %> </td>
                      <td> <%= number_to_currency(payment["incoming"], precision: 2) %> </td>
                      <td class="danger"> <%= number_to_currency(payment["outgoing"], precision: 2) %> </td>
                      <td>
                        <%= number_to_currency(payment["total"], precision: 2) %>
                        <input class="hidden" value="<%= payment["total"] %>" id="<%=key + 1%>">
                      </td>
                    </tr>
                        <%= f.fields_for :cash_out_details do |ff| %>
                        <%= ff.hidden_field :payment_method_id, :value => payment["payment_method_id"] %>
                        <%= ff.hidden_field :incoming, :value => payment["incoming"] %>
                        <%= ff.hidden_field :outgoing, :value => payment["outgoing"] %>
                        <%= ff.hidden_field :total, :value => payment["total"] %>
                        <% end %>
                  <% end %>
                </tbody>
            </table>
        </div>
      </div>
    </div>
    <h4 class="form-section"> Ingresos del día</h4>
    <table class="table table-striped table-bordered table-hover tableadvanced">
      <thead>
        <tr>
          <th>#</th>
          <th>Folio</th>
          <th>Caja registradora</th>
          <th>Método de pago</th>
          <th>Cantidad</th>
          <th>Concepto</th>
          <th>Hora</th>
        </tr>
      </thead>
      <tbody>
        <% @incomings.each_with_index do |move, key| %>
        <tr>
          <td><%= key + 1 %></td>
          <td>
            <% case move.concept %>
              <% when "sale",  "reserved_payment", "reserved_first_payment", "reserved_last_payment" %>
                <%= move.sale.sale_code %>
              <% when "purchase"%>
                <%= move.purchase.purchase_code %>
              <% when "expense"%>
                <%= move.expense.expense_code %>
              <% when "credit_payment"%>
                <%= move.credit_payment.id %>
              <% when "products_return"%>
                <%= move.products_return.sale.sale_code %>
            <% end %>
          </td>
          <td><%= move.open_cash_register.cash_register.name%></td>
          <td><%= move.payment_method.method %></td>
          <td><%= number_to_currency(move.quantity, precision: 2) %></td>
          <td>
            <% case move.concept %>
              <% when "sale"%>
                VENTA
              <% when "purchase"%>
                COMPRA CANCELADA
              <% when "expense"%>
                GASTO CANCELADO
              <% when "credit_payment"%>
                <strong>ABONO A CRÉDITO </strong><br>
                cliente: <%= move.credit_payment.customer.nick_name %>
              <% when "reserved_payment"%>
                ABONO A APARTADO
              <% when "reserved_first_payment" %>
                ANTICIPO DE APARTADO
              <% when "reserved_last_payment" %>
                LIQUIDACIÓN DE APARTADO
              <% when "products_return" %>
                DIFERENCIA POR DEVOLUCIÓN
            <% end %>
          </td>
          <td><%= l(move.created_at, :format => '%I:%M %p') %> </td>
        </tr>
        <% end %>
      </tbody>
    </table>

    <h4 class="form-section"> Egresos del día</h4>
    <table class="table table-striped table-bordered table-hover tableadvanced">
      <thead>
        <tr>
          <th>#</th>
          <th>Folio</th>
          <th>Caja registradora</th>
          <th>Método de pago</th>
          <th>Cantidad</th>
          <th>Concepto</th>
          <th>Hora</th>
        </tr>
      </thead>
      <tbody>
        <% @outgoings.each_with_index do |move, key| %>
        <tr>
          <td><%= key + 1 %></td>
          <td>
            <% case move.concept %>
              <% when "sale",  "reserved_payment" %>
                <%= move.sale.sale_code %>
              <% when "purchase"%>
                <%= move.purchase.purchase_code %>
              <% when "expense"%>
                <%= move.expense.expense_code %>
              <% when "credit_payment"%>
                <%= move.credit_payment.id %>
            <% end %>
          </td>
          <td><%= move.open_cash_register.cash_register.name%></td>
          <td><%= move.payment_method.method %></td>
          <td><%= number_to_currency(move.quantity, precision: 2) %></td>
          <td>
            <% case move.concept %>
              <% when "sale" %>
                <% if move.sale.cash? %>
                  VENTA CANCELADA
                <% elsif move.sale.reserved? %>
                  APARTADO CANCELADO
                <% end %>
              <% when "purchase"%>
                COMPRA
              <% when "expense"%>
                <strong> <%= move.expense.expensesconcept.name %></strong> <br>
                <%= move.expense.observations %>
              <% when "credit_payment"%>
                ABONO CANCELADO
            <% end %>
          </td>
          <td><%= l(move.created_at, :format => '%I:%M %p') %> </td>
        </tr>
        <% end %>
      </tbody>
    </table>
  </div>

  <!-- acciones del form -->
    <div style="margin-top: 30px">
      <div class="row">
        <div class="col-md-9">
        <button type="button" class="btn green" onclick="addCashOut()" disabled id="submit_cash_out">Guardar</button>
          <%= link_to 'Cancelar', root_path, {:class=>"btn default"} %>
        </div>
      </div>
    </div>
  </div>
<% end %>

<script type="text/javascript">
  var timeout = null;
  var cashOutValid = false;

  $(document).on("page:change", function() {
    $('.dataTables_filter').hide();

    $('#cash_out_physical_cash').keyup(function() {
      var physicalCash = $('#cash_out_physical_cash').val();
      if(physicalCash) {
        $('#cash_out_received_cash').attr('disabled', false);
      } else {
        $('#cash_out_received_cash').attr('disabled', true);
        $('#cash_out_received_cash').val('');
      }
    });

    $('#cash_out_physical_cash').keyup(function() {
      receivedAndFundCash();
    });

  });

  function addCashOut() {
    if($("#cash_out_received_by_id option:selected").val() && $("#cash_out_received_cash").val()) {
      $("#cash_out_form").submit();
    } else {
      toastr["error"]("Faltan datos del formulario");
    }
  }

  function receivedAndFundCash() {
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      var physicalCash = parseFloat($('#cash_out_physical_cash').val());
      var receivedCash = parseFloat($('#cash_out_received_cash').val());

      if(!isNaN(physicalCash) && !isNaN(receivedCash)) {
        var cashFund = physicalCash - receivedCash;
        $('#cash_out_cash_fund').val(cashFund);
        $('#cash_fund_display').val(cashFund);

        if(receivedCash > physicalCash) {
          toastr["error"]("El retiro de efectivo no puede ser mayor al efectivo disponible en caja.");
          $('#submit_cash_out').addClass('disabled');
          $('#cash_out_cash_fund').val('');
          $('#cash_fund_display').val('');
        } else {
          $('#submit_cash_out').attr('disabled', false);
        }
      } else {
        $('#submit_cash_out').attr('disabled', true);
      }
    }, 300);
  }
</script>
