@extends('templates.' . site('template') . '.layouts.auth')

@section('css')
@endsection


@section('contents')
    {{-- Main login secton --}}
    <section class="px-6 lg:px-40 my-12 md:my-28 pt-16 md:pt-20 w-full">
        <div
            class="overflow-hidden border border-transparent bg-clip-border md:self-center w-full lg:w-1/2 mx-auto p-8 md:p-12 lg:p-16 relative rounded-2xl backdrop-blur-sm ">


            <a href="{{ route('home') }}"
                class="bg-[#12b7b6] flex items-center justify-center gap-2  py-2 rounded-xl w-24 mb-10">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
                    style="fill: rgb(255, 255, 255);transform: ;msFilter:;">
                    <path
                        d="m21.743 12.331-9-10c-.379-.422-1.107-.422-1.486 0l-9 10a.998.998 0 0 0-.17 1.076c.16.361.518.593.913.593h2v7a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-4h4v4a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-7h2a.998.998 0 0 0 .743-1.669z">
                    </path>
                </svg>
                <span class="text-white">Home</span>
            </a>

            {{-- notification --}}
            <div class="px-4 lg:px-10 mt-6 space-y-6">
                <p id="noticeMsgOtp" class="hidden noticeMsg"
                    style="position: relative; background-color: #f8f9fa; color:#3b0b3b; padding: 16px; border: 2px solid #12b7b6;  border-radius: 6px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); max-width: 400px; margin: 20px auto; ">
                </p>
            </div>


            <div id="loginFormContainer" class="w-full @if (user()) hidden @endif">
                <!-- Content -->
                <h3 class="font-medium text-center mb-4 text-xl md:text-3xl">
                    Welcome ,
                    <span class="font-semibold">Back</span>
                </h3>
                <p class="text-center text-sm text-[#545454] mb-8 md:mb-16">
                    Please enter your details
                </p>
                <form action="{{ route('user.login-validate') }}" method="POST" id="loginForm">
                    @csrf
                    <label for="" class="text-black">Email Address</label>
                    <div class="relative flex items-center">
                        <img src="{{ asset('/assets/templates/gopie/images/username-icon.svg') }}" alt="Password"
                            class="absolute left-3.5 top-5 w-4 h-4" />
                        <input type="email" id="email" name="email" placeholder="Enter Email Address"
                            @if (env('DEMO_MODE')) value="user@user.com" @endif required
                            class="rounded-xl pl-10 py-4 w-full mb-4 md:mb-10 text-gray-700 mt-1 text-sm focus:outline-none shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)]" />
                    </div>
                    <span>
                        @error('email')
                            {{ $message }}
                        @enderror
                    </span>


                    <label for="" class="text-black">Password</label>
                    <div class="relative flex items-center">
                        <img src="{{ asset('/assets/templates/gopie/images/password-icon.svg') }}" alt="Password"
                            class="absolute left-3.5 top-5 w-4 h-4" />
                        <input type="password" id="password" name="password" placeholder="Enter Password"
                            @if (env('DEMO_MODE')) value="password" @endif
                            class="rounded-xl pl-10 py-4 w-full mb-8 md:mb-10 mt-1 text-gray-700 text-sm focus:outline-none shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)]" />
                    </div>
                    <span>
                        @error('password')
                            {{ $message }}
                        @enderror
                    </span>

                    <div class="flex justify-between items-center mb-8">
                        <!-- Remember me -->
                        <label class="flex items-center space-x-2">
                            <input type="checkbox" id="remember" class="form-checkbox h-5 w-5" />
                            <span class="text-sm text-black">Remember me</span>
                        </label>

                        <!-- Forgot password -->
                        <a href="{{ route('user.forgot-password.index') }}"
                            class="text-sm text-block underline hover:text-[#12b7b6]">Forgot
                            password?</a>
                    </div>

                    <button type="submit" id="loginBtn"
                        class="w-full rounded-3xl text-black hover:bg-gray-700 hover:text-white py-3 cursor-pointer hover:transform transition-transform shadow-[0px_10px_20px_0px_rgba(0,_0,_0,_0.15)] hover:shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)] flex items-center justify-center">
                        Login
                    </button>
                    <p class="text-center text-[#545454] mt-4">
                        Don't have an account?
                        <a href="{{ route('user.register') }}" class="text-black hover:text-[#12b7b6] font-semibold">Sign
                            Up</a>
                    </p>
                </form>
            </div>

            <div id="verifyFormContainer" class="w-full @if (!user()) hidden @endif">
                <!-- Content -->
                <h3 class="font-medium text-center mb-4 text-xl md:text-3xl">
                    <span class="font-semibold">OTP</span>
                </h3>
                <p class="text-center text-sm text-[#545454] mb-8 md:mb-16">
                    Enter the OTP Sent to your Email
                </p>

                <form action="{{ route('user.login-verify') }}" method="POST" id="verifyForm">
                    @csrf

                    <div class="w-full mb-20 flex items-center justify-center mb-6">

                        <div class="grid lg:grid-cols-6 grid-cols-3 lg:gap-10 gap-6 text-black">
                            <input type="number" maxlength="1" name="otp[]" autofocus
                                class="otp-input w-12 h-10 text-center text-xl bg-transparent border border-gray-300 shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)] rounded-md focus:ring-2 focus:ring-blue-500 focus:outline-none" />
                            <input type="number" maxlength="1" name="otp[]"
                                class="otp-input w-12 h-10 text-center text-xl bg-transparent border border-gray-300 shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)] rounded-md focus:ring-2 focus:ring-blue-500 focus:outline-none" />
                            <input type="number" maxlength="1" name="otp[]"
                                class="otp-input w-12 h-10 text-center text-xl bg-transparent border border-gray-300 shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)] rounded-md focus:ring-2 focus:ring-blue-500 focus:outline-none" />
                            <input type="number" maxlength="1" name="otp[]"
                                class="otp-input w-12 h-10 text-center text-xl bg-transparent border border-gray-300 shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)] rounded-md focus:ring-2 focus:ring-blue-500 focus:outline-none" />
                            <input type="number" maxlength="1" name="otp[]"
                                class="otp-input w-12 h-10 text-center text-xl bg-transparent border border-gray-300 shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)] rounded-md focus:ring-2 focus:ring-blue-500 focus:outline-none" />
                            <input type="number" maxlength="1" name="otp[]"
                                class="otp-input w-12 h-10 text-center text-xl bg-transparent border border-gray-300 shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)] rounded-md focus:ring-2 focus:ring-blue-500 focus:outline-none" />
                        </div>
                        <input type="hidden" name="otp" id="otp" value="" required maxlength="6">

                        <span>
                            @error('otp')
                                {{ $message }}
                            @enderror
                        </span>

                    </div>

                    <div class="w-full mb-6">
                        <div class="text-center">
                            <button type="submit" id="verifyBtn"
                                class="w-full rounded-3xl text-black hover:bg-gray-700 hover:text-white py-3 cursor-pointer hover:transform transition-transform shadow-[0px_10px_20px_0px_rgba(0,_0,_0,_0.15)] hover:shadow-[inset_0px_5px_15px_-3px_rgba(0,_0,_0,_0.2)] flex items-center justify-center">Send
                                Code</button>
                        </div>
                    </div>

                    <div class="text-center text-black py-5">
                        <button type="button" class="hover:text-[#12b7b6]" id="resendBtn">Resend OTP</button>
                    </div>

                </form>


            </div>



        </div>
    </section>
