<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-tags text-warning 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-warning btn-sm" data-toggle="tooltip" title="Nuevo"><i class="fas fa-plus"></i> Nuevo Concepto</a>
        </div>
      </div>
      <!-- /.card-header -->
      <div class="card-body table-responsive">
        <table id="tabla" class="table table-hover table-bordered table-striped">
          <thead>
            <tr>
              <th>#</th>
              <th>Código</th>
              <th>Concepto</th>
              <th>Tipo</th>
              <th width="120">Acciones</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
      <!-- /.card-body -->
    </div>
  </div>
</div>

<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header bg-warning 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">
        <form action="" id="form" autocomplete="off">
          <input type="hidden" id="id" name="id">
          <div class="form-body">
            <div class="form-group">
              <label>Código <span class="text-danger">*</span></label>
              <input id="codigo" name="codigo" class="form-control" type="text">
              <span class="help-block text-danger"></span>
            </div>
            <div class="form-group">
              <label>Concepto <span class="text-danger">*</span></label>
              <input id="concepto" name="concepto" class="form-control" type="text">
              <span class="help-block text-danger"></span>
            </div>
            <div class="form-group">
              <label>Tipo <span class="text-danger">*</span></label>
              <select id="tipo" name="tipo" class="form-control">
                <option value="INGRESO">INGRESO</option>
                <option value="EGRESO">EGRESO</option>
              </select>
              <span class="help-block text-danger"></span>
            </div>
          </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 save_method;
var table;
$(document).ready(function() {
  table = $('#tabla').DataTable({
    language: dtlanguage,
    "ajax": {
      "url": "<?= $this->url ?>/ajax_list",
      "type": "POST"
    },
    "columnDefs": [
      {
        "targets": [-1],
        "orderable": false,
      },
    ],
  });

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

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

function save() {
  $('#btnSave').text('guardando...');
  $('#btnSave').attr('disabled', true);
  var url = save_method == 'add' ? "<?= $this->url ?>/ajax_add" : "<?= $this->url ?>/ajax_update";
  var msgsuccess = save_method == 'add' ? "El registro fue creado exitosamente." : "El registro fue actualizado exitosamente.";

  $.ajax({
    url: url,
    type: "POST",
    data: $('#form').serialize(),
    dataType: "JSON",
    success: function(data) {
      if (data.status) {
        $('#modal_form').modal('hide');
        reload_table();
        Swal.fire({ icon: 'success', title: '¡Éxito!', text: msgsuccess, timer: 2000, showConfirmButton: false, toast: true, position: 'bottom-end' });
      } 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() {
      Swal.fire({ icon: 'error', title: 'Error', text: 'Error al procesar la solicitud', timer: 3000, showConfirmButton: false, toast: true, position: 'bottom-end' });
      $('#btnSave').text('Guardar').attr('disabled', false);
    }
  });
};

function edit(id) {
  save_method = 'update';
  $('#form')[0].reset();
  $('.form-control').removeClass('is-invalid');
  $('.help-block').empty();
  $.ajax({
    url: "<?= $this->url ?>/ajax_edit/" + id,
    type: "GET",
    dataType: "JSON",
    success: function(data) {
      $('[name="id"]').val(data.id);
      $('[name="codigo"]').val(data.codigo);
      $('[name="concepto"]').val(data.concepto);
      $('[name="tipo"]').val(data.tipo);
      $('#modal_form').modal('show');
      $('.modal-title').text('Modificar Concepto');
    },
    error: function() { 
      Swal.fire({ icon: 'error', title: 'Error', text: 'Error al obtener datos', timer: 3000, showConfirmButton: false, toast: true, position: 'bottom-end' });
    }
  });
};

function reload_table() { table.ajax.reload(null, false); };

function borrar(id) {
  Swal.fire({ title: '¿Estás seguro?', text: "Seguro desea Eliminar este registro?", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Sí, confirmar', cancelButtonText: 'Cancelar' }).then((result) => { if (result.isConfirmed) {
      $.ajax({
        url: "<?= $this->url ?>/ajax_delete/" + id,
        type: "POST",
        dataType: "JSON",
        success: function() {
          reload_table();
          Swal.fire({ icon: 'success', title: '¡Éxito!', text: 'Registro eliminado', timer: 2000, showConfirmButton: false, toast: true, position: 'bottom-end' });
        },
        error: function() {
          Swal.fire({ icon: 'error', title: 'Error', text: 'No se pudo eliminar el registro', timer: 3000, showConfirmButton: false, toast: true, position: 'bottom-end' });
        }
      });
    }
  });
};
</script>