<div class="row">

  <div class="col-lg-12">

    <div class="card">

      <div class="card-header">

        <div class="card-widgets">

          <button type="button" class="btn btn-danger btn-sm" onclick="location.reload()"><i class="fa fa-redo"></i> Recargar</button>

          <button type="button" class="btn btn-primary btn-sm" onclick="add()"><i class="fa fa-plus"></i> Nuevo</button>

        </div>

        <h3 class="card-title text-dark">Lista de <?= $this->titulo_controlador ?></h3>

      </div>

      <!-- /.box-header -->

      <div class="card-body table-responsive">

        <table id="tabla" class="table table-striped table-bordered dt-responsive nowrap" style="border-collapse: collapse; border-spacing: 0; width: 100%;">

          <thead>

            <tr class="bg-primary text-white">

              <th>#</th>

              <th>Menu</th>

              <th>URL</th>

              <th>Icon</th>

              <th>Grupo</th>

              <th>Posicion</th>

              <th>Acciones</th>

            </tr>

          </thead>

          <tbody></tbody>

        </table>

      </div>

    </div>

  </div>

</div>



<!-- Bootstrap modal -->

<div id="modal_form" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">

  <div class="modal-dialog modal-lg">

    <div class="modal-content">

      <div class="modal-header">

        <h5 class="modal-title"></h5>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">

          <span aria-hidden="true">&times;</span>

        </button>

      </div>

      <div class="modal-body">

        <form action="" id="form" class="form-horizontal" autocomplete="off">

          <input type="hidden" class="form-control" id="id" name="id">

          <div class="row">

            <div class="col-md-6">

              <div class="form-group">

                <label class="control-label">Grupo<span class="required">*</span></label>

                <select id="grupo" name="grupo" class="form-control"></select>

                <span class="help-block"></span>

              </div>

            </div>

            <div class="col-md-6">

              <div class="form-group">

                <label class="control-label">Menu<span class="required">*</span></label>

                <input class="form-control" id="menu" type="text" name="menu">

                <span class="help-block"></span>

              </div>

            </div>

          </div>

          <div class="row">

            <div class="col-md-6">

              <div class="form-group">

                <label class="control-label">URL</label>

                <input class="form-control" id="url" type="text" name="url">

                <span class="help-block"></span>

              </div>

            </div>

            <div class="col-md-6">

              <div class="form-group">

                <label class="control-label">Icon<span class="required">*</span></label>

                <select id="icon" name="icon" class="form-control"></select>

                <span class="help-block"></span>

              </div>

            </div>

          </div>



          <div class="row">

            <div class="col-md-6">              

            </div>

            <div class="col-md-6">

              <div class="form-group">

                <label class="control-label">Posicion<span class="required">*</span></label>

                <input class="form-control" id="posicion" type="number" name="posicion" value="0">

                <span class="help-block"></span>

              </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><!-- /.modal -->



