/* globals Chart:false, feather:false */

let countdownTime = 90;
let inactivityTimer, countdownTimer;
// inactivityTime may be injected by server-side views (e.g. VariousViewsHtml.php).
// Provide a sensible default (5 minutes) when not defined to avoid ReferenceError.
let inactivityTime = (typeof window.inactivityTime !== 'undefined') ? window.inactivityTime : 5 * 60 * 1000;

function resetTimer(type) {
  if ($("#inactivityModal").is(":visible") && type) return;

  clearTimeout(inactivityTimer);
  clearInterval(countdownTimer);

  if ($("#inactivityModal").is(":visible")) {
    const modalElement = document.getElementById("inactivityModal");
    const modal =
      bootstrap.Modal.getInstance(modalElement) ||
      new bootstrap.Modal(modalElement);
    modal.hide();
  }

  startInactivityTimer();
}

function startInactivityTimer() {
  inactivityTimer = setTimeout(showInactivityModal, inactivityTime);
}

function showInactivityModal() {
  let countdown = countdownTime;
  $("#countdown").text(countdown);

  const modal = new bootstrap.Modal(
    document.getElementById("inactivityModal"),
    {
      backdrop: false,
      keyboard: false,
    }
  );
  modal.show();

  countdownTimer = setInterval(() => {
    countdown--;
    $("#countdown").text(formatCountdownMessage(countdown));

    if (countdown === 0 || countdown < 0) {
      clearInterval(countdownTimer);
      window.location.href = "index.php?page=d";
    }
  }, 1000);
}

function formatCountdownMessage(seconds) {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;

  let minPart = mins > 0 ? `${mins} ${mins === 1 ? "minute" : "minutes"}` : "";
  let secPart =
    secs > 0 ? `${secs} ${secs === 1 ? "seconde" : "secondes"}` : "";

  if (minPart && secPart) {
    return `${minPart} et ${secPart}...`;
  } else if (minPart) {
    return `${minPart}...`;
  } else {
    return `${secPart}...`;
  }
}

// Utility function for form validation
function ResetCheckFieldInForm(selector, typeCheck) {
  let isValid = true;
  const $select = $(selector);

  $select.each(function () {
    const field = $(this);
    const fieldId = field.attr("id");
    const errorDiv = $("#" + fieldId + "Error");
    
    if (typeCheck === "reset") {
      field.removeClass("is-invalid");
      errorDiv.addClass("d-none");
    } else if (typeCheck === "check") {
      if (field.val()) {
        field.removeClass("is-invalid");
        errorDiv.addClass("d-none");
      } else {
        field.addClass("is-invalid");
        errorDiv.removeClass("d-none");
        isValid = false;
      }

      // Additional validation for email
      if (field.attr("type") === "email") {
        const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailPattern.test(field.val())) {
          field.addClass("is-invalid");
          errorDiv.text("Adresse email invalide").removeClass("d-none");
          isValid = false;
        } else {
          field.removeClass("is-invalid");
          errorDiv.text("").addClass("d-none");
        }
      }

      // Additional validation for telephone
      if (field.attr("type") === "tel") {
        const phonePattern = /^\(\d{3}\) \d{3}-\d{4}$/; // Matches (123) 456-7890 format
        if (!phonePattern.test(field.val())) {
          field.addClass("is-invalid");
          errorDiv.text("Numéro de téléphone invalide. Format: (XXX) XXX-XXXX").removeClass("d-none");
          isValid = false;
        } else {
          field.removeClass("is-invalid");
          errorDiv.text("").addClass("d-none");
        }
      }
    }
  });

  return isValid;
}

