/** ========================================================================
 * For Administrator / Admin panel
 * Developed by LWEGATECH
 * ========================================================================**/

// Automatically add CSRF token to every AJAX request
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="X-CSRF-TOKEN"]').attr('content')
    }
});


/**==================================================
 * SIEBAR MENU
 ===================================================*/
 $(document).ready(function() {
	$('.menu li:has(ul)').click(function(e) {
		e.preventDefault();

		if($(this).hasClass('activado')) {
			$(this).removeClass('activado');
			$(this).children('ul').slideUp();
		} else {
			$('.menu li ul').slideUp();
			$('.menu li').removeClass('activado');
			$(this).addClass('activado');
			$(this).children('ul').slideDown();
		}

		$('.menu li ul li a').click(function() {
			window.location.href = $(this).attr('href');
		})
	});
});

/** =======================================================
 * SIDEBAR OPEN/CLOSE
 ==========================================================*/
 function toggleSidebar() {
  // Toggle the open/close class on sidebar and main
  document.getElementById("sidebar").classList.toggle("open");
  document.getElementById("main").classList.toggle("open");
  
  // Toggle the visibility of the open and close buttons
  document.getElementById("toggleBtn-open").classList.toggle("hidden");
  document.getElementById("toggleBtn-close").classList.toggle("hidden");
}


/**=======================================
 * LOAD ITEMS BACK
 ==========================================*/
 $(document).ready(function(){
	$('a[data-bs-toggle="tab"]').on('show.bs.tab', function(e) {
		localStorage.setItem('activeTab', $(e.target).attr('href'));
	});
	var activeTab = localStorage.getItem('activeTab');
	if(activeTab){
		$('#myTab a[href="' + activeTab + '"]').tab('show');
	}
});

/**=======================================
 * Change Date DB to Bootstrap format
 ==========================================*/
function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1; //Month from 0 to 11
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

//Date with abbreviated month name
function dateToNFT(date) {
  var d = date.getDate();
  var m = date.toLocaleString('default', { month: 'short' }); 
  var y = date.getFullYear();
  return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}

//Used to convert Date into Bootstrap Form
function dateToYMDinBootstrap(date) {
  var d = date.getDate();
  var m = date.getMonth() + 1; //Month from 0 to 11
  var y = date.getFullYear();
  return y + '-' + (m <= 9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

/** =================================================
 * POPOVERS
 ===================================================*/
 var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl)
})

/** ====================================================
 * CHECK PASSWORD
 *======================================================*/
const togglePassword = document.querySelector("#togglePassword");
    const password = document.querySelector("#password");
                        
    togglePassword.addEventListener("click", function () {
    // toggle the type attribute
    const type = password.getAttribute("type") === "password" ? "text" : "password";
    password.setAttribute("type", type);
                            
    // toggle the icon
    this.classList.toggle("ri-eye-line");
});

/** ====================================================
 * GENERATOR PASSWORD
 *======================================================*/
function onPwd() {
    const length = 15; 
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
    let password = "";
    for (let i = 0; i < length; i++) {
      password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    document.getElementById("passwordgen").value = password;
  }


  /**
   * TINY MCE
   */
  $(document).ready(function(){
  var quill = new Quill('#editor', {
    theme: 'snow'  // Use the Snow theme (default)
  });

  tinymce.init({
    selector: 'textarea#description', // Replace #description with your textarea ID or class
    // Optional configuration options:
    plugins: 'advlist autolink lists link image charmap print preview anchor',
    toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
    readonly: false // Make sure this is false or remove it altogether
});
  });

/**
 * 
 * @param {*} permissionName 
 * @param {*} callback 
 */
function checkPermissionBeforeAction(permissionName, callback) {
    // You can preload permissions in your template
    if (window.userPermissions && window.userPermissions.includes(permissionName)) {
        callback();
    } else {
        toastr.error('You do not have permission for this action');
    }
}

// Usage:
// onclick="checkPermissionBeforeAction('module_sections.create', add_module_section)"
/** ===================================
 * TinyMCE
 */
// Prevent Bootstrap dialog from blocking focusin
document.addEventListener('focusin', (e) => {
  if (e.target.closest(".tox-tinymce, .tox-tinymce-aux, .moxman-window, .tam-assetmanager-root") !== null) {
    e.stopImmediatePropagation();
  }
});