<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Verify OTP | Smart Phone Platform For Businesses</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="{{ asset('assets/css/vendors_css.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

    <style>
        body {
            background: #f6f7fb;
            min-height: 100vh;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        /* Center card and keep small height */
        .otp-card {
            width: 100%;
            max-width: 420px;
            background: #fff;
            padding: 30px 32px;
            border-radius: 18px;
            box-shadow: 0 10px 28px rgba(0, 0, 0, 0.15);
            text-align: center;
        }

        .otp-input {
            width: 45px;
            height: 52px;
            border: 1px solid #ccc;
            border-radius: 10px;
            font-size: 20px;
            font-weight: bold;
            text-align: center;
        }

        .login-btn {
            width: 100%;
            padding: 11px;
            background: #00294d;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            margin-top: 12px;
        }

        #loader {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.7);
            display: none;
            z-index: 999999;
        }

        #loader .spinner {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            border: 6px solid #f3f3f3;
            border-top: 6px solid #3498db;
            border-radius: 50%;
            width: 55px;
            height: 55px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% {
                transform: translate(-50%, -50%) rotate(0deg);
            }

            100% {
                transform: translate(-50%, -50%) rotate(360deg);
            }
        }

        .alert {
            padding: 11px;
            border-radius: 8px;
            margin-bottom: 14px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
        }

        /* Auto centering */
        @media(max-width:480px) {
            .otp-input {
                width: 38px;
                height: 46px;
            }

            .otp-card {
                padding: 25px;
            }
        }
    </style>

</head>

