// ======================= VALIDATION HELPERS =======================
const TOAST_DURATION = 5000; // 5 seconds

const TOAST_ICONS = {
  success: "✓",
  error: "✕",
  info: "i",
  warning: "⚠",
};

function showToast(type = "info", title = "", message = "", duration = 3000) {
  const container = document.getElementById("toastContainer");
  if (!container) {
    console.error("Toast container not found!");
    return;
  }
  console.log(container);

  const toast = document.createElement("div");
  console.log(toast);

  toast.className = `custom-toast ${type}`;

  toast.innerHTML = `
        <div class="toast-icon">${TOAST_ICONS[type]}</div>
        <div class="toast-content">
            <div class="toast-title">${title}</div>
            <div class="toast-message">${message}</div>
        </div>
        <button class="toast-close" onclick="removeToast(this.parentElement)">×</button>
        <div class="toast-progress" style="animation-duration: ${duration}ms"></div>
    `;

  container.appendChild(toast);

  setTimeout(() => {
    removeToast(toast);
  }, duration);
}

function removeToast(toast) {
  if (toast.classList.contains("removing")) return;

  toast.classList.add("removing");

  setTimeout(() => {
    toast.remove();
  }, 300);
}

function toastSuccess(message, title = "Success!") {
  showToast("success", title, message);
}

function toastError(message, title = "Error!") {
  showToast("error", title, message);
}

function toastInfo(message, title = "Info") {
  showToast("info", title, message);
}

function toastWarning(message, title = "Warning!") {
  showToast("warning", title, message);
}

// ======================= REUSABLE VALIDATION FUNCTIONS =======================

/**
 * Validate email address
 * @param {string} email - Email to validate
 * @returns {string|null} - Error message or null if valid
 */
function validateEmail(email) {
  if (!email || email.trim() === "") {
    return "Enter your email";
  }

  if (email.includes(" ")) {
    return "Email cannot contain spaces";
  }

  const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!pattern.test(email)) {
    return "Enter a valid email";
  }

  return null; // valid email
}

/**
 * Validate password
 * @param {string} password - Password to validate
 * @returns {string|null} - Error message or null if valid
 */
function validatePassword(password) {
  if (!password || password.trim() === "") {
    return "Enter your password";
  }

  if (password.length < 8) {
    return "Use 8 characters or more for your password";
  }

  if (password.includes(" ")) {
    return "Password cannot contain spaces";
  }

  return null; // valid password
}

/**
 * Validate name fields (generic text validation with custom field name)
 * @param {string} value - Value to validate
 * @param {string} fieldName - Name of the field (e.g., "country", "category", "state")
 * @returns {string|null} - Error message or null if valid
 */
function validateName(value, fieldName = "name") {
  if (!value || value.trim() === "") {
    return `Enter ${fieldName}`;
  }
  return null;
}

/**
 * Validate text fields (generic)
 * @param {string} value - Value to validate
 * @param {string} fieldName - Name of the field
 * @returns {string|null} - Error message or null if valid
 */
function validateText(value, fieldName) {
  if (!value || value.trim() === "") {
    return `Enter ${fieldName}`;
  }
  return null;
}

/**
 * Validate select/dropdown fields
 * @param {string} value - Selected value
 * @param {string} fieldName - Name of the field
 * @returns {string|null} - Error message or null if valid
 */
function validateSelect(value, fieldName) {
  if (!value || value === "") {
    return `Select ${fieldName}`;
  }
  return null;
}

/**
 * Validate currency field
 * @param {string} currency - Currency to validate
 * @returns {string|null} - Error message or null if valid
 */
function validateCurrency(currency) {
  if (!currency || currency.trim() === "") {
    return "Enter currency";
  }
  return null;
}

/**
 * Validate image files (with dynamic field name and required/optional)
 * @param {File} file - File object to validate
 * @param {string} fieldName - Name of the field (e.g., "country image", "category image")
 * @param {boolean} isRequired - Whether the image is required
 * @returns {string|null} - Error message or null if valid
 */
function validateImage(file, fieldName = "image", isRequired = true) {
  // Check if file is required and missing
  if (isRequired && !file) {
    return `Select ${fieldName}`;
  }

  // If not required and no file provided, it's valid
  if (!isRequired && !file) {
    return null;
  }

  // Validate file type
  const allowedTypes = ["image/jpeg", "image/png", "image/webp"];
  if (!allowedTypes.includes(file.type)) {
    return "Only JPG, PNG or WEBP images allowed";
  }

  return null; // valid image
}

function validateNumber(value, label) {
  if (!value || value <= 0) {
    return `Enter valid ${label}`;
  }
  return null;
}

function validateCode(value) {
  if (!value || value.trim() === "") {
    return "Enter country code";
  }
  return null;
}

// ======================= RESET ERROR HELPERS =======================

function resetLoginErrors() {
  const loginEmail = document.querySelector("#login-email");
  const loginPass = document.querySelector("#login-password");
  const loginEmailErrorBox = document.querySelector("#login-email-error");
  const loginPassErrorBox = document.querySelector("#login-password-error");

  if (loginEmail) {
    loginEmail.setCustomValidity("");
  }
  if (loginPass) {
    loginPass.setCustomValidity("");
  }
  if (loginEmailErrorBox) {
    loginEmailErrorBox.textContent = "";
  }
  if (loginPassErrorBox) {
    loginPassErrorBox.textContent = "";
  }
}

function resetRegErrors() {
  const registerEmail = document.querySelector("#reg-email");
  const registerPassword = document.querySelector("#reg-password");
  const registerName = document.querySelector("#reg-name");
  const registerEmailErrorBox = document.querySelector("#reg-email-error");
  const registerPassErrorBox = document.querySelector("#reg-password-error");
  const regsiterNameErrorBox = document.querySelector("#reg-name-error");

  if (registerEmail) {
    registerEmail.setCustomValidity("");
  }
  if (registerPassword) {
    registerPassword.setCustomValidity("");
  }
  if (registerName) {
    registerName.setCustomValidity("");
  }

  if (registerEmailErrorBox) {
    registerEmailErrorBox.textContent = "";
  }
  if (registerPassErrorBox) {
    registerPassErrorBox.textContent = "";
  }
  if (regsiterNameErrorBox) {
    regsiterNameErrorBox.textContent = "";
  }
}

function resetForgotPasswordErrors() {
  const forgotPasswordEmail = document.querySelector("#forgot-email");
  const forgotPasswordEmailErrorBox = document.querySelector(
    "#forgot-email-error"
  );

  if (forgotPasswordEmail) {
    forgotPasswordEmail.setCustomValidity("");
  }
  if (forgotPasswordEmailErrorBox) {
    forgotPasswordEmailErrorBox.textContent = "";
  }
}

// ======================= API CALLS =======================

async function loginUser(email, password, form) {
  try {
    const response = await fetch("api/authentication/firebase_login.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ email, password }),
    });

    const result = await response.json();
    console.log("Login API Response:", result);

    if (result.status === 200) {
      localStorage.setItem("email", email);
      await checkEmailStatus(form);
    } else if (result.status === 404) {
      toastError(result.message);
      window.href.location = "register.php";
    } else {
      console.warn("Login Failed:", result.message);

      // Clear form + errors on error
      form.reset();
      form.classList.remove("was-validated");
      resetLoginErrors();

      toastError(result.message);
    }
  } catch (error) {
    console.error("Login error:", error);
    alert("Something went wrong. Please try again.");
  }
}
async function verifyEmail() {
  let email = localStorage.getItem("email");
  try {
    const response = await fetch("api/authentication/verify_email_status.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ email }),
    });

    const result = await response.json();
    console.log("Verify Email API Response:", result);

    if (result.status === 200) {
      if (result.data.emailVerified === true) {
        toastSuccess("User Created Successfully");
        setTimeout(() => {
          window.location.href = "view/backend/dashboard.php";
        }, 1500);
      } else {
        toastError("Email is not verified yet!");
      }
    } else if (result.status === 404) {
      console.warn("Verify Failed:", result.message);
      toastError(result.message);
      setTimeout(() => {
        window.location.href = "register.php";
      }, 1500);
    } else {
      console.warn("Verify Failed:", result.message);
      toastError(result.message);
    }
  } catch (error) {
    console.error("Verify Email Error:", error);
    toastError("Something went wrong. Please try again.");
  }
}

async function checkEmailStatus(form) {
  let email = localStorage.getItem("email");

  try {
    const response = await fetch("api/authentication/verify_email_status.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ email }),
    });

    const result = await response.json();
    console.log("Verify Email API Response:", result);

    if (result.status === 200) {
      if (result.data.emailVerified === true) {
        toastSuccess("SingUp Success");
        window.location.href = "view/backend/dashboard.php";
      } else {
        toastError("Email Verification Pending");
        await resendVerificationMail();
        setTimeout(() => {
          window.location.href = "email-verification.php";
        }, 1500);
      }
    } else {
      console.log(response);
      console.warn("Verify Failed:", result.message);
      toastError(result.message);
      form.reset();
      form.classList.remove("was-validated");
      resetLoginErrors();
    }
  } catch (error) {
    console.error("Verify Email Error:", error);
    toastError("Something went wrong. Please try again.");
  }
}

async function resendVerificationMail(showToast = true) {
  let email = localStorage.getItem("email");

  try {
    const response = await fetch(
      "api/authentication/resend_verification_email.php",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ email }),
      }
    );

    const result = await response.json();
    console.log("Resned Verification Email API Response:", result);

    if (result.status === 200) {
      // ⭐ SUCCESS TOAST
      if (showToast) toastSuccess(response.message);
    } else {
      console.warn("Unable To Send Email Verification Link:", result.message);
      if (showToast) toastError(result.message);
    }
  } catch (error) {
    console.error("Verification Email Send Error:", error);
    toastError("Something went wrong. Please try again.");
  }
}
async function registerUser(name, email, password, registerForm) {
  try {
    const response = await fetch("api/authentication/firebase_register.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ name, email, password }),
    });
    console.log(response);

    const result = await response.json();
    console.log("Register API Response:", result);

    if (result.status === 201) {
      toastSuccess("SignUp Success");
      localStorage.setItem("email", email);
      setTimeout(() => {
        window.location.href = "email-verification.php";
      }, 2000);
    } else if (result.status === 409) {
      toastError(result.message);
      setTimeout(() => {
        window.location.href = "login.php";
      }, 2000);
    } else {
      console.warn("Register Failed:", result.message);

      // Clear form + errors on error
      registerForm.reset();
      registerForm.classList.remove("was-validated");
      resetRegErrors();

      toastError(result.message);
    }
  } catch (error) {
    console.error("Register error:", error.toString());
    alert("Something went wrong. Please try again.");
  }
}
function sendResetVerificationLinkTimer() {
  let timeLeft = 30;
  const timerEl = document.getElementById("timerText");
  const resendBtn = document.getElementById("resendLink");
  timerEl.style = "display:inline-block";
  let timer = setInterval(() => {
    let minutes = String(Math.floor(timeLeft / 60)).padStart(2, "0");
    let seconds = String(timeLeft % 60).padStart(2, "0");

    timerEl.textContent = `${minutes}:${seconds}`;

    if (timeLeft <= 0) {
      clearInterval(timer);
      timerEl.textContent = "00:30";
      timerEl.style = "display:none";
      resendBtn.style = "display:inline-block";
    }
    timeLeft--;
  }, 1000);
}
async function forgotPasswordUser(email, form) {
  try {
    const response = await fetch(
      "api/authentication/firebase_forgot_password.php",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ email }),
      }
    );

    const result = await response.json();
    console.log("Forgot Password API Response:", result);

    if (result.status === 200) {
      toastSuccess("Password reset link sent to your email");
    } else {
      console.warn("Forgot Password Failed:", result.message);

      // Clear form + errors on error
      form.reset();
      form.classList.remove("was-validated");
      resetForgotPasswordErrors();

      toastError("Failed to send reset link: " + result.message);
    }
  } catch (error) {
    console.error("Forgot Password error:", error);
    alert("Something went wrong. Please try again.");
  }
}

