<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link
      rel="shortcut icon"
      href="terence-styles/favicon.png"
      type="image/x-icon"
    />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>
      Verify OTP - University of Innovation, Science and Technology, Omuma
    </title>

    <!-- Bootstrap CSS & Icons -->
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="terence-styles/css.css" />

    <style>
      .otp-input {
        width: 50px;
        height: 50px;
        font-size: 24px;
        text-align: center;
        margin: 0 5px;
      }

      .otp-box {
        display: flex;
        justify-content: center;
        gap: 10px;
        margin-bottom: 20px;
      }
    </style>
  </head>

  <body>
    <div class="container-fluid">
      <div class="row min-vh-100">
        <!-- Mobile Title -->
        <div class="d-md-none text-center px-4 pt-3 mt-5">
          <h1 class="h4 fw-bold" style="color: #0d1b4c">
            University of Innovation, Science and Technology, Omuma
          </h1>
          <p class="text-secondary small">Knowledge and Skill for Service.</p>
        </div>

        <!-- Left Panel -->
        <div
          class="col-md-6 d-none d-md-flex flex-column justify-content-center align-items-center text-white text-center"
          style="background-color: #0d1b4c"
        >
          <div class="px-4">
            <h1>UNIVERSITY OF INNOVATION, SCIENCE AND TECHNOLOGY</h1>
            <p>Key to Innovation, Science and Technology</p>
            <img
              src="terence-styles/auth.png"
              alt="Illustration"
              class="img-fluid mt-3 rounded-2"
            />
          </div>
        </div>

        <!-- OTP Input Panel -->
        <div
          class="col-md-6 d-flex align-items-center justify-content-center py-4"
        >
          <div
            class="login-box p-4 shadow rounded bg-white w-100"
            style="max-width: 420px"
          >
            <div class="text-center mb-4">
              <img
                src="terence-styles/dark-logo.png"
                alt="Logo"
                style="width: 120px"
              />
            </div>
            <h5 class="text-center mb-3">Verify OTP</h5>
            <p class="text-center text-muted small mb-4">
              Enter the 4-digit code sent to your email address.
            </p>

            <form id="otpForm">
              <div class="otp-box mb-3">
                <input
                  type="text"
                  class="form-control otp-input"
                  maxlength="1"
                  inputmode="numeric"
                />
                <input
                  type="text"
                  class="form-control otp-input"
                  maxlength="1"
                  inputmode="numeric"
                />
                <input
                  type="text"
                  class="form-control otp-input"
                  maxlength="1"
                  inputmode="numeric"
                />
                <input
                  type="text"
                  class="form-control otp-input"
                  maxlength="1"
                  inputmode="numeric"
                />
              </div>

              <div class="d-grid mb-3">
                <button type="submit" class="btn btn-primary">
                  Verify OTP
                </button>
              </div>

              <div class="text-center">
                <button id="resendBtn" class="btn btn-link" disabled>
                  Resend OTP (<span id="countdown">50</span>s)
                </button>
              </div>

              <div class="text-center mt-3">
                <a href="forgot-password.html" class="text-decoration-none"
                  ><i class="bi bi-arrow-left"></i> Back</a
                >
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
      document.addEventListener("DOMContentLoaded", function () {
        const inputs = document.querySelectorAll(".otp-input");
        const form = document.getElementById("otpForm");
        const resendBtn = document.getElementById("resendBtn");
        const countdownSpan = document.getElementById("countdown");
        let countdown = 50;

        const email = localStorage.getItem("resetEmail");

        if (!email) {
          Swal.fire({
            icon: "error",
            title: "No Email Found",
            text: "Please restart the password recovery process.",
          }).then(() => {
            window.location.href = "forgot-password.html";
          });
          return;
        }

        // Auto-focus next input
        inputs.forEach((input, index) => {
          input.addEventListener("input", () => {
            if (input.value.length === 1 && index < inputs.length - 1) {
              inputs[index + 1].focus();
            }
          });
        });

        // Countdown for initial load
        let timer = setInterval(() => {
          countdown--;
          countdownSpan.textContent = countdown;
          if (countdown === 0) {
            clearInterval(timer);
            resendBtn.disabled = false;
            resendBtn.textContent = "Resend OTP";
          }
        }, 1000);

        // Handle OTP submit
        form.addEventListener("submit", async function (e) {
          e.preventDefault();

          const otp = Array.from(inputs)
            .map((input) => input.value)
            .join("");

          if (otp.length !== 4 || !/^\d{4}$/.test(otp)) {
            return Swal.fire({
              icon: "warning",
              title: "Invalid OTP",
              text: "Please enter a valid 4-digit code.",
            });
          }

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

            const result = await res.json();

            if (res.ok && result.success) {
              localStorage.setItem("resetOtp", otp); // Store OTP for next step
              Swal.fire({
                icon: "success",
                title: "Verified",
                text: "OTP verified successfully. You can now reset your password.",
              }).then(() => {
                window.location.href = "/new-password";
              });
            } else {
              Swal.fire({
                icon: "error",
                title: "Verification Failed",
                text: result.message || "The OTP you entered is incorrect.",
              });
            }
          } catch (err) {
            Swal.fire({
              icon: "error",
              title: "Error",
              text: "Something went wrong. Please try again.",
            });
          }
        });

        // Handle Resend OTP
        resendBtn.addEventListener("click", async function (e) {
          e.preventDefault();

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

            const result = await res.json();

            if (res.ok && result.success) {
              Swal.fire({
                icon: "success",
                title: "OTP Resent",
                text:
                  result.message || "A new OTP has been sent to your email.",
              });

              // Reset countdown
              countdown = 50;
              resendBtn.disabled = true;
              resendBtn.innerHTML = `Resend OTP (<span id="countdown">${countdown}</span>s)`;

              // Re-bind new countdownSpan after updating innerHTML
              const countdownSpanNew = document.getElementById("countdown");

              const newTimer = setInterval(() => {
                countdown--;
                countdownSpanNew.textContent = countdown;
                if (countdown === 0) {
                  clearInterval(newTimer);
                  resendBtn.disabled = false;
                  resendBtn.textContent = "Resend OTP";
                }
              }, 1000);
            } else {
              Swal.fire({
                icon: "error",
                title: "Failed",
                text: result.message || "Could not resend OTP.",
              });
            }
          } catch (err) {
            Swal.fire({
              icon: "error",
              title: "Request Error",
              text: "Failed to resend OTP. Please try again later.",
            });
          }
        });
      });
    </script>
  </body>
</html>
