/**
 * EnglishSpeak — Student Forgot Password
 * Handles form submission via fetch.
 */

document.addEventListener("DOMContentLoaded", () => {
  const form = document.getElementById("forgot-form");
  const errorBox = document.getElementById("forgot-error");
  const successBox = document.getElementById("forgot-success");
  const submitBtn = document.getElementById("forgot-submit");

  // Handle form submission
  if (form) {
    form.addEventListener("submit", async (e) => {
      e.preventDefault();

      // Hide previous messages
      if (errorBox) {
        errorBox.style.display = "none";
        errorBox.textContent = "";
      }
      if (successBox) {
        successBox.style.display = "none";
        successBox.textContent = "";
      }

      // Disable button
      if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.textContent = "Đang gửi...";
      }

      const formData = new FormData(form);

      try {
        const response = await fetch("EnglishSpeak/api/student-forgot-password.php", {
          method: "POST",
          body: formData,
        });

        const data = await response.json();

        if (data.success) {
          if (successBox) {
            successBox.textContent = data.message || "Hướng dẫn đặt lại mật khẩu đã được gửi.";
            successBox.style.display = "block";
          }
        } else {
          if (errorBox) {
            errorBox.textContent = data.message || "Yêu cầu thất bại.";
            errorBox.style.display = "block";
          }
        }
      } catch (err) {
        if (errorBox) {
          errorBox.textContent = "Lỗi kết nối. Vui lòng thử lại.";
          errorBox.style.display = "block";
        }
      } finally {
        if (submitBtn) {
          submitBtn.disabled = false;
          submitBtn.textContent = "Gửi yêu cầu";
        }
      }
    });
  }
});