// ======================= DOM EVENTS =======================

document.addEventListener("DOMContentLoaded", () => {
  // ---------- LOGIN FORM HANDLING ----------
  const loginEmail = document.querySelector("#login-email");
  const loginPass = document.querySelector("#login-password");
  const loginForm = document.querySelector("#login-form");
  const loginEmailErrorBox = document.querySelector("#login-email-error");
  const loginPassErrorBox = document.querySelector("#login-password-error");
  const loginButton = document.querySelector("#login-btn");

  if (loginForm) {
    loginForm.addEventListener("submit", async (e) => {
      e.preventDefault();
      e.stopPropagation();

      loginButton.disabled = true;
      loginButton.innerHTML = `<span class="loader"></span>`;

      resetLoginErrors();

      // Validate Inputs
      const emailError = validateEmail(loginEmail.value);
      const passError = validatePassword(loginPass.value);

      if (emailError) {
        loginEmail.setCustomValidity(emailError);
        loginEmailErrorBox.textContent = emailError;
      }

      if (passError) {
        loginPass.setCustomValidity(passError);
        loginPassErrorBox.textContent = passError;
      }

      // Bootstrap validation UI
      loginForm.classList.add("was-validated");

      if (loginForm.checkValidity()) {
        await loginUser(loginEmail.value, loginPass.value, loginForm);
      }

      loginButton.disabled = false;
      loginButton.innerHTML = `Submit`;
    });
  }

  // ---------- REGISTER FORM HANDLING ----------

  const registerEmail = document.querySelector("#reg-email");
  const registerPassword = document.querySelector("#reg-password");
  const registerName = document.querySelector("#reg-name");
  const registerForm = document.querySelector("#register-form");
  const registerEmailErrorBox = document.querySelector("#reg-email-error");
  const registerPassErrorBox = document.querySelector("#reg-password-error");
  const regsiterNameErrorBox = document.querySelector("#reg-name-error");
  const registerButton = document.querySelector("#register-btn");

  if (registerForm) {
    registerForm.addEventListener("submit", async (e) => {
      e.preventDefault();
      e.stopPropagation();

      registerButton.disabled = true;
      registerButton.innerHTML = `<span class="loader"></span>`;

      resetRegErrors();

      // Validate Inputs
      const regEmailError = validateEmail(registerEmail.value);
      const regPassError = validatePassword(registerPassword.value);
      const regNameError = validateName(registerName.value, "your name");

      if (regEmailError) {
        registerEmail.setCustomValidity(regEmailError);
        registerEmailErrorBox.textContent = regEmailError;
      }

      if (regPassError) {
        registerPassword.setCustomValidity(regPassError);
        registerPassErrorBox.textContent = regPassError;
      }

      if (regNameError) {
        registerName.setCustomValidity(regNameError);
        regsiterNameErrorBox.textContent = regNameError;
      }

      // Bootstrap validation UI
      registerForm.classList.add("was-validated");

      if (registerForm.checkValidity()) {
        await registerUser(
          registerName.value,
          registerEmail.value,
          registerPassword.value,
          registerForm
        );
      }

      registerButton.disabled = false;
      registerButton.innerHTML = `Submit`;
    });
  }

  // ---------- Forgot Password FORM HANDLING ----------

  const forgotPasswordEmail = document.querySelector("#forgot-email");
  const forgotPasswordForm = document.querySelector("#forgot-form");
  const forgotPasswordEmailErrorBox = document.querySelector(
    "#forgot-email-error"
  );
  const forgotPasswordButton = document.querySelector("#forgot-btn");

  if (forgotPasswordForm) {
    forgotPasswordForm.addEventListener("submit", async (e) => {
      e.preventDefault();
      e.stopPropagation();

      forgotPasswordButton.disabled = true;
      forgotPasswordButton.innerHTML = `<span class="loader"></span>`;

      resetForgotPasswordErrors();

      // Validate Inputs
      const emailError = validateEmail(forgotPasswordEmail.value);

      if (emailError) {
        forgotPasswordEmail.setCustomValidity(emailError);
        forgotPasswordEmailErrorBox.textContent = emailError;
      }

      // Bootstrap validation UI
      forgotPasswordForm.classList.add("was-validated");

      if (forgotPasswordForm.checkValidity()) {
        await forgotPasswordUser(forgotPasswordEmail.value, forgotPasswordForm);
      }

      forgotPasswordButton.disabled = false;
      forgotPasswordButton.innerHTML = `Submit`;
    });
  }

  if (
    window.location.pathname === "/carrier_job_admin/email-verification.php"
  ) {
    sendResetVerificationLinkTimer();
  }
  const resendBtn = document.getElementById("resendLink");
  if (resendBtn) {
    resendBtn.addEventListener("click", async (e) => {
      resendBtn.style = "display:none";
      sendResetVerificationLinkTimer();
      await resendVerificationMail();
    });
  }
  const verifyEmailBtn = document.getElementById("verify-btn");
  if (verifyEmailBtn) {
    verifyEmailBtn.addEventListener("click", async (e) => {
      verifyEmailBtn.disabled = true;
      verifyEmailBtn.innerHTML = `<span class="loader"></span>`;
      await verifyEmail();
      verifyEmailBtn.disabled = false;
      verifyEmailBtn.innerHTML = `Submit`;
    });
  }
});

// Sidebar Toggle Functions
function toggleSidebar() {
  const sidebar = document.getElementById("sidebar");
  sidebar.classList.toggle("collapsed");

  // Save state to localStorage
  const isCollapsed = sidebar.classList.contains("collapsed");
  localStorage.setItem("sidebarCollapsed", isCollapsed);
}

// Mobile Sidebar Functions
function openMobileSidebar() {
  const sidebar = document.getElementById("sidebar");
  const overlay = document.getElementById("sidebarOverlay");

  sidebar.classList.add("open");
  overlay.classList.add("active");
  document.body.style.overflow = "hidden"; // Prevent background scroll
}

function closeMobileSidebar() {
  const sidebar = document.getElementById("sidebar");
  const overlay = document.getElementById("sidebarOverlay");

  sidebar.classList.remove("open");
  overlay.classList.remove("active");
  document.body.style.overflow = ""; // Restore scroll
}

// Load saved sidebar state on page load
document.addEventListener("DOMContentLoaded", function () {
  const sidebar = document.getElementById("sidebar");
  const isCollapsed = localStorage.getItem("sidebarCollapsed") === "true";

  if (isCollapsed && window.innerWidth > 768) {
    sidebar.classList.add("collapsed");
  }
});

// Close mobile sidebar when screen is resized to desktop
window.addEventListener("resize", function () {
  if (window.innerWidth > 768) {
    closeMobileSidebar();
  }
});

// ============================================
// UTILITY FUNCTIONS (Optional - Add as needed)
// ============================================

/**
 * Show toast notification
 * @param {string} message - Message to display
 * @param {string} type - Type of notification (success, error, info, warning)
 */
// function showToast(message, type = "info") {
//   // You can implement a toast notification system here
//   console.log(`[${type.toUpperCase()}] ${message}`);
// }

/**
 * Confirm action with user
 * @param {string} message - Confirmation message
 * @returns {boolean} - User's choice
 */
function confirmAction(message) {
  return confirm(message);
}

/**
 * Format number with commas
 * @param {number} num - Number to format
 * @returns {string} - Formatted number
 */
