<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login | ILYBAZAR</title>
    <link rel="icon" href="{{ asset('/assets') }}/images/favicon.ico" type="image/x-icon">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" type="text/css" href="{{ asset('/assets') }}/css/bootstrap/5.3.2/bootstrap.min.css">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="{{ asset('/assets') }}/css/icons/fontawesome/css/fontawesome.css">
    <link rel="stylesheet" href="{{ asset('/assets') }}/css/icons/fontawesome/css/brands.css">
    <link rel="stylesheet" href="{{ asset('/assets') }}/css/icons/fontawesome/css/regular.css">
    <link rel="stylesheet" href="{{ asset('/assets') }}/css/icons/fontawesome/css/solid.css">

    <!-- Page CSS -->
    <link rel="stylesheet" type="text/css" href="{{ asset('/assets') }}/css/style.css">
    <link rel="stylesheet" type="text/css" href="{{ asset('/assets') }}/css/authentication.css">

    <!-- SweetAlert CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .logo-widget {
            background: #D4EFFF;
            /* background:url('{{ asset('/assets') }}/images/login-bg.svg'); */
            background-size: cover !important;
        }

        #otp-actions {
            display: none;
            opacity: 0;
            position: relative;
            bottom: -20px;
            transition: opacity 0.5s ease-in-out, bottom 0.5s ease-in-out;
        }

        #otp-actions.show {
            opacity: 1;
            bottom: 0;
        }

        #otp-success-message {
            color: black;
            /* Default text color */
            font-weight: bold;
            /* Make text bold */
            margin-top: 10px;
            /* Space above the message */
        }

        #otp-error-message {
            color: black;
            /* Default text color */
            font-weight: bold;
            /* Make text bold */
            margin-top: 10px;
            /* Space above the message */
        }

        #otp-success-message.success {
            color: green;
            /* Success message color */
        }

        #otp-success-message.error {
            color: red;
            /* Error message color */
        }
    </style>

</head>

