@extends($activeTemplate.'layouts.frontend')
@section('content')
<!-- ==================== Our Products Start Here ==================== -->
<section class="echommerce-products py-80 section-bg">
    <div class="container">
        <div class="row gy-5 justify-content-center">
            <div class="col-lg-8">
                <div class="row gy-4 justify-content-center filteredProduct">
                    @foreach ($products as $product)
                    <div class="col-lg-4 col-md-6 col-sm-6">
                        <div class="ecommerce-product">
                            <div class="ecommerce-product__thumb">
                                <a href="{{ route('product.details', ['slug' => slug($product->name), 'id' => $product->id])}}">
                                    <img src="{{ getImage(getFilePath('product').'/'.@$product->productImages[0]->image)}}" alt="product Image">
                                </a>
                                @if(isset($product->discount))
                                <div class="product-badge bg--danger">
                                    <p>{{$product->discount}}%</p>
                                </div>
                                @else
                                <div class="product-badge bg--base">
                                    <p>@lang('New')</p>
                                </div>
                                @endif
                                <div class="product-action-wrap">
                                    <ul>
                                        <li class="cart-btn" >
                                            <button class="flyingaddToCart"  data-id="{{$product->id}}" data-quantity="1" ><i class="fas fa-cart-plus"></i></button>
                                             <span class="tooltip">@lang('Add to Cart')</span>
                                        </li>
                                        <li class="cart-btn">
                                            <button class="productModalBtn" data-id="{{$product->id}}"><i class="fas fa-eye" ></i></button>
                                            <span class="tooltip">@lang('Quick View')</span>
                                        </li>
                                        <li class="cart-btn">
                                            <button class="addToWishList" data-id="{{$product->id}}"><i class="fas fa-heart"></i></button>
                                            <span class="tooltip">@lang('Add To Wishlist')</span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div class="ecommerce-product__content">
                                <div class="review-wrap d-flex align-items-center mb-2">
                                    {{-- <ul class="rating-list justify-content-center"> --}}
                                        @php
                                        $averageRatingHtml = calculateAverageRating($product->id);
                                        echo $averageRatingHtml['ratingHtml'];
                                        @endphp
                                    {{-- </ul> --}}
                                    <p class="review-count">({{__( $averageRatingHtml['reviewCount'])}})</p>
                                </div>
                                <h3 class="title">
                                    <a href="{{ route('product.details', ['slug' => slug($product->name), 'id' => $product->id])}}">
                                        @if(strlen(__($product->name)) >22)
                                        {{substr( __($product->name), 0,22).'...' }}
                                        @else
                                        {{__($product->name)}}
                                        @endif
                                    </a>
                                </h3>
                                <div class="price-wrap">
                                    @if(isset($product->discount))
                                    <span class="product-price old">{{__($general->cur_sym)}} {{showAmount($product->price)}}</span>
                                    <span class="product-price new">{{ $general->cur_sym }} {{ showAmount(($product->price)- ($product->price * $product->discount/100 )) }}</span>
                                    @else
                                    <span class="product-price new">{{__($general->cur_sym)}} {{showAmount($product->price)}}</span>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>

                <div class="row mt-4">
                    @if ($products->hasPages())
                    <div class="col-md-12 d-flex justify-content-center">
                        {{ paginateLinks($products) }}
                    </div>
                    @endif
                </div>

            </div>
            <div class="col-lg-4">
                <!-- ============================= Blog Details Sidebar Start ======================== -->
                <div class="blog-sidebar-wrapper">
                    <div class="blog-sidebar">
                        <h5 class="blog-sidebar__title"> @lang('Categories') </h5>
                        <ul class="text-list style-tag">
                            @foreach($categories as $category)
                            <li class="text-list__item"><a href="{{route('filter.category.products',$category->id)}}" class="text-list__link"> {{__($category->name)}}</a></li>
                            @endforeach
                        </ul>
                        <div class="row mt-4">
                            @if ($categories->hasPages())
                            <div class="col-md-12 d-flex justify-content-center">
                                {{ paginateLinks($categories) }}
                            </div>
                            @endif
                        </div>
                    </div>

                    <div class="blog-sidebar">
                        <h5 class="blog-sidebar__title"> @lang('Brands') </h5>
                        <ul class="text-list style-tag">
                            @foreach($brands as $brand)
                            <li class="text-list__item"><a href="{{route('filter.brand.products',$brand->id)}}" class="text-list__link"> {{__($brand->name)}}</a></li>
                            @endforeach
                        </ul>
                        <div class="row mt-4">
                            @if ($categories->hasPages())
                            <div class="col-md-12 d-flex justify-content-center">
                                {{ paginateLinks($categories) }}
                            </div>
                            @endif
                        </div>
                    </div>
                </div>
                <!-- ============================= Blog Details Sidebar End ======================== -->

            </div>
        </div>
    </div>
