<div class="row">
  <div class="col-md-12">
    <div class="card card-outline card-warning">
      <div class="card-header">
        <h3 class="card-title"><i class="fas fa-filter text-warning mr-2"></i> Filtro por fecha</h3>
      </div>
      <div class="card-body">
        <form class="form-horizontal" autocomplete="off">
          <div class="row">
            <div class="col-md-5">
              <div class="form-group">
                <label>Fecha Inicio</label>
                <input type="date" class="form-control" id="finicio" name="finicio" value="<?= date('Y-m-d') ?>">
              </div>
            </div>
            <div class="col-md-5">
              <div class="form-group">
                <label>Fecha Fin</label>
                <input type="date" class="form-control" id="factual" name="factual" value="<?= date('Y-m-d') ?>">
              </div>
            </div>
            <div class="col-md-2 d-flex align-items-end">
              <div class="form-group w-100">
                <button type="button" onclick="generado()" class="btn btn-warning btn-block" data-toggle="tooltip" title="GENERAR"><i class="fas fa-search"></i></button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-md-12">
    <div class="card card-outline card-primary">
      <div class="card-header">
        <h3 class="card-title"><i class="fas fa-file-invoice-dollar text-primary mr-2"></i> Lista de <?= $this->titulo_controlador ?></h3>
        <div class="card-tools">
          <a onclick="location.reload()" class="btn btn-default btn-sm" data-toggle="tooltip" title="RECARGAR"><i class="fas fa-sync-alt"></i></a>
          <a onclick="add()" class="btn btn-primary btn-sm" data-toggle="tooltip" title="Nuevo"><i class="fas fa-plus"></i> Nuevo <?= $this->titulo_controlador ?></a>
        </div>
      </div>
      <div class="card-body table-responsive">
        <table id="tabla" class="table table-hover table-bordered table-striped">
          <thead>
            <tr>
              <th width="50">#</th>
              <th>Nº Doc.</th>
              <th>Razón Social</th>
              <th>Concepto</th>
              <th>Observación</th>
              <th class="text-right">Monto</th>
              <th>Fecha</th>
              <th width="120">Acción</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"></h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form action="#" id="form" autocomplete="off">
          <input type="hidden" id="id" name="id">
          <div class="form-group">
            <label>Caja <span class="text-danger">*</span></label>
            <input type="hidden" name="caja" id="caja" value="<?= $caja ? $caja->id : '' ?>">
            <input type="text" class="form-control" name="cajas" id="cajas" value="<?= $caja ? $caja->descripcion.' | '.$caja->created.' | '.$caja->saldoinicial : '' ?>" readonly>
            <span class="help-block text-danger"></span>
          </div>
          <div class="form-group">
            <label>Concepto <span class="text-danger">*</span></label>
            <select id="concepto" name="concepto" class="form-control">
              <option value="">SELECCIONAR CONCEPTO</option>
              <?php foreach ($conceptos as $value) { ?>
                <option value="<?= $value->id ?>"><?= $value->concepto ?></option>
              <?php } ?>
            </select>
            <span class="help-block text-danger"></span>
          </div>
          <div class="form-group">
            <label>Monto <span class="text-danger">*</span></label>
            <input id="monto" name="monto" class="form-control money" type="text">
            <span class="help-block text-danger"></span>
          </div>
          <div class="form-group">
            <label>Observación <span class="text-danger">*</span></label>
            <textarea class="form-control" id="observacion" name="observacion" rows="3"></textarea>
            <span class="help-block text-danger"></span>
          </div>
          <div class="form-group">
            <label>Fecha</label>
            <input id="fecha" name="fecha" class="form-control" type="date" value="<?= date('Y-m-d') ?>">
            <span class="help-block text-danger"></span>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Guardar</button>
        <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
  var table;
  var dtlanguage = {
    "decimal": "",
    "emptyTable": "No hay información",
    "info": "Mostrando _START_ a _END_ de _TOTAL_ Entradas",
    "infoEmpty": "Mostrando 0 to 0 of 0 Entradas",
    "infoFiltered": "(Filtrado de _MAX_ total entradas)",
    "infoPostFix": "",
    "thousands": ",",
    "lengthMenu": "Mostrar _MENU_ Entradas",
    "loadingRecords": "Cargando...",
    "processing": "Procesando...",
    "search": "Buscar:",
    "zeroRecords": "Sin resultados encontrados",
    "paginate": {
      "first": "Primero",
      "last": "Ultimo",
      "next": "Siguiente",
      "previous": "Anterior"
    }
  };

  $(document).ready(function() {
    generado();
    $('.money').number(true, 2);
    $("#observacion").mayusculassintildes();
    $('#operacion').numeric();

    $("input, textarea, select").change(function() {
      $(this).removeClass('is-invalid');
      $(this).nextAll('.help-block').empty();
    });
  });

  function generado() {
    table = $('#tabla').DataTable({
      language: dtlanguage,
      "destroy": true,
      "ajax": {
        "url": "<?= $this->url ?>/ajax_list/" + $('#finicio').val() + '/' + $('#factual').val(),
        "type": "GET"
      },
    });
  };

  function add() {
    $('#form')[0].reset();
    $('.form-control').removeClass('is-invalid');
    $('.help-block').empty();
    $('#modal_form').modal('show');
    $('.modal-title').text('Crear <?= $this->titulo_controlador ?>');
  };

  function save() {
    $('#btnSave').text('guardando...').attr('disabled', true);
    $.ajax({
      url: "<?= $this->url ?>/ajax_add",
      type: "POST",
      data: $('#form').serialize(),
      dataType: "JSON",
      success: function(data) {
        if (data.status) {
          $('#modal_form').modal('hide');
          reload_table();
          Lobibox.notify('success', { size: 'mini', position: 'top right', msg: "El registro fue creado exitosamente." });
        } else {
          for (var i = 0; i < data.inputerror.length; i++) {
            $('[name="' + data.inputerror[i] + '"]').addClass('is-invalid');
            $('[name="' + data.inputerror[i] + '"]').nextAll('.help-block').text(data.error_string[i]);
          }
        }
        $('#btnSave').text('Guardar').attr('disabled', false);
      },
      error: function() {
        Lobibox.notify('error', { size: 'mini', position: 'top right', msg: "Error al procesar el registro." });
        $('#btnSave').text('Guardar').attr('disabled', false);
      }
    });
  };

  function borrar(id) {
    bootbox.confirm("¿Seguro desea eliminar este registro?", function(result) {
      if (result) {
        $.ajax({
          url: "<?= $this->url ?>/ajax_delete/" + id,
          type: "POST",
          dataType: "JSON",
          success: function(data) {
            reload_table();
            Lobibox.notify('success', { size: 'mini', position: 'top right', msg: 'Registro eliminado exitosamente.' });
          },
          error: function() {
            Lobibox.notify('error', { size: 'mini', position: 'top right', msg: 'Error al eliminar registro' });
          }
        });
      }
    });
  };

  function reload_table() { table.ajax.reload(null, false); };
</script>