<body>

    <div id="loader">
        <div class="spinner"></div>
    </div>

    <div class="otp-card">

        <!-- LOGO -->
        <img src="{{ env('LEADMINE_LOGO', 'https://leadmine.pro/web/assets/images/headlogo.webp') }}"
            style="max-width:250px;">

        <!-- ================= EMAIL OTP SECTION ================= -->
        <div id="emailSection">

            <h2 style="margin-top:15px;font-weight:700;">Verify Email</h2>
            <p>Enter the 6-digit code sent to <b>{{ request('email') }}</b></p>

            <div id="emailMessage"></div>

            <form id="emailOtpForm">
                @csrf

                <div style="display:flex;gap:10px;justify-content:center;margin-bottom:18px;">
                    <input maxlength="1" class="otp-input email-otp">
                    <input maxlength="1" class="otp-input email-otp">
                    <input maxlength="1" class="otp-input email-otp">
                    <input maxlength="1" class="otp-input email-otp">
                    <input maxlength="1" class="otp-input email-otp">
                    <input maxlength="1" class="otp-input email-otp">
                </div>

                <button class="login-btn" type="submit">VERIFY EMAIL</button>

                <div style="margin-top:10px;">
                    Didn't get code? <br>
                    <button type="button" id="resendEmailOtpBtn" disabled
                        style="margin-top:8px;padding:6px 16px;background:#ccc;border:none;border-radius:6px;">
                        Resend OTP (<span id="emailTimer">30</span>s)
                    </button>
                </div>
            </form>
        </div>


        <!-- ================= MOBILE OTP SECTION (HIDDEN FIRST) ================= -->
        <div id="mobileSection" style="display:none;">

            <h2 style="margin-top:15px;font-weight:700;">Verify Mobile</h2>
            <p id="mobileDesc"></p>

            <div id="mobileMessage"></div>

            <form id="mobileOtpForm">
                @csrf
                <input type="hidden" id="hiddenPhone">

                <div style="display:flex;gap:10px;justify-content:center;margin-bottom:18px;">
                    <input maxlength="1" class="otp-input mobile-otp">
                    <input maxlength="1" class="otp-input mobile-otp">
                    <input maxlength="1" class="otp-input mobile-otp">
                    <input maxlength="1" class="otp-input mobile-otp">
                    <input maxlength="1" class="otp-input mobile-otp">
                    <input maxlength="1" class="otp-input mobile-otp">
                </div>

                <button class="login-btn" type="submit">VERIFY MOBILE</button>

                <div style="margin-top:10px;">
                    Didn't get code? <br>
                    <button type="button" id="resendMobileOtpBtn" disabled
                        style="margin-top:8px;padding:6px 16px;background:#ccc;border:none;border-radius:6px;">
                        Resend OTP (<span id="mobileTimer">10</span>s)
                    </button>
                </div>
            </form>
        </div>

    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        /* =============== OTP Auto-Focus Handler =============== */
        function otpHandler(cls) {
            const boxes = document.querySelectorAll("." + cls);
            boxes.forEach((el, i) => {
                el.addEventListener("input", e => {
                    e.target.value = e.target.value.replace(/\D/g, '').slice(0, 1);
                    if (el.value && i < boxes.length - 1) boxes[i + 1].focus();
                });
                el.addEventListener("keydown", e => {
                    if (e.key === "Backspace" && !el.value && i > 0) {
                        boxes[i - 1].focus();
                    }
                });
            });
        }
        otpHandler("email-otp");
        otpHandler("mobile-otp");


        /* =============== Timer Function =============== */
        function startTimer(btn, span) {
            let t = parseInt(span.textContent);
            btn.disabled = true;
            btn.style.background = "#ccc";

            let timer = setInterval(() => {
                t--;
                span.textContent = t;
                if (t <= 0) {
                    clearInterval(timer);
                    btn.disabled = false;
                    btn.style.background = "#28a745";
                    btn.textContent = "Resend OTP";
                }
            }, 1000);
        }

        startTimer(
            document.getElementById("resendEmailOtpBtn"),
            document.getElementById("emailTimer")
        );


        /* =============== Verify Email OTP =============== */
        $("#emailOtpForm").on("submit", function(e) {
            e.preventDefault();

            let otp = "";
            $(".email-otp").each(function() {
                otp += $(this).val();
            });
            if (otp.length !== 6) {
                $("#emailMessage").html(`<div class="alert alert-danger">Enter full 6-digit OTP.</div>`);
                return;
            }

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

            $.post("{{ route('frontend.verifyBothOtps') }}", {
                _token: "{{ csrf_token() }}",
                email: "{{ request('email') }}",
                email_otp: otp,
                step: 'email'
            }).done(res => {
                $("#loader").hide();

                if (res.success) {

                    $("#emailSection").hide();
                    $("#mobileSection").show();

                    if (res.phone) {
                        $("#hiddenPhone").val(res.phone);
                        let last4 = res.phone.slice(-4);
                        $("#mobileDesc").html(`Enter OTP sent to your phone ending in <b>****${last4}</b>`);
                    } else {
                        $("#mobileDesc").html(`Enter the 6-digit code sent to your mobile`);
                    }

                    // Start timer after DOM is ready
                    setTimeout(() => {
                        startTimer(
                            document.getElementById("resendMobileOtpBtn"),
                            document.getElementById("mobileTimer")
                        );
                    }, 100);

                } else {
                    $("#emailMessage").html(`<div class="alert alert-danger">${res.message}</div>`);
                }

            }).fail(() => {
                $("#loader").hide();
                $("#emailMessage").html(`<div class="alert alert-danger">Invalid OTP.</div>`);
            });
        });


        /* =============== Resend Email OTP =============== */
        $("#resendEmailOtpBtn").on("click", function() {
            $("#loader").show();

            $.post("{{ route('frontend.resend_otp') }}", {
                _token: "{{ csrf_token() }}",
                email: "{{ request('email') }}",
                type: 'email'
            }).done(res => {
                $("#loader").hide();
                if (res.success) {
                    $("#emailMessage").html(`<div class="alert alert-success">OTP resent.</div>`);
                } else {
                    $("#emailMessage").html(
                        `<div class="alert alert-danger">${res.message || 'Unable to resend.'}</div>`);
                }
                this.innerHTML = `Resend OTP (<span id=\"emailTimer\">120</span>s)`;
                startTimer(this, document.getElementById("emailTimer"));
            }).fail(() => {
                $("#loader").hide();
                $("#emailMessage").html(`<div class="alert alert-danger">Unable to resend.</div>`);
            });
        });


        /* =============== Verify Mobile OTP =============== */
        $("#mobileOtpForm").on("submit", function(e) {
            e.preventDefault();

            let otp = "";
            $(".mobile-otp").each(function() {
                otp += $(this).val();
            });

            if (otp.length !== 6) {
                $("#mobileMessage").html(`<div class="alert alert-danger">Enter 6-digit OTP.</div>`);
                return;
            }

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

            $.post("/verifyBothOtps", {
                _token: "{{ csrf_token() }}",
                email: "{{ request('email') }}",
                phone: $("#hiddenPhone").val(),
                otp: otp,
                step: 'mobile'
            }).done(res => {
                $("#loader").hide();

                if (res.success) {
                    window.location.href = "/thank-you";
                } else {
                    $("#mobileMessage").html(`<div class="alert alert-danger">${res.message}</div>`);
                }
            }).fail(() => {
                $("#loader").hide();
                $("#mobileMessage").html(`<div class="alert alert-danger">Invalid OTP.</div>`);
            });
        });


        /* =============== Resend Mobile OTP =============== */
        $("#resendMobileOtpBtn").on("click", function() {
            $("#loader").show();

            $.post("{{ route('frontend.resend_otp') }}", {
                _token: "{{ csrf_token() }}",
                email: "{{ request('email') }}",
                type: 'mobile'
            }).done(res => {
                $("#loader").hide();
                if (res.success) {
                    $("#mobileMessage").html(`<div class="alert alert-success">Mobile OTP resent.</div>`);
                } else {
                    $("#mobileMessage").html(
                        `<div class="alert alert-danger">${res.message || 'Unable to resend.'}</div>`);
                }
                this.innerHTML = `Resend OTP (<span id=\"mobileTimer\">10</span>s)`;
                startTimer(this, document.getElementById("mobileTimer"));
            }).fail(() => {
                $("#loader").hide();
                $("#mobileMessage").html(`<div class="alert alert-danger">Unable to resend.</div>`);
            });
        });
        /* === Auto-focus first input === */
        function focusFirst(selector) {
            setTimeout(() => {
                const box = document.querySelectorAll(selector)[0];
                if (box) box.focus();
            }, 50);
        }

        // Focus email OTP when page loads
        focusFirst(".email-otp");

        /* === Auto instant submit when OTP is complete === */
        function autoSubmitInstant(formSelector, inputSelector, loaderSelector) {
            $(inputSelector).on("input", function() {
                let code = "";
                $(inputSelector).each(function() {
                    code += $(this).val();
                });

                if (code.length === 6) {
                    $(loaderSelector).show();
                    $(formSelector).trigger("submit");
                }
            });
        }

        autoSubmitInstant("#emailOtpForm", ".email-otp", "#loader");
        autoSubmitInstant("#mobileOtpForm", ".mobile-otp", "#loader");

        /* === Auto-focus mobile OTP when email is verified === */
        $(document).ajaxSuccess(function(event, xhr, settings) {
            if (settings.url.includes("verifyBothOtps") && xhr.responseJSON?.success) {
                focusFirst(".mobile-otp");
            }
        });
    </script>

</body>

</html>