<body>
    <div class="page-content overflow-hidden min-vh-100 login-container">
        <div class="row g-0 vh-100">
            <div class="col-xl-5 col-lg-5 col-md-6 col-sm-6 rightside-widget-col">
                <div class="p-lg-5 p-4 h-100 logo-widget">
                    <div class="d-flex justify-content-center align-items-center h-100">
                        <div class="">
                            <img src="{{ asset('/assets') }}/images/login-frame.svg" style="height:400px;"
                                class="inframe-logo" alt="logo frame">
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-7 col-lg-7 col-md-6 col-sm-6 d-flex justify-content-center align-items-center">
                <div class="py-3 px-lg-5 px-md-4 px-sm-4 px-4 form-container row">
                    <div class="d-flex justify-content-center mb-1">
                        <img src="{{ asset('/assets') }}/images/logo-horizontal.svg" class=" d-none widget-logo"
                            alt="logo-horizontal">
                    </div>
                    <div class="text-start">
                        <h3 class="login-heading">Login</h3>
                        <p class="py-2 login-slogan">Please fill your information below</p>
                    </div>

                    <!-- Form start -->


                    <form id="loginForm" action="{{ route('login.handle') }}" method="POST"
                        class="row g-3 needs-validation" autocomplete="off">
                        @csrf


                        <div class="input-group mb-4">
                            <span class="input-group-text">
                                <img src="{{ asset('/assets') }}/images/icons/envelope.svg" alt="Email Icon">
                            </span>
                            <input type="email" name="email" class="form-control" placeholder="E-mail"
                                aria-label="Email" aria-describedby="Email" autocomplete="off" required>
                        </div>
                        <div class="input-group mb-3 position-relative">
                            <span class="input-group-text">
                                <img src="{{ asset('/assets') }}/images/icons/lock.svg" alt="Lock Icon">
                            </span>
                            <input type="password" name="password" id="password" class="form-control"
                                placeholder="Password" aria-label="Password" aria-describedby="Password"
                                autocomplete="off" required>
                            <button type="button" id="toggler" class="btn transparent-btn"><i id="icon"
                                    class="fa-solid fa-eye-slash"></i></button>
                        </div>
                        <strong class="text-info mt-2" id="send_msg" style="color:green;"></strong>

                        <div class="d-flex justify-content-end align-items-center">
                            <a href="{{ route('forgot_password') }}" target="_self" class="forgot-pwd">Forgot
                                Password?</a>
                        </div>
                        <div class="mt-2">
                            <div class="otp-container" id="otpContainer">

                                    <button class="btn btn-warning send-otp-btn" id="sendOtpBtn" name="action" type="button" value="send_otp">Send OTP</button>
                                <!-- Send OTP Button -->
                                <input type="text" name="send_otp" class="form-control send_otp" id="send_otp"
                                    placeholder="OTP">
                            </div>
                        </div>
                        <div class="login-btn-container">
                             <button class="btn btn-success login-btn w-100" id="loginBtn" name="action" type="button" value="verify_otp">Login</button>
                        </div>
                        <div class="otp-actions text-center" id="otp-actions" style="display:none;">
                            <p class="resend-otp-timer">Resend OTP in <span>05:00</span></p>
                        </div>
                    </form>
                    <!-- Form Ends -->




                </div>
            </div>
        </div>
    </div>

    {{-- toast --}}
    <!-- Success Toast -->
    @if (session('successmessage'))
        <div id="success-toast" class="toast bg-success align-items-center border-0 show" role="alert"
            aria-live="assertive" aria-atomic="true"
            style="position: fixed; top: 150px; right: 20px; z-index: 1050; border-radius: 8px;">
            <div class="toast-body d-flex text-white align-items-center">
                <i class="fa-regular fa-circle-check" style="font-size: 20px; margin-right: 10px;"></i>
                <div>
                    {{ session('successmessage') }}
                </div>
                <button type="button" class="btn-close btn-close-white ms-2" data-bs-dismiss="toast"
                    aria-label="Close"></button>
            </div>
        </div>
    @endif

    <!-- Error Toast -->
    @if ($errors->any())
        <div id="error-toast" class="toast bg-danger align-items-center border-0 show" role="alert"
            aria-live="assertive" aria-atomic="true"
            style="position: fixed; top: 80px; right: 20px; z-index: 1050; border-radius: 8px;">
            <div class="toast-body d-flex text-white align-items-center">
                <i class="fa-solid fa-circle-exclamation" style="font-size: 20px; margin-right: 10px;"></i>
                <div>
                    @foreach ($errors->all() as $error)
                        <div>{{ $error }}</div>
                    @endforeach
                </div>
                <button type="button" class="btn-close btn-close-white ms-2" data-bs-dismiss="toast"
                    aria-label="Close"></button>
            </div>
        </div>
    @endif
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Get session messages from Blade and escape them for use in JavaScript
            const successMessage = @json(session('successmessage'));
            const errorMessage = @json($errors->any() ? $errors->first() : null);

            function showAlertAndToast(type, message) {
                // Determine the alert title and text based on the type
                const isSuccess = type === 'success';
                const alertTitle = isSuccess ? 'Success' : 'Error';
                const alertText = message || (isSuccess ? 'Operation was successful!' : 'Something went wrong!');

                // Show SweetAlert
                Swal.fire({
                    icon: type,
                    title: alertTitle,
                    text: alertText,
                    willClose: () => {
                        // Show Toast after SweetAlert closes
                        const toastElement = document.getElementById(`${type}-toast`);
                        if (toastElement) {
                            const toast = new bootstrap.Toast(toastElement);
                            toast.show();
                        }
                    }
                });
            }

            // Show alerts based on session messages
            if (successMessage) {
                showAlertAndToast('success', successMessage);
            } else if (errorMessage) {
                showAlertAndToast('error', errorMessage);
            }

            // Event listeners for manual triggers (for testing)
            document.getElementById('trigger-success').addEventListener('click', function() {
                showAlertAndToast('success', successMessage);
            });

            document.getElementById('trigger-error').addEventListener('click', function() {
                showAlertAndToast('error', errorMessage);
            });
        });
    </script>
    <!-- JS for Resend OTP Timer -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var sendOtpButton = document.getElementById('send-otp-btn');
            var otpActions = document.getElementById('otp-actions');
            var timerDisplay = document.querySelector('.resend-otp-timer span');
            var initialTime = 5 * 60;

            sendOtpButton.addEventListener('click', function() {
                sendOtpButton.classList.add('disabled');
                otpActions.style.display = 'block';
                setTimeout(function() {
                    otpActions.classList.add('show');
                }, 10);
                startCountdown(initialTime);
            });

            function startCountdown(duration) {
                var timer = duration;
                var interval = setInterval(function() {
                    var minutes = Math.floor(timer / 60);
                    var seconds = timer % 60;
                    minutes = minutes < 10 ? '0' + minutes : minutes;
                    seconds = seconds < 10 ? '0' + seconds : seconds;
                    timerDisplay.textContent = minutes + ':' + seconds;

                    if (--timer < 0) {
                        clearInterval(interval);
                        sendOtpButton.classList.remove('disabled');
                        otpActions.classList.remove('show');
                        setTimeout(function() {
                            otpActions.style.display = 'none';
                        }, 500);
                    }
                }, 1000);
            }
        });
    </script>
    {{-- toast --}}

    <script>
        const otpInput = document.getElementById('send_otp');
        const otpContainer = document.getElementById('otpContainer');
        otpInput.addEventListener('focus', function() {
            otpContainer.style.borderColor = '#022859';
        });
        otpInput.addEventListener('blur', function() {
            otpContainer.style.borderColor = 'rgba(179, 180, 186, 1)';
        });
    </script>



    <!-- JS for Resend OTP Timer -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var sendOtpButton = document.getElementById('send-otp-btn');
            var otpActions = document.getElementById('otp-actions');
            var timerDisplay = document.querySelector('.resend-otp-timer span');
            var initialTime = 5 * 60;

            sendOtpButton.addEventListener('click', function() {
                sendOtpButton.classList.add('disabled');
                otpActions.style.display = 'block';
                setTimeout(function() {
                    otpActions.classList.add('show');
                }, 10);
                startCountdown(initialTime);
            });

            function startCountdown(duration) {
                var timer = duration;
                var interval = setInterval(function() {
                    var minutes = Math.floor(timer / 60);
                    var seconds = timer % 60;
                    minutes = minutes < 10 ? '0' + minutes : minutes;
                    seconds = seconds < 10 ? '0' + seconds : seconds;
                    timerDisplay.textContent = minutes + ':' + seconds;

                    if (--timer < 0) {
                        clearInterval(interval);
                        sendOtpButton.classList.remove('disabled');
                        otpActions.classList.remove('show');
                        setTimeout(function() {
                            otpActions.style.display = 'none';
                        }, 500);
                    }
                }, 1000);
            }
        });
    </script>



    <script type="text/javascript" src="{{ asset('/assets') }}/js/authentication.js"></script>
    <script type="text/javascript" src="{{ asset('/assets') }}/js/bootstrap/5.3.2/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    {{-- <script type="text/javascript">
        $(document).ready(function() {
          console.log("all")
            // Handle Send OTP button click
            $('#sendOtpBtn').on('click', function(event) {
                event.preventDefault(); // Prevent the default form submission

                // Add loading state to button
                $(this).text('Sending OTP...').addClass('disabled');

                $.ajax({
                    url: "{{ route('login.handle') }}", // Ensure this is the correct route
                    method: "POST",
                    data: {
                        _token: '{{ csrf_token() }}',
                        action: 'send_otp',
                        email: $('input[name="email"]').val()
                    },
                    dataType: 'json', // Expect JSON response
                    success: function(response) {
                        if (response.status === "success") {
                            $('#send_msg').text(response.message);
                        } else {
                            $('#send_msg').text(response
                            .message); // Display error message from server
                        }
                        // Reset button after response
                        $('#sendOtpBtn').text('Send OTP').removeClass('disabled');
                    },
                    error: function(xhr) {
                        // Handling different types of errors
                        if (xhr.status === 422) { // Unprocessable Entity (validation errors)
                            $('#send_msg').text('Invalid email address.');
                        } else {
                            $('#send_msg').text('Error sending OTP: ' + xhr.statusText);
                        }
                        // Reset button after response
                        $('#sendOtpBtn').text('Send OTP').removeClass('disabled');
                    }
                });
            });

        // Handle Verify OTP button click
        $('#loginBtn').on('click', function(event) {
                event.preventDefault(); 

                const otp = $('#send_otp').val();
                if (!otp) {
                    Swal.fire('Error', 'Please enter the OTP.', 'error');
                    return;
                }

                $.ajax({
                    url: "{{ route('login.handle') }}",
                    method: "POST",
                    data: {
                        _token: '{{ csrf_token() }}',
                        action: 'verify_otp',
                        otp: otp,
                        email: $('input[name="email"]').val(),
                        password: $('#password').val()
                    },
                    success: function(response) {
                        if (response.status === 'success') {
                            window.location.href = response.redirect_url;
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    },
                    error: function(xhr) {
                        Swal.fire('Error', 'An error occurred. Please try again.', 'error');
                    }
                });
            });   
            //
            // Handle password visibility toggle
            $('#toggler').on('click', function() {
                const passwordField = $('#password');
                const icon = $('#icon');
                const isPasswordVisible = passwordField.attr('type') === 'text';

                if (isPasswordVisible) {
                    passwordField.attr('type', 'password');
                    icon.removeClass('fa-eye').addClass('fa-eye-slash');
                } else {
                    passwordField.attr('type', 'text');
                    icon.removeClass('fa-eye-slash').addClass('fa-eye');
                }
            });
             //
            // Function to start countdown
            function startCountdown(duration) {
                let timer = duration,
                    minutes, seconds;
                const countdownElement = $('.resend-otp-timer span');

                const interval = setInterval(function() {
                    minutes = parseInt(timer / 60, 10);
                    seconds = parseInt(timer % 60, 10);

                    minutes = minutes < 10 ? '0' + minutes : minutes;
                    seconds = seconds < 10 ? '0' + seconds : seconds;

                    countdownElement.text(`${minutes}:${seconds}`);

                    if (--timer < 0) {
                        clearInterval(interval);
                        $('#otp-actions').show(); // Show the OTP actions after countdown
                        $('#sendOtpBtn').removeClass('disabled'); // Enable button after countdown
                    }
                }, 1000);
            }
        });
    </script> --}}


    <script type="text/javascript">
    $(document).ready(function() {
    $('#sendOtpBtn').on('click', function(event) {
        event.preventDefault();

        // Disable button and set loading state
        $(this).text('Sending OTP...').addClass('disabled');

        // Send OTP via AJAX
        $.ajax({
            url: "{{ route('login.handle') }}",
            method: "POST",
            data: {
                _token: '{{ csrf_token() }}',
                action: 'send_otp',
                email: $('input[name="email"]').val()
            },
            dataType: 'json',
            success: function(response) {
                if (response.status === "success") {
                    $('#send_msg').text(response.message).css('color', 'green');
                    startCountdown(120);
                    $('#otp-actions').hide();
                    $('#sendOtpBtn').removeClass('disabled').text('Send OTP');
                } else {
                    $('#send_msg').text(response.message).css('color', 'red');
                    $('#sendOtpBtn').removeClass('disabled').text('Send OTP');
                }
            },
            error: function(xhr) {
                $('#send_msg').text('Error: ' + xhr.statusText).css('color', 'red');
                $('#sendOtpBtn').removeClass('disabled').text('Send OTP');
            }
        });
    });

    $('#loginBtn').on('click', function(event) {
    event.preventDefault();

    const otp = $('#send_otp').val();
    const email = $('input[name="email"]').val();
    const password = $('#password').val();

    if (!otp || !email) {
        Swal.fire('Error', 'Please enter both OTP and email.', 'error');
        return;
    }

    $.ajax({
        url: "{{ route('login.handle') }}",
        method: "POST",
        data: {
            _token: '{{ csrf_token() }}',
            action: 'verify_otp',
            send_otp: otp, 
            email: email,
            password: password
        },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                window.location.href = response.redirect_url;
            } else {
                Swal.fire('Error', response.message, 'error');
            }
        },
        error: function(xhr) {
            Swal.fire('Error', 'An error occurred. Please try again.', 'error');
        }
    });
});


    $('#toggler').on('click', function() {
        const passwordField = $('#password');
        const isPasswordVisible = passwordField.attr('type') === 'text';

        passwordField.attr('type', isPasswordVisible ? 'password' : 'text');
        $(this).find('i').toggleClass('fa-eye fa-eye-slash');
    });

    function startCountdown(duration) {
        let timer = duration, minutes, seconds;
        const countdownElement = $('.resend-otp-timer span');

        const interval = setInterval(function() {
            minutes = Math.floor(timer / 60);
            seconds = timer % 60;

            countdownElement.text(`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`);

            if (--timer < 0) {
                clearInterval(interval);
                $('#otp-actions').show();
                $('#sendOtpBtn').removeClass('disabled');
            }
        }, 1000);
    }
});
    </script>
    



</body>

</html>
