<div class="container">
    <div class="login-container">

        <!-- Logo Section -->
        <div style="text-align:center; padding:10px 0;">

            <div class="school-logo mb-3">
                <i class="fas fa-graduation-cap"></i>
            </div>

            <h2 style="font-size:30px; font-weight:800; color:#000; margin:0;">
                StuLite
            </h2>

            <small style="color:#aaa; font-size:12px; letter-spacing:2px;">
                OTP Verification
            </small>
        </div>

        <!-- Error Message -->
        <% if (typeof error_msg !=='undefined' && error_msg) { %>

            <div class="alert alert-danger">
                <%= error_msg %>
            </div>

            <% } %>


                <% if (typeof success_msg !=='undefined' && success_msg) { %>
                    <div class="alert alert-success">
                        <%= success_msg %>
                    </div>
                    <% } %>


                        <!-- Verification Form -->

                        <form id="verificationForm" method="POST">
                            <div class="verification-code">
                                <input type="text" maxlength="1" class="otp-input" name="digit1" />
                                <input type="text" maxlength="1" class="otp-input" name="digit2" />
                                <input type="text" maxlength="1" class="otp-input" name="digit3" />
                                <input type="text" maxlength="1" class="otp-input" name="digit4" />
                                <input type="text" maxlength="1" class="otp-input" name="digit5" />
                                <input type="text" maxlength="1" class="otp-input" name="digit6" />
                            </div>


                            <button type="submit" class="btn btn-primary btn-login">
                                Verify
                            </button>

                        </form>
                        <hr>
                        <div class="text-center">
                            <a class="small" href="<%= ROUTES.ADMIN_LOGIN %>">Back To Login?</a>
                        </div>
                        <hr>
                        <div class="text-center">
                            <a class="small resend_mail" href="#">Resend OTP?</a>
                        </div>
    </div>
</div>
<div class="loader"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        const inputs = document.querySelectorAll(".otp-input");

        inputs.forEach((input, index) => {

            // 🔥 TYPE ONLY NUMBER + AUTO NEXT
            input.addEventListener("input", function () {

                // allow only numbers
                this.value = this.value.replace(/[^0-9]/g, "");

                if (this.value && index < inputs.length - 1) {
                    inputs[index + 1].focus();
                }

            });

            // 🔥 BACKSPACE GO PREVIOUS
            input.addEventListener("keydown", function (e) {

                if (e.key === "Backspace") {

                    if (this.value === "" && index > 0) {
                        inputs[index - 1].focus();
                    }

                }

                // 🔥 PREVENT SPACE
                if (e.key === " ") {
                    e.preventDefault();
                }

            });

            // 🔥 PASTE SUPPORT (VERY IMPORTANT BEST PRACTICE)
            input.addEventListener("paste", function (e) {
                e.preventDefault();

                const paste = (e.clipboardData || window.clipboardData).getData("text");

                const digits = paste.replace(/\D/g, "").split("");

                inputs.forEach((inp, i) => {
                    inp.value = digits[i] || "";
                });

                const lastFilledIndex = Math.min(digits.length, inputs.length) - 1;

                if (lastFilledIndex >= 0) {
                    inputs[lastFilledIndex].focus();
                }
            });

        });
        // OTP Submit
        const form = document.getElementById("verificationForm");

        if (form) {
            form.addEventListener("submit", async function (event) {
                event.preventDefault();

                $(".loader").show();

                const otp = [...document.querySelectorAll("input[name^='digit']")]
                    .map(input => input.value)
                    .join("");

                try {
                    const res = await fetch("<%= ROUTES.ADMIN_VERIFY %>", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json"
                        },
                        body: JSON.stringify({ otp })
                    });

                    const data = await res.json();

                    $(".loader").hide();

                    if (data.success) {

                        await Swal.fire({
                            title: "Success!",
                            text: "Code verified successfully!",
                            icon: "success",
                            confirmButtonText: "OK"
                        });
                         if(data.isNewUser){
                            window.location.href = "<%= ROUTES.ADMIN_LOGIN %>";
                        } else {
                            window.location.href = "<%= ROUTES.ADMIN_RESET_PASSWORD %>";
                        }
                    } else {

                        await Swal.fire({
                            title: "Error!",
                            text: data.message || "Invalid code. Please try again.",
                            icon: "error",
                            confirmButtonText: "OK"
                        });

                        window.location.href = "<%= ROUTES.ADMIN_VERIFY %>";
                    }

                } catch (error) {

                    $(".loader").hide();
                    console.error(error);

                    await Swal.fire({
                        title: "Error!",
                        text: "An error occurred. Please try again.",
                        icon: "error",
                        confirmButtonText: "OK"
                    });

                    window.location.href = "<%= ROUTES.ADMIN_VERIFY %>";
                }

            });
        }

        // Resend OTP
        $(document).on("click", ".resend_mail", function (e) {
            e.preventDefault();
            $(".loader").show();

            $.ajax({
                url: "<%= ROUTES.ADMIN_RESENT_EMAIL %>",
                type: "POST",

                success: function (response) {
                    console.log('response:', response);

                    $(".loader").hide();
                    if (response.success == true) {
                        Swal.fire({
                            title: "Success!",
                            text: response.message,
                            icon: "success",
                            confirmButtonText: "OK"
                        }).then(() => {
                            window.location.href = "<%= ROUTES.ADMIN_VERIFY %>";
                        });
                    } else {
                        console.log("error ", response);
                    }

                },

                error: function (xhr) {

                    $(".loader").hide();

                    Swal.fire({
                        title: "Error!",
                        text: xhr.responseJSON?.message || "Something went wrong",
                        icon: "error",
                        confirmButtonText: "OK"
                    });

                }
            });

        });

    });
</script>