</section>
<!-- ==================== Our Products End Here ============ -->

{{-- product modal --}}
<section id="productModal" class="product-details-area py-80 modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
      <div class="modal-content">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        <div class="row gy-4 align-items-center">
          <div class="col-lg-6">
            <div class="product-details-left align-items-center">
              <div class="product-details-left__nav">
                <ul class="nav nav-tabs" id="myTab" role="tablist">
                </ul>
              </div>
              <div class="product-details-left__content">
                <div class="tab-content" id="myTabContent">
                </div>
              </div>
            </div>
          </div>
          <div class="col-lg-6">
            <div class="product-details">
              <div class="product-details__content">
                <span class="title m_product_title"></span>
                <div class="review-wrap d-flex align-items-center mb-2">
                  <p class="stock m_stock me-2"></p>

                  <ul class="rating-list m_rating-list justify-content-center">
                  </ul>
                  <p class="review-count m_review-count"></p>

                </div>
                <p class="desc mb-2 m_product_desc"></p>
                <div class="price-wrap m_price-wrap mb-2"></div>
                <div class="about-bottom mb-3">
                    <ul>
                        <li class="mb-2"><i class="fa-solid fa-circle-check"></i> <p>@lang('Hurry up! only ')<span class="m_left_item"></span> @lang('items left')</p></li>
                    </ul>

                </div>
                <div class="project-details mb-3">
                  <div class="quantity_box">
                    <button type="button" class="sub"><i class="fa fa-minus"></i></button>
                    <input type="number" id="quantityInput" value="1">
                    <button type="button" class="add"><i class="fa fa-plus"></i></button>
                  </div>
                  <button class="btn--sm btn--base outline hover-white-c mr-2 mb-10 addToCart">@lang('Add To Cart')</button>
                  <button class="btn--sm btn--base outline hover-white-c mb-10 ms-2 buyNow">@lang('Buy Now')</button>
                </div>
                <div class="product-details__bottom mb-2">

                    <div class="col-sm-8">
                        <div class="form-group mb-3">
                            <label class="form--label">@lang('Shipping')</label>
                            <div class="col-sm-12">
                                <select class="select form--control">
                                    @foreach($shippings as $item)
                                       <option >{{ __($item->name) }} --> @lang('within') {{__($item->day)}} @lang('days')</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                    </div>
                  <div class="product-details__number">
                    <div class="blog-details__share mt-2 mb-2 d-flex align-items-center flex-wrap">
                      <h5 class="social-share__title mb-0 me-sm-3 me-1 d-inline-block">@lang('Share This')</h5>
                      <ul class="social-list blog-details">
                        <li class="social-list__item"><a href="#" class="social-list__link facebook-share"><i class="fab fa-facebook-f"></i></a></li>
                        <li class="social-list__item"><a href="#" class="social-list__link twitter-share"> <i class="fab fa-twitter"></i></a></li>
                        <li class="social-list__item"><a href="#" class="social-list__link linkedin-share"> <i class="fab fa-linkedin-in"></i></a></li>
                        <li class="social-list__item"><a href="#" class="social-list__link instagram-share"> <i class="fab fa-instagram"></i></a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
</section>


@endsection