function formatNumber(num) {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

/**
 * Format date to readable format
 * @param {string|Date} date - Date to format
 * @returns {string} - Formatted date
 */
function formatDate(date) {
  const d = new Date(date);
  return d.toLocaleDateString("en-US", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
}

document
  .querySelector(".profile-toggle")
  .addEventListener("click", function () {
    document.querySelector(".profile-dropdown").classList.toggle("active");
  });

/*DataTable Initialization*/
$(document).ready(function () {
  $("#myTable").DataTable({
    responsive: true,
    pageLength: 10,
  });
});

$(document).ready(function () {
  $(".summernote").summernote({
    height: 180,
    placeholder: "Write here...",
    toolbar: [
      ["style", ["bold", "italic", "underline"]],
      ["para", ["ul", "ol", "paragraph"]],
      ["insert", ["link"]],
      ["view", ["codeview"]],
    ],
  });
});

document.getElementById("profileImage").addEventListener("change", function () {
  const file = this.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = () => {
    document.getElementById("profilePreview").src = reader.result;
  };
  reader.readAsDataURL(file);
});

// Image preview
document.addEventListener("DOMContentLoaded", () => {
  // Add Country Image
  const countryImage = document.getElementById("c_image");
  const countryImagePreview = document.getElementById("imagePreview");

  if (countryImage && countryImagePreview) {
    countryImage.addEventListener("change", () => {
      const file = countryImage.files[0];
      countryImagePreview.src = file
        ? URL.createObjectURL(file)
        : "../../../assets/img/default-country-icon.png";
    });
  }

  // Edit Country Image
  const editCountry = document.getElementById("c_image1");
  if (editCountry) {
    editCountry.addEventListener("change", function () {
      const file = this.files[0];
      const preview = document.getElementById("imagePreview1");

      preview.src = file
        ? URL.createObjectURL(file)
        : "../../../assets/img/default-country-icon.png";
    });
  }

  // Add Category Image
  const categoryImage = document.getElementById("c_image2");
  const categoryImagePreview = document.getElementById("imagePreview2");

  if (categoryImage && categoryImagePreview) {
    categoryImage.addEventListener("change", () => {
      const file = categoryImage.files[0];
      categoryImagePreview.src = file
        ? URL.createObjectURL(file)
        : "../../../assets/img/default-category-icon.png";
    });
  }

  // Edit Category Image
  const editCategory = document.getElementById("c_image3");
  if (editCategory) {
    editCategory.addEventListener("change", function () {
      const file = this.files[0];
      const preview = document.getElementById("imagePreview3");

      preview.src = file
        ? URL.createObjectURL(file)
        : "../../../assets/img/default-category-icon.png";
    });
  }
});

// Add Country Form Submission
document.addEventListener("DOMContentLoaded", function () {
  const addForm = document.getElementById("addCountryForm");
  if (!addForm) return;

  $("#addCountryForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const nameInput = document.getElementById("countryName");
    const currencyInput = document.getElementById("countryCurrency");
    const imageInput = document.getElementById("c_image");
    const codeInput = document.getElementById("countryCode");

    const nameErrorBox = document.getElementById("country-name-error");
    const currencyErrorBox = document.getElementById("country-currency-error");
    const codeErrorBox = document.getElementById("country-code-error");

    // reset
    // reset errors safely
    if (nameErrorBox) nameErrorBox.textContent = "";
    if (currencyErrorBox) currencyErrorBox.textContent = "";
    if (codeErrorBox) codeErrorBox.textContent = "";

    nameInput.classList.remove("is-invalid");
    currencyInput.classList.remove("is-invalid");
    codeInput.classList.remove("is-invalid");

    // 🔹 NAME
    const nameError = validateName(nameInput.value, "country name");
    if (nameError) {
      nameInput.setCustomValidity(nameError);
      nameErrorBox.textContent = nameError;
      isValid = false;
    } else {
      nameInput.setCustomValidity("");
    }

    // 🔹 CURRENCY
    const currencyError = validateCurrency(currencyInput.value);
    if (currencyError) {
      currencyInput.setCustomValidity(currencyError);
      currencyErrorBox.textContent = currencyError;
      isValid = false;
    } else {
      currencyInput.setCustomValidity("");
    }

    // 🔹 CODE
    const codeError = validateCode(codeInput.value);
    if (codeError) {
      codeInput.setCustomValidity(codeError);
      codeErrorBox.textContent = codeError;
      isValid = false;
    } else {
      codeInput.setCustomValidity("");
    }

    // 🔹 IMAGE (OPTIONAL → no validation)
    imageInput.setCustomValidity("");

    // ✅ show bootstrap validation UI
    this.classList.add("was-validated");

    // ⛔ STOP AJAX
    if (!isValid) return;

    // ✅ VALID → AJAX
    const formData = new FormData(this);

    $.ajax({
      url: "../../../api/country/create_country.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          bootstrap.Modal.getInstance(
            document.getElementById("addCountryModal")
          )?.hide();

          Swal.fire({
            icon: "success",
            title: "Success",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          });

          setTimeout(() => location.reload(), 1500);
        } else {
          Swal.fire({ icon: "error", title: "Error", text: data.message });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// Edit Country Form Submission
function EditCountry(id, name, currency, code, icon) {
  const idInput = document.getElementById("edit_country_id");
  const nameInput = document.getElementById("edit_name");
  const currencyInput = document.getElementById("edit_currency");
  const codeInput = document.getElementById("edit_code");
  const imagePreview = document.getElementById("imagePreview1");
  const fileInput = document.getElementById("c_image1");
  const modalEl = document.getElementById("editCountryModal");

  // ❗ If modal is not on this page, stop safely
  if (
    !idInput ||
    !nameInput ||
    !currencyInput ||
    !codeInput ||
    !imagePreview ||
    !modalEl
  ) {
    console.warn("EditCountry modal elements not found on this page");
    return;
  }

  idInput.value = id;
  nameInput.value = name;
  currencyInput.value = currency;
  codeInput.value = code;

  imagePreview.src = icon
    ? "../../../uploads/country_icon/" + icon
    : "../../../assets/img/default-country-icon.png";

  if (fileInput) fileInput.value = "";

  const modal = new bootstrap.Modal(modalEl);
  modal.show();
}
document.addEventListener("DOMContentLoaded", () => {
  const editCountryForm = document.getElementById("editCountryForm");
  if (!editCountryForm) return;

  $("#editCountryForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const nameInput = document.getElementById("edit_name");
    const currencyInput = document.getElementById("edit_currency");
    const codeInput = document.getElementById("edit_code");
    const imageInput = document.getElementById("c_image1");

    const nameErrorBox = document.getElementById("edit-country-name-error");
    const currencyErrorBox = document.getElementById(
      "edit-country-currency-error"
    );
    const codeErrorBox = document.getElementById("edit-country-code-error");
    const imageErrorBox = document.getElementById("edit-country-image-error");

    // ---------- RESET ----------
    [nameInput, currencyInput, codeInput, imageInput].forEach((el) => {
      el.classList.remove("is-valid", "is-invalid");
    });

    nameErrorBox.textContent = "";
    currencyErrorBox.textContent = "";
    codeErrorBox.textContent = "";
    imageErrorBox.textContent = "";

    // ---------- NAME ----------
    if (!nameInput.value.trim()) {
      nameInput.classList.add("is-invalid");
      nameErrorBox.textContent = "Enter country name";
      isValid = false;
    } else {
      nameInput.classList.add("is-valid");
    }

    // ---------- CURRENCY ----------
    if (!currencyInput.value.trim()) {
      currencyInput.classList.add("is-invalid");
      currencyErrorBox.textContent = "Enter currency";
      isValid = false;
    } else {
      currencyInput.classList.add("is-valid");
    }

    // ---------- CODE ----------
    const codeError = validateCode(codeInput.value);
    if (codeError) {
      codeInput.classList.add("is-invalid");
      codeErrorBox.textContent = codeError;
      isValid = false;
    } else {
      codeInput.classList.add("is-valid");
    }

    // ---------- IMAGE (OPTIONAL) ----------
    if (imageInput.files.length > 0) {
      const imgError = validateImage(
        imageInput.files[0],
        "country image",
        false
      );
      if (imgError) {
        imageInput.classList.add("is-invalid");
        imageErrorBox.textContent = imgError;
        isValid = false;
      } else {
        imageInput.classList.add("is-valid");
      }
    } else {
      imageInput.classList.remove("is-valid", "is-invalid");
    }

    // ⛔ STOP AJAX
    if (!isValid) return;

    // ✅ AJAX
    const formData = new FormData(this);

    $.ajax({
      url: "../../../api/country/update_country.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          bootstrap.Modal.getInstance(
            document.getElementById("editCountryModal")
          )?.hide();

          Swal.fire({
            icon: "success",
            title: "Success",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          });

          setTimeout(() => location.reload(), 1500);
        } else {
          Swal.fire({ icon: "error", title: "Error", text: data.message });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// Delete Country
function DeleteCountry(id) {
  if (!id) return;

  Swal.fire({
    title: "Are you sure?",
    text: "This will permanently delete the country and cannot be undone!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "red",
    cancelButtonColor: "#3085d6",
    confirmButtonText: "Yes, delete it!",
  }).then((result) => {
    if (result.isConfirmed) {
      // Proceed with delete
      $.ajax({
        url: "../../../api/country/delete_country.php",
        type: "POST",
        dataType: "json",
        data: { id: id },
        success: function (data) {
          Swal.fire({
            icon: "success",
            title: "Deleted!",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          });

          setTimeout(() => {
            location.reload();
          }, 1500);
        },
        error: function (xhr) {
          let message = "Something went wrong";

          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
          });
        },
      });
    }
  });
}

document.addEventListener("DOMContentLoaded", function () {
  const categoryForm = document.getElementById("addCategoryForm");
  if (!categoryForm) return;

  $("#addCategoryForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const nameInput = this.querySelector('input[name="category_name"]');
    const imageInput = this.querySelector("#c_image2");

    const nameErrorBox = document.querySelector("#category-name-error");

    // reset errors
    nameInput.setCustomValidity("");
    imageInput.setCustomValidity("");
    nameErrorBox.textContent = "";

    // ---------- NAME ----------
    const nameError = validateName(nameInput.value, "category name");
    if (nameError) {
      nameInput.setCustomValidity(nameError);
      nameErrorBox.textContent = nameError;
      isValid = false;
    }

    // ---------- IMAGE (OPTIONAL → NO VALIDATION) ----------
    imageInput.setCustomValidity("");

    this.classList.add("was-validated");

    // ⛔ STOP EVERYTHING IF INVALID
    if (!isValid) return;

    // ✅ VALID → AJAX
    let formData = new FormData(this);

    $.ajax({
      url: "../../../api/category/create_category.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "Category Added!",
            text: data.message,
            showConfirmButton: false,
            timer: 1500,
          }).then(() => {
            const modalEl = document.getElementById("addCategoryModal");
            bootstrap.Modal.getInstance(modalEl)?.hide();
            categoryForm.reset();
            location.reload();
          });
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: data.message,
          });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// ================= EDIT CATEGORY OPEN MODAL =================
function EditCategory(id, name, icon) {
  const idInput = document.getElementById("edit_category_id");
  const nameInput = document.getElementById("edit_category_name");
  const imagePreview = document.getElementById("imagePreview3");
  const fileInput = document.getElementById("c_image3");
  const modalEl = document.getElementById("editCategoryModal");

  if (!idInput || !nameInput || !imagePreview || !modalEl) {
    console.warn("EditCategory modal elements not found");
    return;
  }

  idInput.value = id;
  nameInput.value = name;

  imagePreview.src = icon
    ? "../../../uploads/category_icon/" + icon
    : "../../../assets/img/default-category-icon.png";

  if (fileInput) fileInput.value = "";

  const modal = new bootstrap.Modal(modalEl);
  modal.show();
}

// ================= EDIT CATEGORY SUBMIT =================
document.addEventListener("DOMContentLoaded", function () {
  const editCategoryForm = document.getElementById("editCategoryForm");
  if (!editCategoryForm) return;

  $("#editCategoryForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const nameInput = document.getElementById("edit_category_name");
    const imageInput = document.getElementById("c_image3");

    const nameErrorBox = document.getElementById("edit-category-name-error");
    const imageErrorBox = document.getElementById("edit-category-image-error");

    // reset errors
    nameInput.setCustomValidity("");
    imageInput.setCustomValidity("");
    nameErrorBox.textContent = "";
    imageErrorBox.textContent = "";

    // ---------- NAME (REQUIRED) ----------
    const nameError = validateName(nameInput.value, "category name");
    if (nameError) {
      nameInput.classList.add("is-invalid");
      nameInput.classList.remove("is-valid");
      nameErrorBox.textContent = nameError;
      isValid = false;
    } else {
      nameInput.classList.remove("is-invalid");
      nameInput.classList.add("is-valid");
      nameErrorBox.textContent = "";
    }

    // ---------- IMAGE (OPTIONAL) ----------
    if (imageInput.files.length > 0) {
      const imageError = validateImage(
        imageInput.files[0],
        "category image",
        false
      );

      if (imageError) {
        // ❌ invalid image
        imageInput.classList.add("is-invalid");
        imageInput.classList.remove("is-valid");
        imageErrorBox.textContent = imageError;
        isValid = false;
      } else {
        // ✅ valid image → SHOW GREEN TICK
        imageInput.classList.remove("is-invalid");
        imageInput.classList.add("is-valid");
        imageErrorBox.textContent = "";
      }
    } else {
      // ⚪ no image → NO validation state
      imageInput.classList.remove("is-valid", "is-invalid");
      imageErrorBox.textContent = "";
    }

    // ⛔ STOP AJAX IF INVALID
    if (!isValid) {
      return;
    }

    // ✅ VALID → AJAX
    const formData = new FormData(this);

    $.ajax({
      url: "../../../api/category/update_category.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        console.log("Update response:", data);

        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "Category Updated!",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          });

          setTimeout(() => {
            const modalEl = document.getElementById("editCategoryModal");
            bootstrap.Modal.getInstance(modalEl)?.hide();
            $("#editCategoryForm")[0].reset();
            location.reload();
          }, 1500);
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: data.message,
            confirmButtonColor: "#d33",
          });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// Delete Category
function DeleteCategory(id) {
  if (!id) return;

  Swal.fire({
    title: "Are you sure?",
    text: "This will permanently delete the category and cannot be undone!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "red",
    cancelButtonColor: "#3085d6",
    confirmButtonText: "Yes, delete it!",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../../api/category/delete_category.php",
        type: "POST",
        dataType: "json",
        data: { id: id },

        success: function (data) {
          console.log("Delete category response:", data);

          if (data.status === 200) {
            Swal.fire({
              icon: "success",
              title: "Deleted!",
              text: data.message,
              timer: 1500, // automatically close
              showConfirmButton: false, // no OK button
            });

            setTimeout(() => {
              location.reload();
            }, 1500);
          } else {
            Swal.fire({
              icon: "error",
              title: "Error",
              text: data.message,
              confirmButtonColor: "#d33",
            });
          }
        },

        error: function (xhr) {
          let message = "Something went wrong";

          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
          });
        },
      });
    }
  });
}

// Add State Form Submission

document.addEventListener("DOMContentLoaded", function () {
  const addStateForm = document.getElementById("addStateForm");

  $("#addStateForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const countryInput = document.getElementById("countryId");
    const stateInput = document.getElementById("stateName");

    const countryErrorBox = document.getElementById("state-country-error");
    const stateErrorBox = document.getElementById("state-name-error");

    // reset errors
    countryInput.setCustomValidity("");
    stateInput.setCustomValidity("");
    countryErrorBox.textContent = "";
    stateErrorBox.textContent = "";

    // ---------- COUNTRY ----------
    const countryError = validateSelect(countryInput.value, "country");
    if (countryError) {
      countryInput.setCustomValidity(countryError);
      countryErrorBox.textContent = countryError;
      isValid = false;
    }

    // ---------- STATE NAME ----------
    const stateError = validateText(stateInput.value, "state name");
    if (stateError) {
      stateInput.setCustomValidity(stateError);
      stateErrorBox.textContent = stateError;
      isValid = false;
    }

    // show bootstrap validation UI
    this.classList.add("was-validated");

    // ⛔ STOP AJAX IF INVALID
    if (!isValid) {
      return;
    }

    // ✅ VALID → AJAX
    let formData = new FormData(this);

    $.ajax({
      url: "../../../api/state/create_state.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "State Added!",
            text: data.message,
            showConfirmButton: false,
            timer: 1500,
          }).then(() => {
            const modalEl = document.getElementById("addStateModal");
            bootstrap.Modal.getInstance(modalEl)?.hide();
            addStateForm.reset();
            location.reload();
          });
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: data.message,
          });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// Edit State Form Submission
function EditState(id, countryID, name, icon) {
  const idInput = document.getElementById("edit_state_id");
  const countryInput = document.getElementById("edit_country_id");
  const nameInput = document.getElementById("edit_state_name");
  const modalEl = document.getElementById("editStateModal");

  if (!idInput || !nameInput || !countryInput || !modalEl) {
    console.warn("EditState modal elements not found");
    return;
  }

  idInput.value = id;
  nameInput.value = name;
  countryInput.value = countryID;

  const modal = new bootstrap.Modal(modalEl);
  modal.show();
}
document.addEventListener("DOMContentLoaded", function () {
  const editStateForm = document.getElementById("editStateForm");
  if (!editStateForm) return;

  $("#editStateForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const countryInput = document.getElementById("edit_country_id");
    const stateInput = document.getElementById("edit_state_name");

    const countryErrorBox = document.getElementById("edit-state-country-error");
    const stateErrorBox = document.getElementById("edit-state-name-error");

    // reset errors
    countryInput.setCustomValidity("");
    stateInput.setCustomValidity("");
    countryErrorBox.textContent = "";
    stateErrorBox.textContent = "";

    // ---------- COUNTRY ----------
    const countryError = validateSelect(countryInput.value, "country");
    if (countryError) {
      countryInput.setCustomValidity(countryError);
      countryErrorBox.textContent = countryError;
      isValid = false;
    }

    // ---------- STATE NAME ----------
    const stateError = validateText(stateInput.value, "state name");
    if (stateError) {
      stateInput.setCustomValidity(stateError);
      stateErrorBox.textContent = stateError;
      isValid = false;
    }

    // show bootstrap validation UI
    this.classList.add("was-validated");

    // ⛔ STOP AJAX IF INVALID
    if (!isValid) return;

    // ✅ VALID → AJAX
    const formData = new FormData(this);

    $.ajax({
      url: "../../../api/state/update_state.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "State Updated!",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          });

          setTimeout(() => {
            const modalEl = document.getElementById("editStateModal");
            bootstrap.Modal.getInstance(modalEl)?.hide();
            editStateForm.reset();
            location.reload();
          }, 1500);
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: data.message,
          });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// Delete State
function DeleteState(id) {
  if (!id) return;

  Swal.fire({
    title: "Are you sure?",
    text: "This will permanently delete the state and cannot be undone!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "red",
    cancelButtonColor: "#3085d6",
    confirmButtonText: "Yes, delete it!",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../../api/state/delete_state.php",
        type: "POST",
        dataType: "json",
        data: { id: id },

        success: function (data) {
          console.log("Delete state response:", data);

          if (data.status === 200) {
            Swal.fire({
              icon: "success",
              title: "Deleted!",
              text: data.message,
              timer: 1500, // automatically close
              showConfirmButton: false, // no OK button
            });

            setTimeout(() => {
              location.reload();
            }, 1500);
          } else {
            Swal.fire({
              icon: "error",
              title: "Error",
              text: data.message,
              confirmButtonColor: "#d33",
            });
          }
        },

        error: function (xhr) {
          let message = "Something went wrong";

          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
          });
        },
      });
    }
  });
}

// Add City Form Submission
document.addEventListener("DOMContentLoaded", function () {
  const addCityForm = document.getElementById("addCityForm");

  $("#addCityForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const stateInput = document.getElementById("stateId");
    const cityInput = document.getElementById("cityName");

    const stateErrorBox = document.getElementById("city-state-error");
    const cityErrorBox = document.getElementById("city-name-error");

    // reset errors
    stateInput.setCustomValidity("");
    cityInput.setCustomValidity("");
    stateErrorBox.textContent = "";
    cityErrorBox.textContent = "";

    // ---------- STATE ----------
    const stateError = validateSelect(stateInput.value, "state");
    if (stateError) {
      stateInput.setCustomValidity(stateError);
      stateErrorBox.textContent = stateError;
      isValid = false;
    }

    // ---------- CITY NAME ----------
    const cityError = validateText(cityInput.value, "city name");
    if (cityError) {
      cityInput.setCustomValidity(cityError);
      cityErrorBox.textContent = cityError;
      isValid = false;
    }

    // show bootstrap validation UI
    this.classList.add("was-validated");

    // ⛔ STOP AJAX IF INVALID
    if (!isValid) {
      return;
    }

    // ✅ VALID → AJAX
    let formData = new FormData(this);

    $.ajax({
      url: "../../../api/city/create_city.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "City Added!",
            text: data.message,
            showConfirmButton: false,
            timer: 1500,
          }).then(() => {
            const modalEl = document.getElementById("addCityModal");
            bootstrap.Modal.getInstance(modalEl)?.hide();
            addCityForm.reset(); // ✅ correct form
            location.reload(); // reload page so table shows new city
          });
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: data.message,
          });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// Edit State Form Submission
function EditCity(id, stateID, name) {
  const idInput = document.getElementById("edit_city_id");
  const stateInput = document.getElementById("edit_state_id");
  const nameInput = document.getElementById("edit_city_name");
  const modalEl = document.getElementById("editCityModal");

  if (!idInput || !nameInput || !stateInput || !modalEl) {
    console.warn("EditCity modal elements not found");
    return;
  }

  idInput.value = id;
  nameInput.value = name;
  stateInput.value = stateID;

  const modal = new bootstrap.Modal(modalEl);
  modal.show();
}
document.addEventListener("DOMContentLoaded", function () {
  const editCityForm = document.getElementById("editCityForm");
  if (!editCityForm) return;

  $("#editCityForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const stateInput = document.getElementById("edit_state_id");
    const cityInput = document.getElementById("edit_city_name");

    const stateErrorBox = document.getElementById("edit-city-state-error");
    const cityErrorBox = document.getElementById("edit-city-name-error");

    // reset errors
    stateInput.setCustomValidity("");
    cityInput.setCustomValidity("");
    stateErrorBox.textContent = "";
    cityErrorBox.textContent = "";

    // ---------- State ----------
    const stateError = validateSelect(stateInput.value, "state");
    if (stateError) {
      stateInput.setCustomValidity(stateError);
      stateErrorBox.textContent = stateError;
      isValid = false;
    }

    // ---------- CITY NAME ----------
    const cityError = validateText(cityInput.value, "City name");
    if (cityError) {
      cityInput.setCustomValidity(cityError);
      cityErrorBox.textContent = cityError;
      isValid = false;
    }

    // show bootstrap validation UI
    this.classList.add("was-validated");

    // ⛔ STOP AJAX IF INVALID
    if (!isValid) return;

    // ✅ VALID → AJAX
    const formData = new FormData(this);

    $.ajax({
      url: "../../../api/city/update_city.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "City Updated!",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          });

          setTimeout(() => {
            const modalEl = document.getElementById("editCityModal");
            bootstrap.Modal.getInstance(modalEl)?.hide();
            editCityForm.reset();
            location.reload();
          }, 1500);
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: data.message,
          });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// Delete City
function DeleteCity(id) {
  if (!id) return;

  Swal.fire({
    title: "Are you sure?",
    text: "This will permanently delete the city and cannot be undone!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "red",
    cancelButtonColor: "#3085d6",
    confirmButtonText: "Yes, delete it!",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../../api/city/delete_city.php",
        type: "POST",
        dataType: "json",
        data: { id: id },

        success: function (data) {
          console.log("Delete city response:", data);

          if (data.status === 200) {
            Swal.fire({
              icon: "success",
              title: "Deleted!",
              text: data.message,
              timer: 1500, // automatically close
              showConfirmButton: false, // no OK button
            });

            setTimeout(() => {
              location.reload();
            }, 1500);
          } else {
            Swal.fire({
              icon: "error",
              title: "Error",
              text: data.message,
              confirmButtonColor: "#d33",
            });
          }
        },

        error: function (xhr) {
          let message = "Something went wrong";

          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
          });
        },
      });
    }
  });
}

// Update Profile
document.addEventListener("DOMContentLoaded", function () {
  const profileForm = document.getElementById("profileForm");
  if (!profileForm) {
    console.warn("profileForm not found");
    return;
  }

  $("#profileForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const nameInput = profileForm.querySelector('input[name="name"]');
    const emailInput = profileForm.querySelector('input[name="email"]');
    const phoneInput = profileForm.querySelector('input[name="phone"]');

    // ---------- RESET VALIDATION ----------
    nameInput.setCustomValidity("");
    emailInput.setCustomValidity("");
    phoneInput.setCustomValidity("");

    // ---------- NAME ----------
    const nameError = validateText(nameInput.value, "name");
    if (nameError) {
      nameInput.setCustomValidity(nameError);
      isValid = false;
    }

    // ---------- EMAIL ----------
    if (!emailInput.value.trim()) {
      emailInput.setCustomValidity("Email is required");
      isValid = false;
    }

    // ---------- PHONE ----------
    const phoneError = validateText(phoneInput.value, "phone");
    if (phoneError) {
      phoneInput.setCustomValidity(phoneError);
      isValid = false;
    }

    // show bootstrap validation UI
    profileForm.classList.add("was-validated");

    // ⛔ STOP AJAX IF INVALID
    if (!isValid) return;

    // ✅ VALID → AJAX
    const formData = new FormData(profileForm);

    $.ajax({
      url: "../../../api/authentication/update_profile.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "Profile Updated!",
            text: data.message,
            showConfirmButton: false,
            timer: 1500,
          }).then(() => {
            const modalEl = document.getElementById("profileModal");
            bootstrap.Modal.getInstance(modalEl)?.hide();
            profileForm.reset();
            location.reload();
          });
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: data.message,
          });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// Get State By Country Id
document.addEventListener("DOMContentLoaded", function () {
  const countrySelect = document.getElementById("add_country_id");
  const stateSelect = document.getElementById("add_state_id");
  const indiaId = document.getElementById("india_id").value;

  if (!countrySelect || !stateSelect || !indiaId) return;

  countrySelect.addEventListener("change", function () {
    const countryId = this.value;

    if (countryId !== indiaId) return;
    // Reset state dropdown
    stateSelect.innerHTML = '<option value="">Select State</option>';

    if (!countryId) return;

    fetch("../../../api/state/get_state_by_id.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ id: countryId }),
    })
      .then(async (response) => {
        const text = await response.text(); // 👈 raw response
        console.log("RAW RESPONSE:", text);

        if (!response.ok) {
          throw new Error("HTTP Error " + response.status);
        }

        return JSON.parse(text); // parse manually
      })
      .then((res) => {
        console.log("PARSED JSON:", res);

        if (res.status === 200 && Array.isArray(res.data)) {
          res.data.forEach((state) => {
            const option = document.createElement("option");
            option.value = state.id;
            option.textContent = state.state_name;
            stateSelect.appendChild(option);
          });
        }
      })
      .catch((error) => {
        console.error("State fetch error:", error.message);
      });
  });
});

// Get City By State Id
document.addEventListener("DOMContentLoaded", function () {
  const stateSelect = document.getElementById("add_state_id");
  const citySelect = document.getElementById("add_city_id");

  if (!stateSelect || !citySelect) return;

  stateSelect.addEventListener("change", function () {
    const stateId = this.value;

    // Reset city dropdown
    citySelect.innerHTML = '<option value="">Select City</option>';

    if (!stateId) return;

    fetch("/carrier_job_admin/api/city/get_city_by_id.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ id: stateId }),
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.status === 200 && Array.isArray(res.data)) {
          res.data.forEach((city) => {
            const option = document.createElement("option");
            option.value = city.id;
            option.textContent = city.city_name;
            citySelect.appendChild(option);
          });
        }
      })
      .catch((error) => {
        console.error("City fetch error:", error);
      });
  });
});

// Add Job Form Submission
document.addEventListener("DOMContentLoaded", function () {
  const addJobForm = document.getElementById("addJobForm");
  if (!addJobForm) return;
  const selectedCountry = document.getElementById("add_country_id");
  const stateDiv = document.getElementById("addState");
  const cityDiv = document.getElementById("addCity");
  const draftJob = document.getElementById("saveDraftBtn");
  const form = document.getElementById("addJobForm");
  draftJob.addEventListener("click", (e) => {
    const jobName = form.job_name;
    const jobType = form.job_type;
    const jobSalary = form.job_salary;
    const jobPosition = form.available_positions;
    const categoryId = form.category_id;
    const countryId = form.country_id;
    const stateId = form.state_id;
    const cityId = form.city_id;
    const expiryDate = form.expiry_date;
    const jobDescription = $("#jobDescription");
    const howToApply = $("#howToApply");
    const jobId = form.job_id;

    const data = {
      draft_id: jobId.value,
      job_name: jobName.value.trim(),
      job_type: jobType.value,
      job_salary: jobSalary.value.trim(),
      job_positions: jobPosition.value,
      description: jobDescription.summernote("code"),
      apply: howToApply.summernote("code"),
      country_id: countryId.value,
      state_id: stateId.value,
      city_id: cityId.value,
      expiry_date: expiryDate.value,
      category_id: categoryId.value,
      is_featured: form.is_featured.checked ? 1 : 0,
    };

    fetch("../../../api/jobs/draft_job.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
      .then((res) => res.json())
      .then((res) => {
        if (res.status === 201 || res.status === 200) {
          console.log("called");
          Swal.fire({
            icon: "success",
            title: "Success",
            text: res.message,
            timer: 1500,
            showConfirmButton: false,
          }).then(() => {
            form.reset();
            // Reset summernote editors
            $(".summernote").summernote("code", "");
            clearErrors();
            // Close modal
            const modal = bootstrap.Modal.getInstance(
              document.getElementById("addJobModal")
            );
            if (modal) modal.hide();
            location.reload();
          });
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: res.message,
            timer: 1500,
            showConfirmButton: false,
          });
        }
      })
      .catch((err) => {
        console.error(err);
        Swal.fire({
          icon: "error",
          title: "Server Error",
          text: "Something went wrong while adding the job.",
          timer: 1500,
          showConfirmButton: false,
        });
      });
  });
  if (!selectedCountry || !stateDiv || !cityDiv) return;
  selectedCountry.addEventListener("change", function () {
    const indiaId = document.getElementById("india_id").value;
    if (this.value === indiaId) {
      stateDiv.style.display = "block";
      cityDiv.style.display = "block";
    } else {
      stateDiv.style.display = "none";
      document.getElementById("add_state_id").value = 0;
      cityDiv.style.display = "none";
      document.getElementById("add_city_id").value = 0;
    }
  });
  addJobForm.addEventListener("submit", function (e) {
    console.log("From submited");

    e.preventDefault();

    const form = this;
    let isValid = true;

    // Get all form inputs
    const jobId = form.job_id;
    const jobName = form.job_name;
    const jobType = form.job_type;
    const jobSalary = form.job_salary;
    const jobPosition = form.available_positions;
    const countryId = form.country_id;
    const categoryId = form.category_id;
    const stateId = form.state_id;
    const cityId = form.city_id;
    const expiryDate = form.expiry_date;
    const jobDescription = $("#jobDescription");
    const howToApply = $("#howToApply");
    const indiaId = document.getElementById("india_id").value;

    // Clear all previous errors
    clearErrors();

    // Validation rules
    const validations = [
      {
        field: jobName,
        condition: !jobName.value.trim(),
        message: "Job name is required",
      },
      {
        field: jobType,
        condition: !jobType.value,
        message: "Please select a job type",
      },
      {
        field: jobSalary,
        condition: !jobSalary.value.trim(),
        message: "Job salary is required",
      },
      {
        field: jobPosition,
        condition: !jobPosition.value || jobPosition.value < 1,
        message: "Available positions must be at least 1",
      },
      {
        field: categoryId,
        condition: !categoryId.value,
        message: "Please select a category",
      },
      {
        field: countryId,
        condition: !countryId.value,
        message: "Please select a country",
      },

      {
        field: stateId,
        condition: countryId.value === indiaId && !stateId.value,
        message: "Please select a state",
      },
      {
        field: cityId,
        condition: countryId.value === indiaId && !cityId.value,
        message: "Please select a city",
      },
    ];

    // Check all validations
    validations.forEach((validation) => {
      if (validation.condition) {
        showError(validation.field, validation.message);
        isValid = false;
      }
    });

    // Validate Job Description (Summernote)
    const descriptionValue = jobDescription.summernote("code");
    const descriptionText = $("<div>").html(descriptionValue).text().trim();
    if (!descriptionText || descriptionText.length < 10) {
      showSummernoteError(
        jobDescription,
        "Job description must be at least 10 characters"
      );
      isValid = false;
    }

    // Validate How to Apply (Summernote)
    const applyValue = howToApply.summernote("code");
    const applyText = $("<div>").html(applyValue).text().trim();
    if (!applyText || applyText.length < 10) {
      showSummernoteError(
        howToApply,
        "How to apply must be at least 10 characters"
      );
      isValid = false;
    }

    // Validate expiry date is in future
    if (expiryDate.value) {
      const selectedDate = new Date(expiryDate.value);
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      if (selectedDate < today) {
        showError(expiryDate, "Expiry date must be in the future");
        isValid = false;
      }
    }

    if (!isValid) {
      return;
    }

    // Prepare data for submission
    const data = {
      job_id: jobId.value,
      job_name: jobName.value.trim(),
      job_type: jobType.value,
      job_salary: jobSalary.value.trim(),
      job_positions: jobPosition.value,
      description: jobDescription.summernote("code"),
      apply: howToApply.summernote("code"),
      category_id: categoryId.value,
      country_id: countryId.value,
      state_id: stateId.value,
      city_id: cityId.value,
      expiry_date: expiryDate.value,
      is_featured: form.is_featured.checked ? 1 : 0,
    };

    // Submit the form
    fetch("../../../api/jobs/create_job.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    })
      .then((res) => res.json())
      .then((res) => {
        if (res.status === 201 || res.status === 200) {
          Swal.fire({
            icon: "success",
            title: "Success",
            text: "Job added successfully",
            timer: 1500,
            showConfirmButton: false,
          }).then(() => {
            form.reset();
            // Reset summernote editors
            $(".summernote").summernote("code", "");
            clearErrors();
            // Close modal
            const modal = bootstrap.Modal.getInstance(
              document.getElementById("addJobModal")
            );
            if (modal) modal.hide();
            location.reload();
          });
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: res.message,
            timer: 1500,
            showConfirmButton: false,
          });
        }
      })
      .catch((err) => {
        console.error(err);
        Swal.fire({
          icon: "error",
          title: "Server Error",
          text: "Something went wrong while adding the job.",
          timer: 1500,
          showConfirmButton: false,
        });
      });
  });

  // Helper function to show error
  function showError(field, message) {
    field.classList.add("is-invalid");
    const errorDiv = field.parentElement.querySelector(".invalid-feedback");
    if (errorDiv) {
      errorDiv.textContent = message;
      errorDiv.style.display = "block";
    }
  }

  // Helper function to show summernote error
  function showSummernoteError(summernoteField, message) {
    const fieldId = summernoteField.attr("id");
    const container = summernoteField.closest(".mb-3");
    const noteEditor = container.find(".note-editor");

    // Add invalid styling to note-editor
    if (noteEditor.length) {
      noteEditor.addClass("is-invalid");
      noteEditor.css("border", "1px solid #dc3545");
    }

    // Find or create error div
    let errorDiv = container.find(".invalid-feedback");
    if (errorDiv.length) {
      errorDiv.text(message);
      errorDiv.css("display", "block");
    }
  }

  // Helper function to clear all errors
  function clearErrors() {
    const invalidFields = addJobForm.querySelectorAll(".is-invalid");
    invalidFields.forEach((field) => {
      field.classList.remove("is-invalid");
    });

    const errorDivs = addJobForm.querySelectorAll(".invalid-feedback");
    errorDivs.forEach((div) => {
      div.textContent = "";
      div.style.display = "none";
    });

    // Clear summernote errors
    $(".note-editor").removeClass("is-invalid").css("border", "");
  }

  // Real-time validation - clear errors on input
  addJobForm.querySelectorAll("input, select").forEach((field) => {
    field.addEventListener("input", function () {
      if (this.classList.contains("is-invalid")) {
        this.classList.remove("is-invalid");
        const errorDiv = this.parentElement.querySelector(".invalid-feedback");
        if (errorDiv) {
          errorDiv.textContent = "";
          errorDiv.style.display = "none";
        }
      }
    });

    field.addEventListener("change", function () {
      if (this.classList.contains("is-invalid")) {
        this.classList.remove("is-invalid");
        const errorDiv = this.parentElement.querySelector(".invalid-feedback");
        if (errorDiv) {
          errorDiv.textContent = "";
          errorDiv.style.display = "none";
        }
      }
    });
  });

  // Real-time validation for Summernote
  $("#jobDescription, #howToApply").on("summernote.change", function () {
    const container = $(this).closest(".mb-3");
    const noteEditor = container.find(".note-editor");
    const errorDiv = container.find(".invalid-feedback");

    if (noteEditor.hasClass("is-invalid")) {
      noteEditor.removeClass("is-invalid");
      noteEditor.css("border", "");
      errorDiv.text("");
      errorDiv.hide();
    }
  });

  // Reset form when modal is closed
  $("#addJobModal").on("hidden.bs.modal", function () {
    addJobForm.reset();
    $(".summernote").summernote("code", "");
    clearErrors();
  });
});

