@extends('shop::layouts.master')
@push('css_before')
    <link rel="stylesheet" href="{{bagisto_asset('styles/swiper-bundle.min.css')}}">
@endpush
@php
    $channel = core()->getCurrentChannel();

    $homeSEO = $channel->home_seo;

    if (isset($homeSEO)) {
        $homeSEO = json_decode($channel->home_seo);

        $metaTitle = $homeSEO->meta_title;

        $metaDescription = $homeSEO->meta_description;

        $metaKeywords = $homeSEO->meta_keywords;
    }
   $count = core()->getConfigData('catalog.products.homepage.no_of_featured_product_homepage');
@endphp

@section('page_title')
    {{ isset($metaTitle) ? $metaTitle : "" }}
@endsection

@section('head')

    @if (isset($homeSEO))
        @isset($metaTitle)
            <meta name="title" content="{{ $metaTitle }}" />
        @endisset

        @isset($metaDescription)
            <meta name="description" content="{{ $metaDescription }}" />
        @endisset

        @isset($metaKeywords)
            <meta name="keywords" content="{{ $metaKeywords }}" />
        @endisset
    @endif
@endsection

@section('content-wrapper')

    <section class="hero">
        <div class="container hero-inner">
            @if(isset($bannerData))
            @include('shop::home.slider', ['sliderData' => $bannerData->where('type','slider')->toArray()])
            @endif
            @include('shop::home.weekly-offers')
        </div>
    </section>
    <main class="item-gallery container">

{{--    @if (! is_null($channel->home_page_content) && !empty($channel->home_page_content))--}}
{{--        {!! DbView::make($channel)->field('home_page_content')->with(['sliderData' => $sliderData])->render() !!}--}}
{{--    @else--}}
        @include('shop::home.new-products')
        @if(isset($bannerData))
        @include('shop::home.banner',['banner'=>$bannerData->where('type','banner')->first()])
        @endif
        @include('shop::home.discount-products')
        @if(isset($bannerData))
        @include('shop::home.banner',['banner'=>$bannerData->where('type','banner')->last()])
        @endif
        @include('shop::home.featured-products')
        @include('shop::home.reviews')
        @include('shop::websiteReview.review-popup')
        @include('shop::products.popup-card')
{{--    @endif--}}
    </main>
    @if(core()->getConfigData('customer.settings.newsletter.subscription'))

        <!-- <section class="pre-footer">
            <div class="container">
            <div class="pre-footer-inner">
                <h2 class="pre-footer-title">{{__('shop::app.footer.subscribe-newsletter')}}</h2>
                <form action="{{ route('shop.subscribe') }}" class="pre-footer-email">
                <input type='email' id="subscribe-field" placeholder="{{__('shop::app.footer.subscribe-email')}}" name="subscriber_email" required>
                <button type="submit">{{__('shop::app.footer.subscribe')}}</button>
                </form>
            </div>
            </div>
        </section> -->

    @endif
    {{ view_render_event('bagisto.shop.home.content.after') }}

@endsection

