<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-id-badge 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 Perfil</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>Perfil</th>
              <th>Descripcion</th>
              <th width="120">Acciones</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
      <!-- /.card-body -->
    </div>
  </div>
</div>

<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>Perfil <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>Descripcion</label>
              <textarea id="descripcion" name="descripcion" class="form-control" rows="3"></textarea>
              <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>

<!-- Bootstrap modal -->
<div class="modal fade" id="menu_form" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header bg-info 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 id="menu" autocomplete="off">
          <div id="listarmenu"></div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" id="btnSavemenu" onclick="savemenu()" 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();
  });
});

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="nombre"]').val(data.nombre);
      $('[name="descripcion"]').val(data.descripcion);
      $('#modal_form').modal('show');
      $('.modal-title').text('Modificar <?= $this->titulo_controlador ?>');
    },
    error: function() { alert('Error al obtener datos'); }
  });
};

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' });
        }
      });
    }
  });
};

function menu(id) {
  $.ajax({
    url: "<?= $this->url ?>/listarmenu/" + id,
    type: "POST",
    success: function(data) {
      $('#listarmenu').html(data);
      $('#menu_form').modal('show');
      $('.modal-title').text('Configurar Permisos de Menú');
      $("ul.checktree").checktree();
    },
    error: function() { alert("Error al cargar menú"); }
  });
};

function savemenu() {
  $('#btnSavemenu').text('guardando...').attr('disabled', true);
  $.ajax({
    url: "<?= $this->url ?>/ajax_add_menu",
    type: "POST",
    data: $('#menu').serialize(),
    dataType: "JSON",
    success: function(data) {
      if (data.status) {
        $('#menu_form').modal('hide');
        reload_table();
        Swal.fire({ icon: 'success', title: '¡Éxito!', text: "Permisos actualizados", timer: 2000, showConfirmButton: false, toast: true, position: 'bottom-end' });
      }
      $('#btnSavemenu').text('Guardar').attr('disabled', false);
    },
    error: function() {
      Swal.fire({ icon: 'error', title: 'Error', text: "Error al guardar permisos", timer: 3000, showConfirmButton: false, toast: true, position: 'bottom-end' });
      $('#btnSavemenu').text('Guardar').attr('disabled', false);
    }
  });
};
</script>