// Edit Job Form Submission
function EditJob(
  id,
  indiaId,
  name,
  type,
  description,
  salary,
  positions,
  apply,
  is_featured,
  country_id,
  state_id,
  city_id,
  category_id,
  expiry_date
) {
  const idInput = document.getElementById("edit_job_id");
  const nameInput = document.getElementById("edit_job_name");
  const typeInput = document.getElementById("edit_job_type");
  const salaryInput = document.getElementById("edit_job_salary");
  const positionsInput = document.getElementById("edit_available_positions");
  const isFeaturedInput = document.getElementById("edit_is_featured");
  const countryInput = document.getElementById("edit_country_id");
  const categoryInput = document.getElementById("edit_category_id");
  const stateInput = document.getElementById("edit_state_id");
  const cityInput = document.getElementById("edit_city_id");

  const expiryInput = document.getElementById("edit_expiry_date");
  const modalEl = document.getElementById("editJobModal");

  if (!idInput || !nameInput || !typeInput || !modalEl) return;

  if (country_id !== indiaId) {
    document.getElementById("edit_state").style.display = "none";
    document.getElementById("edit_city").style.display = "none";
  }
  idInput.value = id;
  nameInput.value = name;
  typeInput.value = type;
  salaryInput.value = salary;
  positionsInput.value = positions;
  isFeaturedInput.checked = is_featured == 1;
  countryInput.value = country_id;
  categoryInput.value = category_id;
  stateInput.value = state_id;
  cityInput.value = city_id;

  // Set Summernote fields
  $("#edit_job_description").summernote("code", description);
  $("#edit_how_to_apply").summernote("code", apply);

  // Set Expiry date
  if (expiry_date) {
    const dateStr =
      typeof expiry_date === "string" ? expiry_date : String(expiry_date);

    expiryInput.value = dateStr.substring(0, 10);
  }

  // Clear any previous validation errors
  const form = document.getElementById("editJobForm");
  form.classList.remove("was-validated");
  clearEditJobErrors();

  const modal = new bootstrap.Modal(modalEl);
  modal.show();
}
function openDraftFromButton(btn) {
  const modalEl = document.getElementById("addJobModal");
  const modal = new bootstrap.Modal(modalEl);

  data = JSON.parse(btn.dataset.job);

  if (data) {
    data.indiaId = btn.dataset.indiaId;
    openDraftJob(
      data.id,
      data.indiaId,
      data.job_name,
      data.job_type,
      data.job_description,
      data.job_salary,
      data.job_available_positions,
      data.apply,
      data.is_featured,
      data.country_id,
      data.state_id,
      data.city_id,
      data.category_id, // ✅ ADD THIS
      data.expiry_date
    );
  } else {
    // No data -> open empty modal
    const form = document.getElementById("addJobForm");
    form.reset();
    form.classList.remove("was-validated");

    modal.show();
  }
}
function openDraftJob(
  id,
  indiaId,
  name,
  type,
  description,
  salary,
  positions,
  apply,
  is_featured,
  country_id,
  state_id,
  city_id,
  category_id,
  expiry_date
) {
  const idInput = document.getElementById("job_id");
  const nameInput = document.getElementById("job_name");
  const typeInput = document.getElementById("jobType");
  const salaryInput = document.getElementById("jobSalary");
  const positionsInput = document.getElementById("jobPosition");
  const isFeaturedInput = document.getElementById("is_featured");
  const countryInput = document.getElementById("add_country_id");
  const stateInput = document.getElementById("add_state_id");
  const cityInput = document.getElementById("add_city_id");
  const categoryInput = document.getElementById("add_category_id");
  const expiryInput = document.getElementById("expiredId");
  const modalEl = document.getElementById("addJobModal");

  if (!idInput || !modalEl) return;

  console.log(indiaId);
  console.log(country_id);
  const stateDiv = document.getElementById("addState");
  const cityDiv = document.getElementById("addCity");
  const show = country_id == indiaId;
  if (show) {
    stateDiv.style.display = "block";
    cityDiv.style.display = "block";
  } else {
    stateDiv.style.display = "none";
    cityDiv.style.display = "none";
  }

  idInput.value = id;
  nameInput.value = name;
  typeInput.value = type;
  salaryInput.value = salary;
  positionsInput.value = positions;
  isFeaturedInput.checked = is_featured == 1;
  countryInput.value = country_id;

  stateInput.value = state_id;
  cityInput.value = city_id;

  categoryInput.value = category_id;
  // Set Summernote fields
  $("#jobDescription").summernote("code", description);
  $("#howToApply").summernote("code", apply);

  // Set Expiry date
  if (expiry_date) {
    const dateStr =
      typeof expiry_date === "string" ? expiry_date : String(expiry_date);

    expiryInput.value = dateStr.substring(0, 10);
  }

  // Clear any previous validation errors
  const form = document.getElementById("addJobForm");
  form.classList.remove("was-validated");

  const modal = new bootstrap.Modal(modalEl);
  modal.show();
}
function toggleDraftStatus(id) {
  const data = {
    draft_id: id, // we only need draft_id to toggle
  };

  fetch("../../../api/jobs/draft_job.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data),
  })
    .then((res) => res.json())
    .then((res) => {
      if (res.status === 200) {
        Swal.fire({
          icon: "success",
          title: "Success",
          text: res.message,
          timer: 1500,
          showConfirmButton: false,
        }).then(() => {
          location.reload(); // refresh list after toggle
        });
      } else {
        Swal.fire({
          icon: "error",
          title: "Error",
          text: res.message,
          timer: 1500,
          showConfirmButton: false,
        });
      }
    })
    .catch((err) => {
      console.error(err);
      Swal.fire({
        icon: "error",
        title: "Server Error",
        text: "Something went wrong while updating job status.",
        timer: 1500,
        showConfirmButton: false,
      });
    });
}
document.addEventListener("DOMContentLoaded", function () {
  const editJobForm = document.getElementById("editJobForm");
  if (!editJobForm) return;

  const selectedCountry = document.getElementById("edit_country_id");
  const stateDiv = document.getElementById("edit_state");
  const cityDiv = document.getElementById("edit_city");
  selectedCountry.addEventListener("change", function () {
    const indiaId = document.getElementById("india_id1").value;
    if (this.value === indiaId) {
      stateDiv.style.display = "block";
      cityDiv.style.display = "block";
    } else {
      stateDiv.style.display = "none";
      document.getElementById("edit_state_id").value = 0;
      cityDiv.style.display = "none";
      document.getElementById("edit_city_id").value = 0;
    }
  });
  editJobForm.addEventListener("submit", function (e) {
    e.preventDefault();

    const form = this;
    let isValid = true;

    // Get all form inputs
    const jobName = form.job_name;
    const jobType = form.job_type;
    const jobSalary = form.job_salary;
    const jobPosition = form.available_positions;
    const categoryId = form.category_id;
    const countryId = form.country_id;
    const stateId = form.state_id;
    const cityId = form.city_id;
    const expiryDate = form.expiry_date;
    const jobDescription = $("#edit_job_description");
    const howToApply = $("#edit_how_to_apply");
    const indiaId = document.getElementById("india_id1").value;

    // Clear all previous errors
    clearEditJobErrors();

    // Validation rules
    const validations = [
      {
        field: jobName,
        condition: !jobName.value.trim(),
        message: "Job name is required",
      },
      {
        field: jobType,
        condition: !jobType.value,
        message: "Please select a job type",
      },
      {
        field: jobSalary,
        condition: !jobSalary.value.trim(),
        message: "Job salary is required",
      },
      {
        field: jobPosition,
        condition: !jobPosition.value || jobPosition.value < 1,
        message: "Available positions must be at least 1",
      },
      {
        field: categoryId,
        condition: !categoryId.value,
        message: "Please select a category",
      },
      {
        field: countryId,
        condition: !countryId.value,
        message: "Please select a country",
      },
      {
        field: stateId,
        condition: countryId.value === indiaId && !stateId.value,
        message: "Please select a state",
      },
      {
        field: cityId,
        condition: countryId.value === indiaId && !cityId.value,
        message: "Please select a city",
      },
      {
        field: expiryDate,
        condition: !expiryDate.value,
        message: "Expiry date is required",
      },
    ];

    // Check all validations
    validations.forEach((validation) => {
      if (validation.condition) {
        showEditJobError(validation.field, validation.message);
        isValid = false;
      }
    });

    // Validate Job Description (Summernote)
    const descriptionValue = jobDescription.summernote("code");
    const descriptionText = $("<div>").html(descriptionValue).text().trim();
    if (!descriptionText || descriptionText.length < 10) {
      showEditJobSummernoteError(
        jobDescription,
        "Job description must be at least 10 characters"
      );
      isValid = false;
    }

    // Validate How to Apply (Summernote)
    const applyValue = howToApply.summernote("code");
    const applyText = $("<div>").html(applyValue).text().trim();
    if (!applyText || applyText.length < 10) {
      showEditJobSummernoteError(
        howToApply,
        "How to apply must be at least 10 characters"
      );
      isValid = false;
    }

    // Validate expiry date is in future
    if (expiryDate.value) {
      const selectedDate = new Date(expiryDate.value);
      const today = new Date();
      today.setHours(0, 0, 0, 0);

      if (selectedDate < today) {
        showEditJobError(expiryDate, "Expiry date must be in the future");
        isValid = false;
      }
    }

    if (!isValid) {
      return;
    }

    // Prepare FormData for submission
    const formData = new FormData(this);

    $.ajax({
      url: "../../../api/jobs/update_job.php",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "Job Updated!",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          }).then(() => {
            const modalEl = document.getElementById("editJobModal");
            bootstrap.Modal.getInstance(modalEl)?.hide();
            editJobForm.reset();
            $("#edit_job_description").summernote("code", "");
            $("#edit_how_to_apply").summernote("code", "");
            clearEditJobErrors();
            location.reload();
          });
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: data.message,
          });
        }
      },

      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });

  // Helper function to show error
  function showEditJobError(field, message) {
    field.classList.add("is-invalid");
    const errorDiv = field.parentElement.querySelector(".invalid-feedback");
    if (errorDiv) {
      errorDiv.textContent = message;
      errorDiv.style.display = "block";
    }
  }

  // Helper function to show summernote error
  function showEditJobSummernoteError(summernoteField, message) {
    const container = summernoteField.closest(".mb-3");
    const noteEditor = container.find(".note-editor");

    // Add invalid styling to note-editor
    if (noteEditor.length) {
      noteEditor.addClass("is-invalid");
      noteEditor.css("border", "1px solid #dc3545");
    }

    // Find or create error div
    let errorDiv = container.find(".invalid-feedback");
    if (errorDiv.length) {
      errorDiv.text(message);
      errorDiv.css("display", "block");
    }
  }

  // Helper function to clear all errors
  function clearEditJobErrors() {
    const invalidFields = editJobForm.querySelectorAll(".is-invalid");
    invalidFields.forEach((field) => {
      field.classList.remove("is-invalid");
    });

    const errorDivs = editJobForm.querySelectorAll(".invalid-feedback");
    errorDivs.forEach((div) => {
      div.textContent = "";
      div.style.display = "none";
    });

    // Clear summernote errors
    $("#editJobForm .note-editor").removeClass("is-invalid").css("border", "");
  }

  // Real-time validation - clear errors on input
  editJobForm.querySelectorAll("input, select").forEach((field) => {
    field.addEventListener("input", function () {
      if (this.classList.contains("is-invalid")) {
        this.classList.remove("is-invalid");
        const errorDiv = this.parentElement.querySelector(".invalid-feedback");
        if (errorDiv) {
          errorDiv.textContent = "";
          errorDiv.style.display = "none";
        }
      }
    });

    field.addEventListener("change", function () {
      if (this.classList.contains("is-invalid")) {
        this.classList.remove("is-invalid");
        const errorDiv = this.parentElement.querySelector(".invalid-feedback");
        if (errorDiv) {
          errorDiv.textContent = "";
          errorDiv.style.display = "none";
        }
      }
    });
  });

  // Real-time validation for Summernote
  $("#edit_job_description, #edit_how_to_apply").on(
    "summernote.change",
    function () {
      const container = $(this).closest(".mb-3");
      const noteEditor = container.find(".note-editor");
      const errorDiv = container.find(".invalid-feedback");

      if (noteEditor.hasClass("is-invalid")) {
        noteEditor.removeClass("is-invalid");
        noteEditor.css("border", "");
        errorDiv.text("");
        errorDiv.hide();
      }
    }
  );

  // Reset form when modal is closed
  $("#editJobModal").on("hidden.bs.modal", function () {
    editJobForm.reset();
    $("#edit_job_description").summernote("code", "");
    $("#edit_how_to_apply").summernote("code", "");
    clearEditJobErrors();
  });
});

