<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-sitemap 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 Menú</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>Menú</th>
              <th>URL</th>
              <th>Icono</th>
              <th>Grupo</th>
              <th>Posición</th>
              <th>Estado</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>Grupo <span class="text-danger">*</span></label>
              <select id="grupo" name="grupo" class="form-control">
                <option value="">SELECCIONAR</option>
                <?php foreach ($menus as $value) { ?>
                  <option value="<?= $value->id ?>"><?= $value->nombre ?></option>
                <?php } ?>
              </select>
              <span class="help-block text-danger"></span>
            </div>
            <div class="form-group">
              <label>Menú <span class="text-danger">*</span></label>
              <input id="nombre" name="nombre" class="form-control" type="text">
              <span class="help-block text-danger"></span>
            </div>
            <div class="form-group">
              <label>URL <span class="text-danger">*</span></label>
              <input id="url" name="url" class="form-control" type="text">
              <span class="help-block text-danger"></span>
            </div>
            <div class="form-group">
              <label>Icono</label>
              <select class="form-control" id="icono" name="icono">
                <option value="">SELECCIONAR</option>
                <?php foreach ($iconos as $value) { ?>
                  <option value="<?= $value->nombre ?>"><?= $value->nombre ?></option>
                <?php } ?>
              </select>
              <span class="help-block text-danger"></span>
            </div>
            <div class="row">
              <div class="col-md-6">
                <div class="form-group">
                  <label>Posición</label>
                  <input id="posicion" name="posicion" class="form-control" type="number" value="0">
                  <span class="help-block text-danger"></span>
                </div>
              </div>
              <div class="col-md-6">
                <div class="form-group">
                  <label>Estado</label>
                  <select id="estado" name="estado" class="form-control">
                    <option value="0">ACTIVO</option>
                    <option value="1">INACTIVO</option>
                  </select>
                  <span class="help-block text-danger"></span>
                </div>
              </div>
            </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"
    },
    "order": [[ 5, "asc" ]],
    "columnDefs": [
      {
        "targets": [-1],
        "orderable": false,
      },
    ],
  });

  $("input, textarea, select").change(function() {
    $(this).removeClass('is-invalid');
    $(this).nextAll('.help-block').empty();
  });
  
  $("#nombre").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 <?= $this->titulo_controlador ?>');
};

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="grupo"]').val(data.parent_id);
      $('[name="nombre"]').val(data.nombre);
      $('[name="url"]').val(data.url);
      $('[name="icono"]').val(data.icono);
      $('[name="posicion"]').val(data.posicion);
      $('[name="estado"]').val(data.estado);
      $('#modal_form').modal('show');
      $('.modal-title').text('Modificar <?= $this->titulo_controlador ?>');
    },
    error: function() { 
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Error al obtener datos',
        timer: 2000,
        showConfirmButton: false,
        toast: true,
        position: 'bottom-end'
      });
    }
  });
};

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

function estado(id, estado) {
  $.ajax({
    url: "<?= $this->url ?>/ajax_estado/" + id + "/" + estado,
    type: "POST",
    dataType: "JSON",
    success: function(data) {
      if (data.status) {
        reload_table();
        Swal.fire({
          icon: 'success',
          title: 'Estado actualizado',
          timer: 2000,
          showConfirmButton: false,
          toast: true,
          position: 'bottom-end'
        });
      }
    },
    error: function() {
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Error al cambiar estado',
        timer: 2000,
        showConfirmButton: false,
        toast: true,
        position: 'bottom-end'
      });
    }
  });
};

function borrar(id) {
  Swal.fire({
    title: '¿Estás seguro?',
    text: "No podrás revertir esta acción",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Sí, eliminar',
    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: 'Eliminado',
            text: 'El registro ha sido 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: 2000,
            showConfirmButton: false,
            toast: true,
            position: 'bottom-end'
          });
        }
      });
    }
  });
};
</script>