@extends('admin.layouts.layout')
@section('title', 'Verify the OTP')

@section('content')

    <!-- Content -->

    <div class="container-xxl">
        <div class="authentication-wrapper authentication-basic container-p-y">
            <div class="authentication-inner">
                @if ($errors->has('error'))
                    <div class="alert alert-danger alert-dismissible" role="alert">
                        {{ $errors->first('error') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif
                <div class="card">
                    <div class="card-body">
                        <!-- Logo -->
                        <div class="app-brand justify-content-center">
                            <a class="app-brand-link gap-2">
                                <span class="app-brand-logo demo">
                                    <img src="{{ asset($websiteData->company_footer_logo) }}" alt="Website_Logo"
                                        width="120px" height="90px">
                                </span>
                            </a>
                        </div>
                        <!-- /Logo -->
                        <h4 class="mb-2">Welcome to {{ $websiteData->company_name }} Admin Panel! 👋</h4>
                        <p class="mb-4">Please enter the OTP to get-in to your account.</p>

                        <form onsubmit="return checkInputs();" class="mb-3" action="{{ route('verify.otp') }}"
                            method="POST">
                            @csrf
                            <div class="mb-3">
                                <label class="form-label">Enter OTP</label>
                                <div class="d-flex gap-2 justify-content-center">
                                    <input type="text" class="otp-input form-control text-center" maxlength="1">
                                    <input type="text" class="otp-input form-control text-center" maxlength="1">
                                    <input type="text" class="otp-input form-control text-center" maxlength="1">
                                    <input type="text" class="otp-input form-control text-center" maxlength="1">
                                    <input type="text" class="otp-input form-control text-center" maxlength="1">
                                    <input type="text" class="otp-input form-control text-center" maxlength="1">
                                </div>
                                <input type="hidden" name="login_otp" id="login_otp">
                                <div id="login_otp_error" class="text-danger"></div>
                                @error('login_otp')
                                    <div class="text-danger">{{ $message }}</div>
                                @enderror

                                <div class="text-center mt-2">
                                    <button type="button" id="resendOtp" disabled class="btn btn-link p-0">
                                        <span id="resendText">Resend OTP (<span id="timer">30</span>s)</span>
                                        <span id="resendLoader" class="spinner-border spinner-border-sm ms-2" role="status"
                                            style="display:none;"></span>
                                    </button>
                                </div>
                                <div id="resend_success" class="text-success mt-1"></div>
                                <div id="resend_error" class="text-danger mt-1"></div>
                            </div>
                            <div class="mb-3">
                                <button
                                    class="btn btn-primary d-grid w-100 d-flex justify-content-center align-items-center gap-2"
                                    id="verifyOtpBtn" type="submit">
                                    <span id="btnText">Verify OTP</span>
                                    <span id="btnLoader" class="spinner-border spinner-border-sm d-none" role="status"
                                        aria-hidden="true"></span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- / Content -->

@endsection

@section('admin-custom-js')
    <script>
        // ===== OTP Input Auto-Move =====
        const otpInputs = document.querySelectorAll('.otp-input');
        otpInputs.forEach((input, index) => {
            input.addEventListener('input', () => {
                if (input.value.length === 1 && index < otpInputs.length - 1) {
                    otpInputs[index + 1].focus();
                }
                updateOtpValue();
            });

            input.addEventListener('keydown', (e) => {
                if (e.key === "Backspace" && index > 0 && !input.value) {
                    otpInputs[index - 1].focus();
                }
            });
        });

        function updateOtpValue() {
            let otp = '';
            otpInputs.forEach(i => otp += i.value);
            document.getElementById('login_otp').value = otp;
        }

        // ===== Timer & Resend OTP =====
        const resendBtn = document.getElementById("resendOtp");
        const resendText = document.getElementById("resendText");
        const resendLoader = document.getElementById("resendLoader");
        const resendSuccess = document.getElementById("resend_success");
        const resendError = document.getElementById("resend_error");
        const timerElement = document.getElementById("timer");
        let timer = 30;
        let countdownInterval = null;

        // Start initial countdown
        startCountdown();

        function startCountdown() {
            const timerElement = document.getElementById("timer");

            resendBtn.disabled = true;
            timerElement.textContent = timer;

            countdownInterval = setInterval(() => {
                timer--;
                if (timerElement) timerElement.textContent = timer;

                if (timer <= 0) {
                    clearInterval(countdownInterval);
                    resendBtn.disabled = false;
                    resendText.textContent = "Resend OTP";
                }
            }, 1000);
        }

        // Resend OTP Click Handler
        resendBtn.addEventListener("click", () => {
            // Clear previous messages
            resendSuccess.textContent = "";
            resendError.textContent = "";

            // UI changes
            resendBtn.disabled = true;
            resendText.textContent = "Sending...";
            resendLoader.style.display = "inline-block";

            fetch("{{ route('resend.otp') }}", {
                    method: "POST",
                    headers: {
                        "X-Requested-With": "XMLHttpRequest",
                        "X-CSRF-TOKEN": "{{ csrf_token() }}"
                    }
                })
                .then(response => response.json())
                .then(data => {
                    resendLoader.style.display = "none";

                    if (data.status === "success") {
                        resendSuccess.textContent = data.message;

                        // Reset timer
                        timer = 30;
                        resendText.innerHTML = `Resend OTP (<span id="timer">${timer}</span>s)`;

                        startCountdown();

                    } else {
                        resendError.textContent = data.message;
                        resendBtn.disabled = false;
                        resendText.textContent = "Resend OTP";
                    }
                })
                .catch(() => {
                    resendLoader.style.display = "none";
                    resendError.textContent = "Something went wrong!";
                    resendBtn.disabled = false;
                    resendText.textContent = "Resend OTP";
                });
        });

        // ===== OTP Validation =====
        function checkInputs() {
            let otp = document.getElementById('login_otp').value.trim();
            let errors = 0;

            document.getElementById("login_otp_error").textContent = "";

            if (otp.length !== 6) {
                document.getElementById("login_otp_error").textContent = "Enter valid 6-digit OTP";
                errors += 1;
            }

            if (errors > 0) {
                return false;
            } else {
                document.getElementById("btnText").textContent = "Please Wait...";
                document.getElementById("btnLoader").classList.remove("d-none");
                document.getElementById("verifyOtpBtn").disabled = true;
            }
        }
    </script>

@endsection
