//Selecting Tags into Posts, Forums and Adding new tags.
  $(document).ready(function () {
    // Initialize tags input with autocomplete and allow the creation of new tags
    var selectizeInput = $("#tags-input").selectize({
      plugins: ['remove_button'],
      delimiter: ',',
      openOnFocus: true,
      closeAfterSelect: true,
      loadingClass: 'loading',
      create: function (input) {
        return {
          value: input,
          text: input
        };
      },
      load: function (query, callback) {
        if (!query.length) return callback();
        $.ajax({
          url: base_url + 'administrator/tags/list',
          type: 'GET',
          dataType: 'json',
          data: {
            search: query
          },
          error: function () {
            callback();
          },
          success: function (res) {
            var tags = res.tags.map(function (tag) {
              return {
                value: tag.id,
                text: tag.name
              };
            });
            callback(tags);
          }
        });
      }
    });

  });


  //Adding a new Tag & Using it.
  function addPostTag()
  {
    //var form = $('#network-form')[0].reset();
    $('#add_TagModal').modal('show');

  }

  function reloadTagSection() {
    // Make an AJAX request to fetch the updated tags
    $.ajax({
        url: base_url + 'administrator/tags/list',
        type: 'GET', // Use GET or POST based on your server-side implementation
        dataType: 'json', // Expect JSON data
        success: function (data) {
            // Clear the existing options in the Selectize input
            var selectizeInput = $('#tags-input')[0].selectize;
            selectizeInput.clear();

            // Add the updated tags as options
            data.tags.forEach(function (tag) {
                selectizeInput.addOption({ value: tag.id, text: tag.name });
            });

            // Set the new tags as selected values (if needed)
            selectizeInput.setValue(data.selectedTagIds);

            // Trigger an event to reflect the changes (if needed)
            selectizeInput.trigger('change');
        },
        error: function (xhr, status, error) {
            console.error(xhr, status, error);
        }
    });
  }


  function saveNewTag() {

    var form = $('#tag-form')[0];
    var formData = new FormData(form);

    // Retrieve the CSRF token from the page's HTML
    var csrfToken = $('[name="csrf_token"]').val();

    // Append the CSRF token to the FormData object
    formData.append('csrf_token', csrfToken);
    $.ajax({
      url: base_url + 'administrator/tags/add',
      type: 'POST',
      dataType: 'json',
      data: formData,
      processData: false,
      contentType: false,
      headers: {'X-Requested-With': 'XMLHttpRequest'},
      success: function(data)
      {
        //console.log(data);
        if(data.success == true)
        {
            
            $('#add_TagModal').modal('hide');
            $('#add_TagModal').find('form')[0].reset();

              toastr.success(data.msg);

              //window.location.href= base_url +"administrator/posts/add";
              reloadTagSection();

              //$('#add_TagModal').reset;     
            }else{
              $('#add_TagModal').modal('hide');
              $('#add_TagModal').find('form')[0].reset();

              toastr.error(data.msg);
              reloadTagSection();
              //window.location.href= base_url +"administrator/posts/add";
            }
      },
      error: function (xhr, status, error) {
        // Handle the error response here
        console.error(xhr, status, error);
      }
    });
}