// Make clearEditJobErrors globally accessible for EditJob function
function clearEditJobErrors() {
  const editJobForm = document.getElementById("editJobForm");
  if (!editJobForm) return;

  const invalidFields = editJobForm.querySelectorAll(".is-invalid");
  invalidFields.forEach((field) => {
    field.classList.remove("is-invalid");
  });

  const errorDivs = editJobForm.querySelectorAll(".invalid-feedback");
  errorDivs.forEach((div) => {
    div.textContent = "";
    div.style.display = "none";
  });

  // Clear summernote errors
  $("#editJobForm .note-editor").removeClass("is-invalid").css("border", "");
}

// Delete Job
function DeleteJob(id) {
  if (!id) return;

  Swal.fire({
    title: "Are you sure?",
    text: "This will permanently delete the Job and cannot be undone!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "red",
    cancelButtonColor: "#3085d6",
    confirmButtonText: "Yes, delete it!",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../../api/jobs/delete_job.php",
        type: "POST",
        dataType: "json",
        contentType: "application/json", // important!
        data: JSON.stringify({ id: id }), // send JSON

        success: function (data) {
          if (data.status === 200) {
            Swal.fire({
              icon: "success",
              title: "Deleted!",
              text: data.message,
              timer: 1500,
              showConfirmButton: false,
            });
            setTimeout(() => location.reload(), 1500);
          } else {
            Swal.fire({
              icon: "error",
              title: "Error",
              text: data.message,
            });
          }
        },

        error: function (xhr) {
          let message = "Something went wrong";

          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
          });
        },
      });
    }
  });
}