$(document).ready(function () {
  let params = new URLSearchParams(window.location.search);
  let currentIndex = -1;
  let inactivityTimers = {};

  // Initialize inactivity monitoring
  $(document).on("mousemove keypress click scroll", function () {
    resetTimer(true);
  });

  $(document).on("click", "#stayBtn", function () {
    window.location.href = "index.php?" + params.toString();
  });

  $(document).on("click", "#disconnectBtn", function () {
    window.location.href = "index.php?page=d";
  });

  // Start inactivity timer if modal exists
  if ($("#inactivityModal").length) {
    startInactivityTimer();
  }

  // Hide main content and show loading spinner
  $("#main-content").hide();

  $("body").prepend(`
  <div id="loadingContainer">
    <div id="loadingSpinner">
        <div class="spinner-line" id="line1"></div>
        <div class="spinner-line" id="line2"></div>
        <div class="spinner-line" id="line3"></div>
    </div>
    <p id="loadingText">Chargement...</p>
  </div>
        `);

  $("#loadingContainer").show();
  
  if ($("#gridUtilisateurs").length) {
    let pendingCheckbox = null;
    let pendingIdUser = null;
    let pendingIsChecked = null;

    /*------------------------------------------------------------*/
    /*-------------------- gridUtilisateurs  ---------------------*/
    /*------------------------------------------------------------*/
    let resetBtn;

    var gridUtilisateurs = new DataTable("#gridUtilisateurs", {
      paging: true,
      scrollCollapse: true,
      scrollY: "57vh",
      scrollX: false,
      ordering: true,
      info: true,
      footer: true,
      stateSave: true,
      pageLength: 100,
      columnDefs: [
        {
          targets: [6],
          createdCell: function (td) {
            td.style.textAlign = "center";
            td.style.fontWeight = "bold";
          },
        },
        {
          targets: [7],
          createdCell: function (td) {
            td.style.textAlign = "center";
            td.style.fontWeight = "bold";
          },
        },
        {
          targets: [11],
          orderable: false,
        },
      ],
      columns: [
        { width: "50px" },
        { width: "auto" },
        { width: "auto" },
        { width: "auto" },
        { width: "200px" },
        { width: "200px" },
        { width: "200px" },
        { width: "200px" },
        { width: "200px" },
        { width: "auto" },
        { width: "auto" },
        { width: "95px" },
      ],
      language: {
        info: "Affichage page _PAGE_ / _PAGES_, Total : _TOTAL_ ligne(s).",
        infoEmpty: "Aucun enregistrement trouvé.",
        infoFiltered: "(filtrage de _MAX_ total enregistrements)",
        lengthMenu: "Afficher _MENU_ records par page",
        zeroRecords: "Aucun enregistrement trouvé - désolé",
        search: "<b>Recherche Global : <b>",
        stateRestore: {
          creationModal: {
            length: "Length:",
          },
        },
        buttons: {
          pageLength: {
            _: "Afficher %d éléments",
            "-1": "Tout afficher",
          },
          copyTitle: "Copie réussie",
          copySuccess: {
            1: "1 ligne copiée dans le presse-papiers",
            _: "%d lignes copiées dans le presse-papiers",
          },
          copy: "Copier",
          print: "Imprimer",
        },
      },
      lengthMenu: [
        [10, 25, 50, 100, 500, -1],
        [
          "10 lignes",
          "25 lignes",
          "50 lignes",
          "100 lignes",
          "500 lignes",
          "Afficher tous",
        ],
      ],
      layout: {
        topStart: {
          buttons: [
            {
              extend: "pageLength",
            },
            {
              extend: "copyHtml5",
              filename: "LISTE DES UTILISATEURS",
              text: '<i class="fas fa-copy" style="color: #6f42c1;"></i>&nbsp',
              titleAttr: "Copier dans le presse-papiers",
            },
            {
              extend: "excel",
              filename: "LISTE DES UTILISATEURS",
              text: '<i class="fas fa-file-excel" style="color: #28a745;"></i>&nbsp',
              titleAttr: "Exporter au format Excel",
            },
            {
              extend: "pdf",
              filename: "LISTE DES UTILISATEURS",
              text: '<i class="fas fa-file-pdf" style="color: #dc3545;"></i>&nbsp',
              titleAttr: "Exporter au format PDF",
              exportOptions: {
                columns: ":not(.no-export)",
              },
            },
            {
              extend: "print",
              filename: "LISTE DES UTILISATEURS",
              text: '<i class="fas fa-print" style="color: #fd7e14;"></i>&nbsp',
              titleAttr: "Imprimer la table",
              exportOptions: {
                columns: ":not(.no-export)",
              },
            },
            {
              text: '<i class="fas fa-sync-alt"></i>&nbsp',
              titleAttr: "Réinitialiser et recharger",
              action: function (e, dt, node, config) {
                dt.state.clear();
                dt.search("").columns().search("").draw();
                location.reload();
              },
            },
            {
              text: '<i class="fas fa-plus"></i> Ajouter un utilisateur',
              titleAttr: "Ajouter un nouveau utilisateur",
              attr: {
                id: "btnAddUser",
              },
            },
          ],
        },
      },
      initComplete: function () {
        var api = this.api();
        var excludedColumns = [11];
        var calendarColumns = [7, 8];

        $.datepicker.setDefaults($.datepicker.regional["fr"]);

        api.columns().every(function () {
          this.search("");
        });
        api.search("").draw();

        api.columns().every(function (index) {
          if (excludedColumns.includes(index)) return;

          let column = this;
          let title = column.footer().textContent;

          let wrapper = document.createElement("div");
          wrapper.classList.add("input-group");

          let input = document.createElement("input");
          input.placeholder = title;
          input.value = column.search();
          input.classList.add("form-control");
          input.classList.add("form-control-sm");

          if (calendarColumns.includes(index)) {
            input.classList.add("show-calendar");

            let iconSpan = document.createElement("span");
            iconSpan.className = "input-group-text";
            (iconSpan.innerHTML = '<i class="fas fa-calendar-alt"></i>&nbsp'),
              iconSpan.addEventListener("click", function () {
                $(input).datepicker("show");
              });

            wrapper.appendChild(input);
            wrapper.appendChild(iconSpan);

            $(input).datepicker({
              format: "yy-mm-dd",
              autoclose: true,
              todayHighlight: true,
              clearBtn: true,
              onSelect: function (dateText) {
                if (column.search() !== dateText) {
                  column.search(dateText).draw();
                  updateResetButton();
                }
              },
            });
          } else {
            wrapper.appendChild(input);
          }

          column.footer().replaceChildren(wrapper);

          input.addEventListener("input", function () {
            if (column.search() !== this.value) {
              column.search(this.value).draw();
              updateResetButton();
            }
          });
        });

        let resetFooter = api.column(11).footer();
        resetFooter.innerHTML = "";

        resetBtn = document.createElement("button");
        resetBtn.textContent = "Réinitialiser";
        resetBtn.className = "btn btn-outline-secondary btn-sm d-none";
        resetBtn.addEventListener("click", function () {
          api.columns().every(function () {
            this.search("");
          });

          api.search("").draw();
          $(api.table().footer()).find("input").val("");
          $(".dt-search input[type='search']").val("");
          resetBtn.classList.add("d-none");
        });

        resetFooter.appendChild(resetBtn);

        function updateResetButton() {
          const hasColumnFilter = api
            .columns()
            .indexes()
            .toArray()
            .some(function (index) {
              return api.column(index).search().trim() !== "";
            });

          const hasGlobalSearch = api.search().trim() !== "";

          if (hasColumnFilter || hasGlobalSearch) {
            resetBtn.classList.remove("d-none", "btn-outline-secondary");
            resetBtn.classList.add("btn-danger");
          } else {
            resetBtn.classList.add("d-none");
            resetBtn.classList.remove("btn-danger");
            resetBtn.classList.add("btn-outline-secondary");
          }
        }

        updateResetButton();

        $('.dt-search input[type="search"]').on("input", function () {
          updateResetButton();
        });
      },
    });

    gridUtilisateurs.column("1:visible").order("asc").draw();

    var dtscroll = document.querySelector(".dt-scroll");
    var scrollHead = document.querySelector(".dt-scroll-head");
    var scrollBody = document.querySelector(".dt-scroll-body");
    var scrollFoot = document.querySelector(".dt-scroll-foot");

    dtscroll.insertBefore(scrollFoot, scrollHead.nextSibling);

    if (scrollFoot) {
      var thElements = scrollFoot.querySelectorAll("tfoot tr th");
      thElements.forEach((th) => {
        th.style.borderBottom = "2px solid rgba(0, 0, 0, 0.3)";
      });
    }

    $(".dt-layout-row").last().find(".dt-buttons").remove();

    $("#gridUtilisateurs").css("font-size", "14px");
    $("#gridUtilisateurs td, #gridUtilisateurs head, #gridUtilisateurs th").css(
      {
        "padding-top": "2px",
        "padding-bottom": "2px",
      }
    );

    $(document).on("click", ".user-edit-link", function (e) {
      e.preventDefault();

      const idUser = $(this).data("id");
      const confirmSubmit = $("#confirmSubmit");
      const modalFormAddEditUserLabel = $("#modalFormAddEditUserLabel");
      const alertMessageUserModal = $("#alertMessageUserModal");
      const confirmBody = $("#confirmBody");
      const idUserToEdit = $("#idUserToEdit");
      const divRoles = $("#divRoles");
      const divDepartements = $("#divDepartements");

      alertMessageUserModal.hide();
      $("#username").prop("disabled", true);
      divRoles.empty();
      divDepartements.empty();

      idUserToEdit.val(idUser);
      $('input[name="typeSend"]').val("edit");
      modalFormAddEditUserLabel.text("Modifier utilisateur Num : " + idUser);
      confirmSubmit.removeClass("btn-success");
      confirmSubmit.addClass("btn-danger");

      $.ajax({
        url: "api/functions",
        type: "POST",
        data: { idUser: idUser, action: "getUserDetails" },
        dataType: "json",
        success: function (response) {
          if (response.success) {
            const data = response.data[0];
            const userRoles = response.dataroleuser.map((role) => role.id_role);
            const userDep = response.datadepuser.map(
              (dep) => dep.id_departement
            );

            $("#modalFormAddEditUser #idUser").val(data.id_visite);
            $("#modalFormAddEditUser #username").val(data.username);
            $("#modalFormAddEditUser #lastname").val(data.lastname);
            $("#modalFormAddEditUser #firstname").val(data.firstname);
            $("#modalFormAddEditUser #email").val(data.email);
            $("#modalFormAddEditUser #comment").val(data.comment);
            $("#modalFormAddEditUser #num_licence").val(data.num_licence);
            $("#modalFormAddEditUser #finContrat").val(data.valide_au);

            if (response.datadep.length > 0) {
              response.datadep.forEach((dep) => {
                const isChecked = userDep.includes(dep.id_departement)
                  ? "checked"
                  : "";
                divDepartements.append(`
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="userDepartements[]" id="departement_${dep.id_departement}" value="${dep.id_departement}" ${isChecked}/>
                        <label class="form-check-label" for="departement_${dep.id_departement}">${dep.nom_departement}</label>
                    </div>
                `);
              });
            }

            if (response.datarole.length > 0) {
              response.datarole.forEach((role2) => {
                const isChecked = userRoles.includes(role2.id_role)
                  ? "checked"
                  : "";

                divRoles.append(`
                              <div class="form-check">
                                  <input type="checkbox" class="form-check-input" name="userRoles[]" id="role_${role2.id_role}" value="${role2.id_role}" ${isChecked}/>
                                  <label class="form-check-label" for="role_${role2.id_role}">${role2.role_name}</label>
                              </div>
                          `);
              });
            }

            $("#modalFormAddEditUser").modal("show");
          } else {
            console.error("Error:", response.message);
          }
        },
        error: function (xhr, status, error) {
          window.location.href = "index.php?page=user&msg=errorajax";
          console.error("AJAX Error:", error);
        },
      });
    });

    $(document).on("click", ".user-delete-link", function (e) {
      e.preventDefault();

      const idUser = $(this).data("id");
      const confirmDeletionBodyUser = $("#confirmDeletionBodyUser");
      const confirmDeletionModalLabelUser = $("#confirmDeletionModalLabelUser");
      const confirmDeletionSubmitUser = $("#confirmDeletionSubmitUser");
      const alertMessageModalDeleteUser = $("#alertMessageModalDeleteUser");

      alertMessageModalDeleteUser.hide();
      $('input[name="typeConfirmDeletionUser"]').val("delete");
      confirmDeletionModalLabelUser.html("Confirmer la suppression");
      confirmDeletionBodyUser.html(
        "Vouslez-vous vraiment supprimer cet l'utilisateur Numéro : <b>" +
          idUser +
          "</b> ?"
      );
      confirmDeletionSubmitUser.text("Oui, supprimer");
      $("#confirmDeletionSubmitUser").prop("disabled", false);
      $('input[name="idUserToDelete"]').val(idUser);

      $("#confirmDeletionModalUser").modal("show");
    });

    $(document).on("change", ".user-edit-locked-link", function (e) {
      e.preventDefault();

      pendingCheckbox = $(this);
      pendingIdUser = $(this).data("id");
      pendingIsChecked = $(this).is(":checked") ? "yes" : "no";

      let modalMessage =
        pendingIsChecked === "yes"
          ? "Voulez-vous vraiment verrouiller ce compte ?"
          : "Voulez-vous vraiment déverrouiller ce compte ?";

      $("#confirmModalVerifie .modal-body").text(modalMessage);
      $("#confirmModalVerifie").modal("show");
    });

    $("#confirmChange").on("click", function () {
      if (pendingCheckbox) {
        $.ajax({
          url: "api/functions",
          type: "POST",
          data: {
            action: "refreshStatutVerrouillage",
            answer: pendingIsChecked,
            idUser: pendingIdUser,
          },
          dataType: "json",
          success: function (response) {
            if (response.success !== true) {
              window.location.href = "index.php?page=user&msg=errorajax";
            }
            pendingIsChecked = null;
            pendingCheckbox = null;
            $("#confirmModalVerifie").modal("hide");
          },
          error: function (xhr, status, error) {
            window.location.href = "index.php?page=user&msg=errorajax";
          },
        });
      }
    });

    $("#formAddEditUser").on("submit", function (e) {
      let isValid = true;

      e.preventDefault();

  $("#alertMessageUserModal").empty();

      $("#formAddEditUser [required]").each(function () {
        const field = $(this);
        const errorDiv = $("#" + field.attr("id") + "Error");

        if (!field.val()) {
          field.addClass("is-invalid");
          errorDiv.removeClass("d-none");
          isValid = false;
        } else {
          field.removeClass("is-invalid");
          errorDiv.addClass("d-none");
        }

        // Additional validation for telephone
        if (field.attr("type") === "tel") {
          const phonePattern = /^\(\d{3}\) \d{3}-\d{4}$/; // Matches (123) 456-7890 format
          if (!phonePattern.test(field.val())) {
            field.addClass("is-invalid");
            errorDiv
              .text("Invalid phone number. Use (XXX) XXX-XXXX format")
              .removeClass("d-none");
            isValid = false;
          } else {
            field.removeClass("is-invalid");
            errorDiv.text("").addClass("d-none");
          }
        }
      });

      const emailField = $('#formAddEditUser input[type="email"]');
      if (emailField.val()) {
        const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        const emailErrorDiv = $("#" + emailField.attr("id") + "Error");
        if (!emailPattern.test(emailField.val())) {
          emailField.addClass("is-invalid");
          emailErrorDiv
            .text("L'Adresse E-mail est invalide.")
            .removeClass("d-none");
          isValid = false;
        } else {
          emailField.removeClass("is-invalid");
          emailErrorDiv.text("").addClass("d-none");
        }
      }

      if ($("#divDepartements input[type='checkbox']:checked").length === 0) {
        $("#divDepartements").addClass("is-invalid");
        $("#divDepartements").removeClass("d-none");
        $("#alertMessageUserModal")
          .removeClass("alert-info alert-success")
          .addClass("alert-danger")
          .append(
            "Vous devez cocher au moins un département pour cet utilisateur."
          )
          .fadeIn();
        isValid = false;
      } else {
        $("#divDepartements").removeClass("is-invalid");
        $("#divDepartements").addClass("d-none");
      }

      if ($("#divRoles input[type='checkbox']:checked").length === 0) {
        $("#divRoles").addClass("is-invalid");
        $("#divRoles").removeClass("d-none");
        $("#alertMessageUserModal")
          .removeClass("alert-info alert-success")
          .addClass("alert-danger")
          .append("Vous devez cocher au moins un rôle pour cet utilisateur.")
          .fadeIn();
        isValid = false;
      } else {
        $("#divRoles").removeClass("is-invalid");
        $("#divRoles").addClass("d-none");
      }

      if (!isValid) {
        $("#alertMessageUserModal")
          .removeClass("alert-info alert-success")
          .addClass("alert-danger")
          .fadeIn();
        e.preventDefault();
      } else {
        let idUser = $("#idUserToEdit").val();
        let action = "";
        let action2 = "";
        let typeSend = $('input[name="typeSend"]').val();

        if (typeSend === "edit") {
          action = "addEditUser";
          action2 = "&id_user=" + idUser + "&msg=updated";
        } else if (typeSend === "add") {
          action = "addEditUser";
          action2 = "&msg=added";
        }

        $("#username").prop("disabled", false);
        const formData = $("#formAddEditUser").serialize();
        const fullData = formData + "&action=" + action;

        $.ajax({
          url: "api/functions",
          type: "POST",
          data: fullData,
          dataType: "json",
          success: function (response) {
            if (typeSend === "edit") {
              $("#username").prop("disabled", true);
            }

            if (response.message === "userexist") {
              $("#alertMessageUserModal")
                .removeClass("alert-info alert-success")
                .addClass("alert-danger")
                .append(
                  "L'utilisateur ( " + $("#username").val() + " ) existe déjà."
                )
                .fadeIn();
            } else if (response.success) {
              window.location.href = "index.php?page=user" + action2;
            }
          },
          error: function (xhr, status, error) {
            window.location.href = "index.php?page=user&msg=errorajax";
            console.error("AJAX Error:", error);
          },
        });
        $("#confirmModal").modal("hide");
      }
    });

    // Apply input masks for phone numbers
    $('#formAddEditUser input[type="tel"]').on("input", function () {
      let value = $(this).val();
      value = value.replace(/\D/g, ""); // Remove non-numeric characters

      if (value.length > 6) {
        value = value.replace(/(\d{3})(\d{3})(\d+)/, "($1) $2-$3");
      } else if (value.length > 3) {
        value = value.replace(/(\d{3})(\d+)/, "($1) $2");
      } else {
        value = value.replace(/(\d+)/, "($1");
      }

      $(this).val(value);
    });

    $("#confirmSubmitUser").click(function () {
      $("#formAddEditUser").submit();
    });

    $("#btnAddUser").click(function () {
      const idUser = $(this).data("id");
      const confirmSubmit = $("#confirmSubmit");
      const modalFormAddEditUserLabel = $("#modalFormAddEditUserLabel");
      const alertMessageUserModal = $("#alertMessageUserModal");
      const confirmBody = $("#confirmBody");
      const idUserToEdit = $("#idUserToEdit");
      const divRoles = $("#divRoles");
      const divDepartements = $("#divDepartements");

      alertMessageUserModal.hide();
      $("#username").prop("disabled", false);
      divRoles.empty();
      divDepartements.empty();

      idUserToEdit.val(idUser);
      $('input[name="typeSend"]').val("add");
      modalFormAddEditUserLabel.text("Ajouter un utilisateur");
      confirmSubmit.removeClass("btn-success");
      confirmSubmit.addClass("btn-danger");

      $("#modalFormAddEditUser #idUser").val("");
      $("#modalFormAddEditUser #username").val("");
      $("#modalFormAddEditUser #lastname").val("");
      $("#modalFormAddEditUser #firstname").val("");
      $("#modalFormAddEditUser #email").val("");
      $("#modalFormAddEditUser #comment").val("");
      $("#modalFormAddEditUser #num_licence").val("");
      $("#modalFormAddEditUser #finContrat").val("");

      $.ajax({
        url: "api/functions",
        type: "GET",
        data: { q: "", type: "champDepartementAndRole" },
        dataType: "json",
        success: function (response) {
          if (response.datadep.length > 0) {
            response.datadep.forEach((dep) => {
              const isChecked =
                response.datadep.id_departement == dep.id_departement
                  ? "checked"
                  : "";
              divDepartements.append(`
                  <div class="form-check">
                      <input type="checkbox" class="form-check-input" name="userDepartements[]" id="departement_${dep.id_departement}" value="${dep.id_departement}" ${isChecked}/>
                      <label class="form-check-label" for="departement_${dep.id_departement}">${dep.nom_departement}</label>
                  </div>
              `);
            });
          }

          if (response.datarole.length > 0) {
            response.datarole.forEach((role2) => {
              divRoles.append(`
              <div class="form-check">
                  <input type="checkbox" class="form-check-input" name="userRoles[]" id="role_${role2.id_role}" value="${role2.id_role}"/>
                  <label class="form-check-label" for="role_${role2.id_role}">${role2.role_name}</label>
              </div>`);
            });
          }
        },
        error: function (xhr, status, error) {
          //window.location.href = "index.php?page=user&msg=errorajax";
          console.error("AJAX Error:", error);
        },
      });

      $("#modalFormAddEditUser").modal("show");
    });

    $("#modalFormAddEditUser").on("show.bs.modal", function (e) {
      $(this).modal({ backdrop: "static", keyboard: false });
    });

    setTimeout(function () {
      $("#alertMessageUser").hide();
    }, 10000);

    $("#confirmDeletionUser").click(function () {
      const idUser = $('input[name="idUserToDelete"]').val();

      action = "deleteUser";
      $.ajax({
        url: "api/functions",
        type: "POST",
        data: { idUserToDelete: idUser, action: "deleteUser" },
        dataType: "json",
        success: function (response) {
          if (response.success) {
            var idUser = response.idUser;
            window.location.href =
              "index.php?page=user&msg=deleted&msg=deleted";
          } else {
            window.location.href = "index.php?page=user&msg=errorajax";
          }
        },
        error: function (xhr, status, error) {
          //window.location.href = "index.php?page=user&msg=errorajax";
          console.error("AJAX Error:", error);
        },
      });
      $("#confirmDeletionSubmit").modal("hide");
    });

    $("#modalFormAddEditUser").on("hidden.bs.modal", function () {
      //window.location.href = "index.php?page=user";
    });

    $("#cancelChange").on("click", function () {
      if (pendingCheckbox) {
        pendingCheckbox.prop(
          "checked",
          pendingIsChecked === "yes" ? false : true
        );
      }
      pendingCheckbox = null;
      pendingIdUser = null;
      pendingIsChecked = null;
    });

    $("#confirmModalVerifie").on("hidden.bs.modal", function (e) {
      if (pendingCheckbox) {
        pendingCheckbox.prop(
          "checked",
          pendingIsChecked === "yes" ? false : true
        );
      }
      pendingCheckbox = null;
      pendingIdUser = null;
      pendingIsChecked = null;
    });
  }

  // Hide loading spinner and show main content
  $("#loadingContainer").fadeOut(900, function () {
    $(this).remove();
    $("#main-content").fadeIn();
  });

});