@push('script')
<script>
      (function($){
        "use strict";

        // Set default quantity to 1
        $('.addToCart').data('quantity', 1);

        // sub quantity
        $('.quantity_box').on('click', '.sub', function() {
            var quantityInput = $('#quantityInput');
            var quantity = parseInt(quantityInput.val());

            if (quantity > 1) {
                quantityInput.val(quantity);
                $('.addToCart').data('quantity', quantity);
            }
        });

        // add quantity
        $('.quantity_box').on('click', '.add', function() {
            var quantityInput = $('#quantityInput');
            var quantity = parseInt(quantityInput.val());

            quantityInput.val(quantity);
            $('.addToCart').data('quantity', quantity);
        });

        // modal open
        $('.productModalBtn').on('click', function () {
                var modal = $('#productModal');
                modal.modal('show');

                var productId = $(this).data('id');
                getProductInfo(productId)


        });

        // get modal into product info
        function getProductInfo(productId) {
            $.ajax({
                url: '{{ route("getmodal.info") }}',
                type: 'get',
                data: {
                    productId: productId,
                },
                success: function(response) {

                    $('.m_product_title').text(response.product.name);

                    $('.m_product_desc').text(response.product.short_desc.substr(0, 200) + '...');

                    if (response.product.quantity > 0) {
                    $('.m_stock').text('In Stock: ' + response.product.quantity);
                    } else {
                    $('.m_stock').text('Out of Stock');
                    }

                    $('.m_left_item').text(response.product.quantity);

                    var productId = response.product.id;
                    $('.addToCart').data('id', productId);
                    $('.buyNow').data('id', productId);


                    var productPrice = response.product.price;
                    var discountPercentage = response.product.discount;

                    var discount = productPrice - (productPrice * discountPercentage / 100);

                    if (!discountPercentage) {
                        $('.m_price-wrap').html(
                            '<span class="product-price">$' + Number(productPrice).toFixed(2) + '</span>'
                        );
                    } else {
                        $('.m_price-wrap').html(
                            '<span class="product-price old">$' + Number(productPrice).toFixed(2) + '</span>' +
                            '<span class="product-price new">$' + discount + '</span>'
                        );
                    }



                    var averageRatingData = JSON.parse(response.averageRatingHtml);
                    // Update the rating HTML
                    $('.m_rating-list').html(averageRatingData.ratingHtml);

                    // Update the review count
                    $('.m_review-count').text('(' + averageRatingData.reviewCount + ')');


                    // Store the product images in an array
                    var productImages = response.productImages;

                    if (Array.isArray(productImages) && productImages.length > 0) {
                    var tabLinks = '';
                    var tabContent = '';

                    productImages.forEach(function(image, index) {
                        var activeClass = index === 0 ? 'active' : '';

                        var tabId = 'tab-' + index;
                        var tabPaneId = 'tab-pane-' + index;

                        tabLinks += '<li class="nav-item" role="presentation">' +
                                    '<button class="nav-link ' + activeClass + '" id="' + tabId + '" data-bs-toggle="tab" data-bs-target="#' + tabPaneId + '" type="button" role="tab" aria-controls="' + tabPaneId + '" aria-selected="' + (index === 0 ? 'true' : 'false') + '">' +
                                    '<img src="' + image + '" alt="">' +
                                    '</button>' +
                                    '</li>';

                        tabContent += '<div class="tab-pane fade' + (index === 0 ? ' show active' : '') + '" id="' + tabPaneId + '" role="tabpanel" aria-labelledby="' + tabId + '" tabindex="0">' +
                                    '<div class="product-details-left__thumb">' +
                                    '<img src="' + image + '" alt="">' +
                                    '</div>' +
                                    '</div>';
                    });

                    $('#myTab').html(tabLinks);
                    $('#myTabContent').html(tabContent);

                    $('.nav-link').on('click', function() {
                        $('.nav-link').removeClass('active');
                        $(this).addClass('active');
                    });
                    } else {
                    console.log('productImages is not an array');
                    }

                        // Access and use the share links
                    var shareLinks = response.shareLinks;
                    $('.facebook-share').attr('href', shareLinks.facebook);
                    $('.twitter-share').attr('href', shareLinks.twitter);
                    $('.linkedin-share').attr('href', shareLinks.linkedin);
                    $('.instagram-share').attr('href', shareLinks.instagram);


                }
            });
        }

        // add to cart
        $(document).on('click', '.addToCart', function() {
            var productId = $(this).data('id');
            var quantity = $(this).data('quantity');

                $.ajax({
                url: '{{ route("cart.add") }}',
                type: 'get',
                data: {
                    product_id: productId,
                    quantity: quantity,
                },
                success: function(response) {
                    if (response.hasOwnProperty('message')) {
                    Toast.fire({
                        icon: 'success',
                        title: response.message
                    });
                    updateCartItemCount(response.cartItemCount);

                    }
                        // Hide the modal
                        $('#productModal').modal('hide');
                        $('#quantityInput').val(1);

                },
                error: function(xhr, status, error) {
                    if (xhr.status === 422) {
                        var errorMessage = xhr.responseJSON.error;
                        Toast.fire({
                            icon: 'error',
                            title: errorMessage
                        });
                    } else {
                        var errorMessage = 'Error occurred while adding the product to cart.';
                        Toast.fire({
                            icon: 'error',
                            title: errorMessage
                        });
                    }
                }
                });
        });

        function updateCartItemCount(count) {
            $('#cartItem').text(count);
        }
      // end add to cart


        // add to wishlist
        $(document).on('click', '.addToWishList', function() {
            var productId = $(this).data('id');
            $.ajax({
                url: '{{ route("wishlist.add") }}',
                type: 'get',
                data: {
                    product_id:productId,
                },
                success: function(response) {

                    if (response.hasOwnProperty('message')) {
                    Toast.fire({
                        icon: 'success',
                        title: response.message
                    });
                    updateWishListCount(response.wishlistCount);
                    }else{
                        Toast.fire({
                        icon: 'warning',
                        title: response.error
                    });
                    }
                },
                error: function(xhr, status, error) {
                    var errorMessage = 'Error occurred while adding the product to wishlist.';
                    Toast.fire({
                    icon: 'error',
                    title: errorMessage
                    });
                }
            });
        });

        function updateWishListCount(count) {
            $('#wishlistItem').text(count);
        }
        // end wishlist


         // buy now add product
         $(document).on('click', '.buyNow', function() {
            var productId = $(this).data('id');
            var quantity = 1;

            $.ajax({
                url: '{{ route("cart.add") }}',
                type: 'get',
                data: {
                    product_id: productId,
                    quantity: quantity,
                },
                success: function(response) {
                    if (response.hasOwnProperty('message')) {
                        Toast.fire({
                            icon: 'success',
                            title: response.message
                        });
                        updateCartItemCount(response.cartItemCount);
                    }

                    // Hide the modal
                    $('#productModal').modal('hide');
                    $('#quantityInput').val(1);

                    // redirect checkout page
                    window.location.href = '{{ route("get.checkout") }}';
                },
                error: function(xhr, status, error) {
                    if (xhr.status === 422) {
                        var errorMessage = xhr.responseJSON.error;
                        Toast.fire({
                            icon: 'error',
                            title: errorMessage
                        });
                    } else {
                        var errorMessage = 'Error occurred while adding the product to cart.';
                        Toast.fire({
                            icon: 'error',
                            title: errorMessage
                        });
                    }
                }
            });
        });
        // end buy now add product


        // flying add to cart
        $(document).on('click', '.flyingaddToCart', function() {
            var productId = $(this).data('id');
            var quantity = $(this).data('quantity');

            var productImage = $(this).closest('.ecommerce-product__thumb').find('img');

            // any error face then flying animation off
            if (productImage.hasClass('out-of-stock')) {
                return;
            }

            // Get the position of the product image
            var imagePosition = productImage.offset();
            var imageClone = productImage.clone();

            // Append the cloned image to the body with absolute positioning
            imageClone.css({
                position: 'absolute',
                top: imagePosition.top,
                left: imagePosition.left,
                width: productImage.width(),
                height: productImage.height(),
                zIndex: 9999
            }).appendTo('body');

            // Animate the cloned image to the cart item position
            imageClone.animate({
                top: $('#cartItem').offset().top,
                left: $('#cartItem').offset().left,
                opacity: 0.3,
                width: 20,
                height: 20
            }, 1000, function() {
                // Remove the cloned image
                $(this).remove();
            });

            $.ajax({
                url: '{{ route("cart.add") }}',
                type: 'get',
                data: {
                    product_id: productId,
                    quantity: quantity,
                },
                success: function(response) {
                    if (response.hasOwnProperty('message')) {
                        Toast.fire({
                            icon: 'success',
                            title: response.message
                        });
                        updateCartItemCount(response.cartItemCount);
                    }

                    // Hide the modal
                    $('#productModal').modal('hide');
                    $('#quantityInput').val(1);
                },
                error: function(xhr, status, error) {
                    if (xhr.status === 422) {
                        var errorMessage = xhr.responseJSON.error;
                        Toast.fire({
                            icon: 'error',
                            title: errorMessage
                        });
                    } else {
                        var errorMessage = 'Error occurred while adding the product to cart.';
                        Toast.fire({
                            icon: 'error',
                            title: errorMessage
                        });
                    }

                    // Remove the cloned image if there is an error
                    imageClone.remove();
                }
            });
        });

        function updateCartItemCount(count) {
            $('#cartItem').text(count);
        }
        // end flying add to cart


    })(jQuery);
</script>
@endpush