// Get State By Country Id
document.addEventListener("DOMContentLoaded", function () {
  const countrySelect = document.getElementById("edit_country_id");
  const stateSelect = document.getElementById("edit_state_id");

  if (!countrySelect || !stateSelect) return;

  countrySelect.addEventListener("change", function () {
    const countryId = this.value;

    // Reset state dropdown
    stateSelect.innerHTML = '<option value="">Select State</option>';

    if (!countryId) return;

    fetch("../../../api/state/get_state_by_id.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ id: countryId }),
    })
      .then(async (response) => {
        const text = await response.text(); // 👈 raw response
        console.log("RAW RESPONSE:", text);

        if (!response.ok) {
          throw new Error("HTTP Error " + response.status);
        }

        return JSON.parse(text); // parse manually
      })
      .then((res) => {
        console.log("PARSED JSON:", res);

        if (res.status === 200 && Array.isArray(res.data)) {
          res.data.forEach((state) => {
            const option = document.createElement("option");
            option.value = state.id;
            option.textContent = state.state_name;
            stateSelect.appendChild(option);
          });
        }
      })
      .catch((error) => {
        console.error("State fetch error:", error.message);
      });
  });
});

// Get City By State Id
document.addEventListener("DOMContentLoaded", function () {
  const stateSelect = document.getElementById("edit_state_id");
  const citySelect = document.getElementById("edit_city_id");

  if (!stateSelect || !citySelect) return;

  stateSelect.addEventListener("change", function () {
    const stateId = this.value;

    // Reset city dropdown
    citySelect.innerHTML = '<option value="">Select City</option>';

    if (!stateId) return;

    fetch("../../../api/city/get_city_by_id.php", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ id: stateId }),
    })
      .then((response) => response.json())
      .then((res) => {
        if (res.status === 200 && Array.isArray(res.data)) {
          res.data.forEach((city) => {
            const option = document.createElement("option");
            option.value = city.id;
            option.textContent = city.city_name;
            citySelect.appendChild(option);
          });
        }
      })
      .catch((error) => {
        console.error("City fetch error:", error);
      });
  });
});