<script type="text/javascript">

  //for save method string

  var save_method;

  var table;

  $(document).ready(function() {

    cargargrupos();

    cargariconos();

    table = $('#tabla').DataTable({

      language: {

        "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"

        }

      },

      dom: 'Bfrtip',

      buttons: [

        'copyHtml5',

        'excelHtml5',

        'csvHtml5',

        'pdfHtml5'

      ],

      // Load data for the table's content from an Ajax source

      "ajax": {

        "url": "<?= $this->url ?>/ajax_list",

        "type": "POST"

      },

    });

    //set input/textarea/select event when change value, remove class error and remove text help block

    $("input").change(function() {

      $(this).parent().parent().removeClass('has-error');

      $(this).next().empty();

    });

    $("textarea").change(function() {

      $(this).parent().parent().removeClass('has-error');

      $(this).next().empty();

    });

    $("select").change(function() {

      $(this).parent().parent().removeClass('has-error');

      $(this).next().empty();

    });

  });



  function cargargrupos() {

    $.ajax({

      url: "<?= $this->url ?>/cargargrupos",

      method: "POST",

      dataType: "json",

      success: function(data) {

        $("#grupo option").remove();

        var options = '<option value="">SELECCIONAR GRUPO</option>';

        $.each(data.grupos, function(index, value) {

          options += "<option value='" + value.id + "'>" + value.nombre + "</option>"

        });

        $("#grupo").append(options);

      },

      error: function(jqXHR, textStatus, errorThrown) {

        console.log(jqXHR);

      }

    });

  };



  function cargariconos() {

    $.ajax({

      url: "<?= $this->url ?>/cargariconos",

      method: "POST",

      dataType: "json",

      success: function(data) {

        $("#icon option").remove();

        var options = '<option value="">SELECCIONAR ICONO</option>';

        $.each(data.iconos, function(index, value) {

          options += "<option value='" + value.nombre + "'>" + value.imagen + ' ' + value.nombre + "</option>"

        });

        $("#icon").append(options);

      },

      error: function(jqXHR, textStatus, errorThrown) {

        console.log(jqXHR);

      }

    });

  };



  function add() {

    save_method = 'add';

    $('#form')[0].reset(); // reset form on modals

    $('.form-group').removeClass('has-error'); // clear error class

    $('.help-block').empty(); // clear error string

    $('#modal_form').modal('show'); // show bootstrap modal

    $('.modal-title').text('Crear <?= $this->titulo_controlador ?>'); // Set Title to Bootstrap modal title

  };



  function save() {

    $('#btnSave').text('guardando...'); //change button text

    $('#btnSave').attr('disabled', true); //set button disable

    var url;

    if (save_method == 'add') {

      url = "<?= $this->url ?>/ajax_add";

      msgsuccess = "El registro fue creado exitosamente.";

      msgerror = "El registro no se pudo crear verifique las validaciones.";

    } else {

      url = "<?= $this->url ?>/ajax_update";

      msgsuccess = "El registro fue actualizado exitosamente.";

      msgerror = "El registro no se pudo actualizar. Verifique la operación";

    }

    // ajax adding data to database

    $.ajax({

      url: url,

      type: "POST",

      data: $('#form').serialize(),

      dataType: "JSON",

      success: function(data) {

        //if success close modal and reload ajax table

        if (data.status) {

          $('#modal_form').modal('hide');

          reload_table();

          Lobibox.notify('success', {

            size: 'mini',

            msg: msgsuccess

          });

        } else {

          for (var i = 0; i < data.inputerror.length; i++) {

            $('[name="' + data.inputerror[i] + '"]').parent().parent().addClass(

              'has-error'

            ); //select parent twice to select div form-group class and add has-error class

            $('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[

              i]); //select span help-block class set text error string

          }

        }

        $('#btnSave').text('Guardar'); //change button text

        $('#btnSave').attr('disabled', false); //set button enable

      },

      error: function(jqXHR, textStatus, errorThrown) {

        Lobibox.notify('error', {

          size: 'mini',

          msg: msgerror

        });

        $('#btnSave').text('Guardar'); //change button text

        $('#btnSave').attr('disabled', false); //set button enable

      }

    });

  };



  function reload_table() {

    table.ajax.reload(null, false); //reload datatable ajax

  };



  function edit(id) {

    save_method = 'update';

    $('#form')[0].reset(); // reset form on modals

    $('.form-group').removeClass('has-error'); // clear error class

    $('.help-block').empty(); // clear error string

    //Ajax Load data from ajax

    $.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="menu"]').val(data.nombre);

        $('[name="url"]').val(data.url);

        $('[name="icon"]').val(data.icono);

        $('[name="posicion"]').val(data.posicion);

        $('#modal_form').modal('show'); // show bootstrap modal when complete loaded

        $('.modal-title').text(

          'Modificar <?= $this->titulo_controlador ?>'); // Set title to Bootstrap modal title

      },

      error: function(jqXHR, textStatus, errorThrown) {

        alert('Error get data from ajax');

      }

    });

  };



  function borrar(id) {

    bootbox.confirm("Seguro desea Eliminar este registro?", function(result) {

      if (result === true) {

        $.ajax({

          url: "<?= $this->url ?>/ajax_delete/" + id,

          type: "POST",

          dataType: "JSON",

          success: function(data) {

            //if success reload ajax table

            $('#modal_form').modal('hide');

            reload_table();

            Lobibox.notify('success', {

              size: 'mini',

              msg: 'El registro fue eliminado exitosamente.'

            });

          },

          error: function(jqXHR, textStatus, errorThrown) {

            Lobibox.notify('error', {

              size: 'mini',

              msg: 'No se puede eliminar este registro por seguridad de su base de datos, Contacte al Administrador del Sistema'

            });

          }

        });

      }

    });

  };

</script>