@endsection

@section('scripts')
    <script>
        // $('#noticeMsgLogin').text("verifyText").show();

        $(document).ready(function() {

            $('#loginForm').submit(function(e) {
                e.preventDefault();

                var form = $(this);
                var formData = form.serialize();
                var clicked = $('#loginBtn');

                //disable the submit button
                clicked.addClass('relative disabled');
                clicked.append('<span class="button-spinner"></span>');
                clicked.prop('disabled', true);

                //custom styling
                clicked.addClass('disabled-button');
                clicked.removeClass(
                    'text-black hover:bg-gray-700'
                );

                $.ajax({
                    url: form.attr('action'),
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        var verifyText = response.message;
                        var verify = response.verify;
                        $('.noticeMsg').html(verifyText).show();

                        if (verify == 1) {
                            //hide register form and display verification form
                            $('#loginFormContainer').hide();
                            $('#verifyFormContainer').show();

                            //update page title
                            $('#page-title').html('Verify OTP');
                        } else {
                            var url = '{{ route('user.dashboard') }}';
                            window.location.href = url;
                        }




                    },
                    error: function(xhr, status, error) {
                        $('#loginBtn').show();
                        var errors = xhr.responseJSON.errors;

                        if (errors) {
                            $.each(errors, function(field, messages) {
                                var fieldErrors = '';
                                $.each(messages, function(index, message) {
                                    fieldErrors += message + '<br>';
                                });


                                toastNotify('error', fieldErrors);
                            });
                        } else {
                            toastNotify('error', 'An error occured, please try again later');
                        }


                    },
                    complete: function() {
                        clicked.removeClass('disabled');
                        clicked.find('.button-spinner').remove();
                        clicked.prop('disabled', false);

                        //custom styling
                        clicked.removeClass('disabled-button');
                        clicked.addClass(
                            'text-black hover:bg-gray-700'
                        );

                    }

                });
            });


            //otp form
            $('#verifyForm').submit(function(e) {
                e.preventDefault();

                var form = $(this);
                var formData = form.serialize();
                var clicked = $('#verifyBtn');

                //disable the submit button
                clicked.addClass('relative disabled');
                clicked.append('<span class="button-spinner"></span>');
                clicked.prop('disabled', true);

                //custom styling
                clicked.addClass('disabled-button');
                clicked.removeClass(
                    'text-black hover:bg-gray-700'
                );

                $.ajax({
                    url: form.attr('action'),
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        var verifyText = response.message;

                        $('.noticeMsg').text(verifyText).show();
                        console.log(verifyText);

                        var url = '{{ route('user.dashboard') }}';
                        window.location.href = url;

                    },
                    error: function(xhr, status, error) {
                        $('#verifyBtn').show();
                        var errors = xhr.responseJSON.errors;

                        if (errors) {
                            $.each(errors, function(field, messages) {
                                var fieldErrors = '';
                                $.each(messages, function(index, message) {
                                    fieldErrors += message + '<br>';
                                });


                                toastNotify('error', fieldErrors);
                            });
                        } else {
                            toastNotify('success', 'An error occured, please try again later');
                        }


                    },
                    complete: function() {
                        clicked.removeClass('disabled');
                        clicked.find('.button-spinner').remove();
                        clicked.prop('disabled', false);

                        //custom styling
                        clicked.removeClass('disabled-button');
                        clicked.addClass(
                            'text-black hover:bg-gray-700'
                        );


                    }

                });
            });

        });
    </script>


    <script>
        const resendBtn = document.getElementById('resendBtn');
        const loginBtn = document.getElementById('loginBtn');
        let isClickable = true;
        let countdown;

        function startCountdown() {
            if (isClickable) {
                isClickable = false;
                resendBtn.disabled = true;

                let secondsLeft = 120; // 2 minutes
                countdown = setInterval(() => {
                    if (secondsLeft > 0) {
                        const minutes = Math.floor(secondsLeft / 60);
                        const seconds = secondsLeft % 60;
                        const formattedTime = `${minutes}:${seconds.toString().padStart(2, '0')}`;
                        resendBtn.textContent = `Resend Again in ${formattedTime}`;
                        secondsLeft--;
                    } else {
                        resendBtn.textContent = 'Resend OTP';
                        resendBtn.disabled = false;
                        isClickable = true;
                        clearInterval(countdown);
                    }
                }, 1000); // Update every 1 second
            }
        }

        resendBtn.addEventListener('click', () => {
            startCountdown();
            // Define the CSRF token
            var csrfToken = '{{ csrf_token() }}';

            // Add the CSRF token to the request headers
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': csrfToken
                }
            });

            // Send the AJAX request
            $.ajax({
                url: "{{ route('user.resend-otp') }}",
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    var verifyText = response.message;

                    toastNotify('success', verifyText);

                },
                error: function(xhr, status, error) {
                    var errors = xhr.responseJSON.errors;

                    if (errors) {
                        $.each(errors, function(field, messages) {
                            var fieldErrors = '';
                            $.each(messages, function(index, message) {
                                fieldErrors += message + '<br>';
                            });

                            toastNotify('error', fieldErrors);

                        });
                    } else {

                        toastNotify('error', 'An error occured, please try again later');

                    }
                }
            });




        });

        loginBtn.addEventListener('click', () => {
            startCountdown();
        });
    </script>

    <script>
        ////// Concatenate all input values
        $(document).ready(function() {
            $('.otp-input').on('input', function() {
                let otpValue = '';

                // Concatenate all input values
                $('.otp-input').each(function() {
                    otpValue += $(this).val();
                });

                // Set the hidden input value
                $('#otp').val(otpValue);
            });
        });


        $(document).ready(function() {
            const $inputs = $(".otp-input");

            $inputs.on("input", function(e) {
                const $this = $(this);
                const value = $this.val();

                // Allow only 1 character
                if (value.length > 1) {
                    $this.val(value.charAt(0)); // Keep only the first character
                }

                // Move focus to the next input if a character is entered
                if (value.length === 1) {
                    $this.next(".otp-input").focus();
                }
            });

            $inputs.on("keydown", function(e) {
                const $this = $(this);

                if (e.key === "Backspace" && !$this.val()) {
                    $this.prev(".otp-input").focus();
                }
            });

            $inputs.on("paste", function(e) {
                const pasteData = e.originalEvent.clipboardData.getData('text').slice(0, $inputs.length);

                // Fill inputs with pasted data, ensuring only one character per input
                $inputs.each(function(index) {
                    $(this).val(pasteData[index] || "");
                });

                // Focus on the next input after the last pasted character
                $inputs.eq(pasteData.length).focus();
                e.preventDefault();
            });
        });
    </script>
@endsection