document.addEventListener("DOMContentLoaded", function () {
  const addPageForm = document.getElementById("addPageForm");
  if (!addPageForm) return;

  // Initialize Summernote
  $("#policyDescription").summernote({
    height: 150,
    toolbar: [
      ["style", ["bold", "italic", "underline"]],
      ["para", ["ul", "ol"]],
      ["insert", ["link"]],
    ],
  });

  $("#addPageForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const policyTypeInput = document.getElementById("policyType");
    const policyTypeErrorBox = document.getElementById("policy-type-error");
    const descriptionErrorBox = document.getElementById(
      "policy-description-error"
    );

    // Reset errors
    policyTypeInput.classList.remove("is-invalid");
    policyTypeErrorBox.textContent = "";
    $(".note-editor").removeClass("border border-danger");
    descriptionErrorBox.textContent = "";

    // Validate policy type
    if (!policyTypeInput.value) {
      policyTypeInput.classList.add("is-invalid");
      policyTypeErrorBox.textContent = "Please select a policy type";
      isValid = false;
    }

    // Validate Summernote description
    const descriptionHtml = $("#policyDescription").summernote("code");
    const descriptionText = $("<div>").html(descriptionHtml).text().trim();

    if (!descriptionText || descriptionText.length < 20) {
      $(".note-editor").addClass("border border-danger");
      descriptionErrorBox.textContent =
        "Description must be at least 20 characters";
      isValid = false;
    }

    if (!isValid) return;

    // Send JSON to API
    $.ajax({
      url: "../../../api/page/create_page.php",
      type: "POST",
      contentType: "application/json",
      dataType: "json",
      data: JSON.stringify({
        policy_type: policyTypeInput.value,
        description: descriptionHtml,
      }),
      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "Policy Added!",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          }).then(() => {
            bootstrap.Modal.getInstance(
              document.getElementById("addPageModal")
            )?.hide();
            addPageForm.reset();
            $("#policyDescription").summernote("reset");
            location.reload();
          });
        } else {
          Swal.fire("Error", data.message, "error");
        }
      },
      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});

// Edit Page Form Submission
function EditPolicy(id, policyType, description) {
  const idInput = document.getElementById("edit_policy_id");
  const typeInput = document.getElementById("editPolicyType");
  const modalEl = document.getElementById("editPageModal");

  idInput.value = id;
  typeInput.value = policyType;

  // Set Summernote content
  $("#editPolicyDescription").summernote("code", description);

  // Reset validation when opening modal
  const form = document.getElementById("editPageForm");
  form.classList.remove("was-validated");

  const policyTypeErrorBox = document.getElementById("edit-policy-type-error");
  const descriptionErrorBox = document.getElementById(
    "edit-policy-description-error"
  );
  policyTypeErrorBox.textContent = "";
  descriptionErrorBox.textContent = "";
  typeInput.classList.remove("is-invalid");

  const modal = new bootstrap.Modal(modalEl);
  modal.show();
}