@push('scripts')
<script src="{{ bagisto_asset('scripts/swiper-bundle.min.js')}}" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {

        // SLIDER SCRIPTS ========================
        let swiper = new Swiper('.mySwiper', {
            spaceBetween: 30,
            loop: true,
            centeredSlides: true,
            autoplay: {
                delay: 3000,
                disableOnInteraction: false,
            },
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
        });

        let swiper1 = new Swiper('.mySwiper1', {
            spaceBetween: 30,
            loop: true,
            centeredSlides: true,
            autoplay: {
                delay: 3000,
                disableOnInteraction: false,
            },
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            navigation: {
                nextEl: '.swiper-button-next2',
                prevEl: '.swiper-button-prev2',
            },
        });

        let swiper2 = new Swiper('.mySwiper2', {
            spaceBetween: 60,
            freeMode: true,
            slidesPerView: 2,
            updateOnWindowResize: true,
        });
        // SLIDER SCRIPTS end ========================

        //SEND WEB REVIEW FORM 
        const $form = $('#review-form');
        const $successMessage = $('#success-message');
        const $successTitle = $('#success-title');

        $form.on('submit', function (event) {
            event.preventDefault();
            const formData = new FormData(this);

            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'X-CSRF-TOKEN': $('input[name="_token"]').val()
                },
                success: function (data) {
                    if (data.success) {
                        $successTitle.text(data.message);
                        $form.addClass('hidden');
                        $successMessage.removeClass('hidden');
                    } else {
                        alert(data.message); 
                    }
                },
                error: function (error) {
                    console.error('Error:', error);
                }
            });
        });
        //SEND WEB REVIEW FORM 

        // Review popup start =======================================
        const $popup = $('#review-popup');
        const $openReviewPopupBtn = $('#openReviewPopupBtn');
        const $closeReviewPopupBtn = $('#closeReviewPopupBtn');
        const $closeReviewPopupBtn2 = $('#closeReviewPopupBtn2');
        const $closeReviewPopupText = $('#closeReviewPopupText');

        const $firstPopupContent = $(".review-popup-content").first();
        const $secondPopupContent = $(".review-popup-content").last();

        const $sendReviewButton = $(".review-popup-button");
        const $nameInput = $("#name");
        const $reviewInput = $("#web_review");

        // Create the loader element ==============================================================
        const $loader = $('<div>', { class: 'loader' });

        const openPopup = () => { 
            $popup.css('display', 'flex');
            $('body').addClass('no-scroll');

            // Reset popup contents
            $firstPopupContent.css('display', 'flex');
            $secondPopupContent.css('display', 'none');
            $loader.remove();
            resetStars();
            resetInputs();
            checkFormCompletion();
        };

        const closePopup = () => {
            $popup.css('display', 'none');
            $('body').removeClass('no-scroll');
            resetStars();
            resetInputs();
        };

        const resetStars = () => {
            $(".review-card-star").removeClass("hovered clicked");
        };

        const resetInputs = () => {
            $("#name, #review").val("");
        };

        const checkFormCompletion = () => {
            // const isNameFilled = $.trim($nameInput.val()) !== "";
            const isReviewFilled = $.trim($reviewInput.val()) !== "";
            const isStarSelected = $(".review-card-star.clicked").length > 0;

            if (isReviewFilled && isStarSelected) {
                $sendReviewButton.removeAttr("disabled");
            } else {
                $sendReviewButton.attr("disabled", true);
            }
        };

        $nameInput.on("input", checkFormCompletion);
        $reviewInput.on("input", checkFormCompletion);

        // $openReviewPopupBtn.on('click', openPopup);
        $signUpSection = $('.sign-up');
        $loginFormSection = $('.login-form');
        $signupFormSection = $('.signup-form');
        $resetPasswordSection = $('.reset-password');

        $closeReviewPopupText.on('click', closePopup);
        $closeReviewPopupBtn.on('click', closePopup);
        $closeReviewPopupBtn2.on('click', closePopup);

        if (isAuthenticated) {
            $openReviewPopupBtn.on('click', openPopup);
        } else {
            $openReviewPopupBtn.on('click', function() {
                $signUpSection.css('display', 'block');
                $loginFormSection.css('display', 'block');
                $signupFormSection.css('display', 'none');
                $resetPasswordSection.css('display', 'none');
            });
        }

        $(window).on('click', (event) => {
            if ($(event.target).is($popup)) {
                closePopup();
            }
        });

        // Review rating click effect start ============================================
        $(".review-rating--popup").each(function() {
            const $container = $(this);
            const $stars = $container.find(".review-card-star");

            let clickedIndex = 0;

            $stars.each(function() {
                const $star = $(this);

                $star.on("mouseover", function() {
                    const index = parseInt($star.attr("data-index"));
                    $stars.each(function(i) {
                        if (i < index) $(this).addClass("hovered");
                    });
                });

                $star.on("mouseout", function() {
                    $stars.removeClass("hovered");
                });

                $star.on("click", function() {
                    const index = parseInt($star.attr("data-index"));

                    $('input[name="web_review_rating"]').val(index);

                    if (index === clickedIndex) {
                        clickedIndex = 0;
                        $stars.removeClass("clicked hovered");
                    } else {
                        clickedIndex = index;
                        $stars.each(function(i) {
                            $(this).toggleClass("clicked", i < index);
                        });
                    }
                    checkFormCompletion(); 
                });
            });
        });

        // Send review ========================================================================
        $sendReviewButton.on("click", function() {
            $firstPopupContent.css('display', 'none');

            $firstPopupContent.after($loader);

            setTimeout(() => {
                $loader.remove();
                $secondPopupContent.css('display', 'block');
            }, 3000);
        });

        $(".close-review-popup").on("click", function() {
            closePopup();
        });

        // Add an event listener to the "Закрыть окно" text to close the popup
        $("#closeReviewPopupText").on("click", function() {
            // Hide the entire popup
            closePopup();
        });

        // Add to cart popup start ============================================================================================================================================================

        const popupCloseIcon = document.querySelector('.add-product-close-btn');
        const popupOverlay = document.getElementById('add-product-overlay');


        // Закрыть корзину при нажатии на overlay
        window.addEventListener('click', (event) => {
            if (event.target === popupOverlay) {
                popupOverlay.classList.remove('active');
                document.body.classList.remove('no-scroll');
            }
        });

        popupCloseIcon.addEventListener('click', () => {
            popupOverlay.classList.remove('active');
            document.body.classList.remove('no-scroll');
        });

        $('.add-to-cart-form').on('submit', function(e) {
            e.preventDefault();

            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: $(this).serialize(),
                success: function(response, textStatus, xhr) {
                    if (xhr.status === 200) {
                        showPopup(response.product);
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert('Error! Status Code: ' + xhr.status);
                }
            });
        });

        const addtoCartBtns = document.querySelectorAll('.item-gallery-cart');

        addtoCartBtns.forEach(button => {
            button.addEventListener('click', () => {
                showPopup();
            });
        });

        function showPopup(data = null) {
            if (data === null) return;

            document.querySelector('.count-cart-item').textContent = '('+data.count_cart_item+')';
            document.querySelector('.cart-quantity').textContent = data.count_cart_item;

            // Update the popup content with the product data
            document.querySelector('.add-product-item-header h4').textContent = data.name;
            document.querySelector('.add-product-item-price').textContent = data.price;
            document.querySelector('.add-product-item-img img').src = data.image;

            popupOverlay.classList.add('active');
            document.body.classList.add('no-scroll');
        }

        // Add to cart popup end ============================================================================================================================================================

    });
</script>
@endpush