document.addEventListener("DOMContentLoaded", function () {
  const editPageForm = document.getElementById("editPageForm");
  if (!editPageForm) return;

  $("#editPageForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const policyTypeInput = document.getElementById("editPolicyType");
    const descriptionInput = document.getElementById("editPolicyDescription");
    const idInput = document.getElementById("edit_policy_id");

    const policyTypeErrorBox = document.getElementById(
      "edit-policy-type-error"
    );
    const descriptionErrorBox = document.getElementById(
      "edit-policy-description-error"
    );

    // Reset errors
    policyTypeInput.classList.remove("is-invalid");
    descriptionInput.classList.remove("is-invalid");
    policyTypeErrorBox.textContent = "";
    descriptionErrorBox.textContent = "";

    // Validate Policy Type
    if (!policyTypeInput.value) {
      const error = "Please select a policy type";
      policyTypeInput.classList.add("is-invalid");
      policyTypeErrorBox.textContent = error;
      policyTypeErrorBox.style.display = "block";
      isValid = false;
    }

    // Validate Description
    const descriptionValue = descriptionInput.value.trim();
    if (!descriptionValue || descriptionValue.length < 20) {
      const error = "Description must be at least 20 characters";
      descriptionInput.classList.add("is-invalid");
      descriptionErrorBox.textContent = error;
      descriptionErrorBox.style.display = "block";
      isValid = false;
    }

    if (!isValid) {
      return;
    }

    // Prepare JSON payload
    const payload = {
      id: idInput.value,
      policy_type: policyTypeInput.value,
      description: descriptionValue,
    };

    $.ajax({
      url: "../../../api/page/update_page.php",
      type: "POST",
      data: JSON.stringify(payload),
      contentType: "application/json",
      dataType: "json",
      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "Policy Updated!",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          }).then(() => {
            const modalEl = document.getElementById("editPageModal");
            bootstrap.Modal.getInstance(modalEl)?.hide();
            editPageForm.reset();
            policyTypeInput.classList.remove("is-invalid");
            descriptionInput.classList.remove("is-invalid");
            location.reload();
          });
        } else {
          Swal.fire("Error", data.message, "error");
        }
      },
      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });

  // Real-time validation for policy type
  $("#editPolicyType").on("change", function () {
    const errorBox = document.getElementById("edit-policy-type-error");
    if (this.value) {
      this.classList.remove("is-invalid");
      errorBox.textContent = "";
      errorBox.style.display = "none";
    }
  });

  // Real-time validation for description
  $("#editPolicyDescription").on("summernote.change", function () {
    const errorBox = document.getElementById("edit-policy-description-error");
    const value = $(this).summernote("code").trim();
    if (value && value.length >= 20) {
      this.classList.remove("is-invalid");
      errorBox.textContent = "";
      errorBox.style.display = "none";
    }
  });
});

// Delete Page
function DeletePolicy(id) {
  if (!id) return;

  Swal.fire({
    title: "Are you sure?",
    text: "This will permanently delete the page and cannot be undone!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "red",
    cancelButtonColor: "#3085d6",
    confirmButtonText: "Yes, delete it!",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../../api/page/delete_page.php",
        type: "POST",
        dataType: "json",
        contentType: "application/json", // important!
        data: JSON.stringify({ id: id }), // send JSON

        success: function (data) {
          if (data.status === 200) {
            Swal.fire({
              icon: "success",
              title: "Deleted!",
              text: data.message,
              timer: 1500,
              showConfirmButton: false,
            });
            setTimeout(() => location.reload(), 1500);
          } else {
            Swal.fire({
              icon: "error",
              title: "Error",
              text: data.message,
            });
          }
        },

        error: function (xhr) {
          let message = "Something went wrong";

          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
          });
        },
      });
    }
  });
}
function blockUser(userId) {
  if (!userId) return;

  Swal.fire({
    title: "Block user?",
    text: "User will not be able to login",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes, block",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../../api/users/block_user.php",
        type: "POST",
        data: { id: userId },
        dataType: "json",
        success: function (res) {
          if (res.status === 200) {
            Swal.fire({
              icon: "success",
              title: "Blocked!",
              text: res.message,
              timer: 1500,
              showConfirmButton: false,
            });
            setTimeout(() => location.reload(), 1500);
          } else {
            Swal.fire({
              icon: "error",
              title: "Error",
              text: data.message,
            });
          }
        },
        error: function (xhr) {
          let message = "Something went wrong";

          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
          });
        },
      });
    }
  });
}

function unblockUser(userId) {
  if (!userId) return;

  Swal.fire({
    title: "Unblock user?",
    text: "User will be able to login",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes, unblock",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../../api/users/unblock_user.php",
        type: "POST",
        data: { id: userId },
        dataType: "json",
        success: function (res) {
          if (res.status === 200) {
            Swal.fire({
              icon: "success",
              title: "Unblocked!",
              text: res.message,
              timer: 1500,
              showConfirmButton: false,
            });
            setTimeout(() => location.reload(), 1500);
          } else {
            Swal.fire({
              icon: "error",
              title: "Error",
              text: res.message,
            });
          }
        },
        error: function (xhr) {
          let message = "Something went wrong";

          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
          });
        },
      });
    }
  });
}
function deleteUser(userId) {
  if (!userId) return;

  Swal.fire({
    title: "Delete user?",
    text: "This action cannot be undone!",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes, delete",
  }).then((result) => {
    if (result.isConfirmed) {
      $.ajax({
        url: "../../../api/users/delete_user.php",
        type: "POST",
        data: { id: userId },
        dataType: "json",
        success: function (res) {
          if (res.status === 200) {
            Swal.fire("Deleted!", res.message, "success").then(() =>
              location.reload()
            );
          } else {
            Swal.fire("Error", res.message, "error");
          }
        },
        error: function (xhr) {
          let message = "Something went wrong";

          if (xhr.responseJSON && xhr.responseJSON.message) {
            message = xhr.responseJSON.message;
          }

          Swal.fire({
            icon: "error",
            title: "Error",
            text: message,
          });
        },
      });
    }
  });
}

//Change Password Validation
document.addEventListener("DOMContentLoaded", function () {
  const changePasswordForm = document.getElementById("changePasswordForm");
  if (!changePasswordForm) return;

  $("#changePasswordForm").on("submit", function (e) {
    e.preventDefault();

    let isValid = true;

    const adminId = document.getElementById("admin_id").value;
    const newPasswordInput = document.getElementById("new_password");
    const confirmPasswordInput = document.getElementById("confirm_password");

    const newPasswordError = document.getElementById("new-password-error");
    const confirmPasswordError = document.getElementById(
      "confirm-password-error"
    );

    // Reset errors
    newPasswordInput.classList.remove("is-invalid");
    confirmPasswordInput.classList.remove("is-invalid");
    newPasswordError.textContent = "";
    confirmPasswordError.textContent = "";

    const newPassword = newPasswordInput.value.trim();
    const confirmPassword = confirmPasswordInput.value.trim();

    // Validate new password
    if (!newPassword || newPassword.length < 6) {
      newPasswordInput.classList.add("is-invalid");
      newPasswordError.textContent = "Password must be at least 6 characters";
      isValid = false;
    }

    // Validate confirm password
    if (newPassword !== confirmPassword) {
      confirmPasswordInput.classList.add("is-invalid");
      confirmPasswordError.textContent =
        "Confirm Passwords do not match with New Password ";
      isValid = false;
    }

    if (!isValid) return;

    // Send JSON to API
    $.ajax({
      url: "../../../api/authentication/change_password.php",
      type: "POST",
      contentType: "application/json",
      dataType: "json",
      data: JSON.stringify({
        uid: adminId,
        new_password: newPassword,
        confirm_password: confirmPassword,
      }),
      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "Password Updated!",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          }).then(() => {
            bootstrap.Modal.getInstance(
              document.getElementById("changePasswordModal")
            )?.hide();

            changePasswordForm.reset();
          });
        } else {
          Swal.fire("Error", data.message, "error");
        }
      },
      error: function (xhr) {
        let message = "Something went wrong";

        if (xhr.responseJSON && xhr.responseJSON.message) {
          message = xhr.responseJSON.message;
        }

        Swal.fire({
          icon: "error",
          title: "Error",
          text: message,
        });
      },
    });
  });
});
$(document).ready(function () {
  $(".select2").select2({
    dropdownParent: $("#manageUserModel"),
    width: "100%",
    placeholder: "Select Permissions",
    closeOnSelect: false,
  });
});

document.addEventListener("DOMContentLoaded", function () {
  console.log("hello");

  const modal = document.getElementById("manageUserModel");
  const hiddenUserId = document.getElementById("manage_user_id");
  const form = document.getElementById("manageUserForm");

  const statusSelect = document.getElementById("user_status");

  const permissionSelect = document.getElementById("user_permissions");
  const permissionWrapper = document.getElementById("permission_selector");
  console.log("statusSelect:", statusSelect);
  console.log("permissionWrapper:", permissionWrapper);

  const statusError = document.getElementById("user-status-error");
  const permissionError = document.getElementById("user-permission-error");

  // SET USER ID
  modal.addEventListener("show.bs.modal", function (e) {
    hiddenUserId.value = e.relatedTarget.getAttribute("data-user-id");
  });

  // TOGGLE PERMISSIONS
  function togglePermissions() {
    console.log("Toggled Permission", statusSelect.value);

    if (statusSelect.value === "reject") {
      // Hide permission block
      permissionWrapper.classList.add("d-none");

      // Reset select2 value
      $(permissionSelect).val(null).trigger("change");

      permissionError.textContent = "";
      $("#permission_selector .select2-selection").removeClass("is-invalid");
    } else if (statusSelect.value === "accept") {
      // Show permission block
      permissionWrapper.classList.remove("d-none");
    }
  }

  statusSelect.addEventListener("change", togglePermissions);
  togglePermissions(); // initial call

  // SUBMIT
  form.addEventListener("submit", function (e) {
    e.preventDefault();

    let valid = true;

    // reset errors
    statusError.textContent = "";
    permissionError.textContent = "";

    statusSelect.classList.remove("is-invalid");
    $("#permission_selector .select2-selection").removeClass("is-invalid");

    // STATUS VALIDATION
    if (!statusSelect.value) {
      statusError.textContent = "Select status";
      statusSelect.classList.add("is-invalid");
      valid = false;
    }

    // PERMISSION VALIDATION (ONLY WHEN ACCEPT)
    if (statusSelect.value === "accept") {
      const perms = $(permissionSelect).val();

      if (!perms || perms.length < 1) {
        permissionError.textContent = "Select at least one permission";
        permissionError.style.display = "block";

        $("#permission_selector .select2-selection").addClass("is-invalid");
        valid = false;
      }
    }

    if (!valid) return;

    const payload = {
      id: hiddenUserId.value,
      user_status: statusSelect.value,
      user_permissions: $(permissionSelect).val() || [],
    };

    $.ajax({
      url: "../../../api/request/manage_request.php",
      type: "POST",
      data: JSON.stringify(payload),
      contentType: "application/json",
      dataType: "json",

      success: function (data) {
        if (data.status === 200) {
          Swal.fire({
            icon: "success",
            title: "Admin Updated!",
            text: data.message,
            timer: 1500,
            showConfirmButton: false,
          });

          setTimeout(() => location.reload(), 1500);
        } else {
          Swal.fire({
            icon: "error",
            title: "Error",
            text: data.message,
          });
        }
      },

      error: function (xhr, status, error) {
        console.error("AJAX ERROR:");
        console.error("Status:", status);
        console.error("Error:", error);
        console.error("Response:", xhr.responseText);

        Swal.fire(
          "Error",
          "Server error occurred. Check console for details.",
          "error"
        );
      },
    });
  });
});
