@extends('shop::layouts.master')

@section('page_title')
    {{ trim($product->meta_title) != "" ? $product->meta_title : $product->name }}
@stop

@section('seo')
    <meta name="description" content="{{ trim($product->meta_description) != "" ? $product->meta_description : \Illuminate\Support\Str::limit(strip_tags($product->description), 120, '') }}"/>

    <meta name="keywords" content="{{ $product->meta_keywords }}"/>

    {{-- @if (core()->getConfigData('catalog.rich_snippets.products.enable'))
        <script type="application/ld+json">
            {{ app('Webkul\Product\Helpers\SEO')->getProductJsonLd($product) }}
        </script>
    @endif --}}

    <?php $productBaseImage = productimage()->getProductBaseImage($product); ?>

    <meta name="twitter:card" content="summary_large_image" />

    <meta name="twitter:title" content="{{ $product->name }}" />

    <meta name="twitter:description" content="{!! htmlspecialchars(trim(strip_tags($product->meta_description))) !!}" />

    <meta name="twitter:image:alt" content="" />

    <meta name="twitter:image" content="{{ $productBaseImage['medium_image_url'] }}" />

    <meta property="og:type" content="og:product" />

    <meta property="og:title" content="{{ $product->name }}" />

    <meta property="og:image" content="{{ $productBaseImage['medium_image_url'] }}" />

    <meta property="og:description" content="{!! htmlspecialchars(trim(strip_tags($product->description))) !!}" />

    <meta property="og:url" content="{{ route('shop.productOrCategory.index', $product->url_key) }}" />

@stop
@push("css")
{{--<link rel="stylesheet" href="{{bagisto_asset('styles/categories-tv.css')}}" />--}}
{{--<link rel="stylesheet" href="{{bagisto_asset('styles/cart.css')}}" />--}}

<link rel="stylesheet" href="{{bagisto_asset('styles/swiper-bundle.min.css')}}">
<link rel="stylesheet" href="{{bagisto_asset('styles/product.css')}}" />
@endpush

@section('content-wrapper')
    <svg display='none'>
        <symbol id="star" viewBox="0 0 16 16">
            <path id="icon__" data-name="icon ()" d="M15.958,6.542a.858.858,0,0,0-.731-.609l-4.619-.438L8.782,1.035a.837.837,0,0,0-1.565,0L5.392,5.495.773,5.932a.86.86,0,0,0-.731.609.914.914,0,0,0,.248.943L3.781,10.68,2.751,15.411a.907.907,0,0,0,.331.916.819.819,0,0,0,.935.043L8,13.885l3.982,2.485a.821.821,0,0,0,.935-.043.907.907,0,0,0,.331-.916L12.218,10.68,15.71,7.485a.914.914,0,0,0,.248-.943Zm-7.881,7.3" transform="translate(0 -0.496)"/>
        </symbol>
    </svg>
@inject ('productViewHelper', 'Webkul\Product\Helpers\View')
@php
        $wishListHelper = app( 'Webkul\Customer\Helpers\Wishlist');
        $optionRepository = app('Webkul\Attribute\Repositories\AttributeOptionRepository');
        $brand = $optionRepository->findOneWhere(['attribute_id'=>25,'id'=>$product->brand]);
        $isLiked = $wishListHelper->getWishlistProduct($product);
@endphp
    <main class="item container">
        <h1 class="item-title">{{ $product->name }}</h1>
        <product-view>
            @csrf()
            @include ('shop::products.view.gallery')
            <div class="upper-section-middle">
                <div class="upper-section-middle-header-top">
                    <span class="header-title">{{__('shop::app.checkout.onepage.price')}}:</span>
                    <div class="header-char-section">
                        @include ('shop::products.price', ['product' => $product])
                    </div>

                    @if(isset($brand))
                    <span class="header-title no-mobile">{{__('shop::app.products.brand')}}:</span>
                    <div class="header-logo no-mobile">
                        <img src="{{$brand->swatch_value_url}}" alt="logo">
                    </div>
                    @endif
                    @include ('shop::products.view.configurable-options')

                </div>
                @include ('shop::products.view.attributes')
            </div>
            <div class="upper-section-right upper-section-right-wrapper" >
                @php $showbox = $product->getTypeInstance()->showQuantityBox(); @endphp

                    <quantity-changer v-if="!isMobile() && {{$showbox}}"></quantity-changer>
                    <input type="hidden" name="quantity" value="1" v-else>
                <div class="upper-section-right-bottom">
                    <button type="submit" class="add-to-cart addtocart" {{ ! $product->isSaleable() ? 'disabled' : '' }} >
                    {{ $product->type == 'booking' ? __('shop::app.products.book-now') : __('shop::app.products.add-to-cart') }}
                    </button>
                    @if (core()->getConfigData('catalog.products.storefront.buy_now_button_display'))
                        <span class="divider" v-if="!isMobile()">{{__('shop::app.products.or')}}</span>
                        <button type="submit" class="order-now buynow"  {{ ! $product->isSaleable(1) ? 'disabled' : '' }}>
                            {{ __('shop::app.products.buy-now') }}
                        </button>
                    @endif

                    @if(core()->getConfigData('general.content.shop.wishlist_option'))

                        <form class="wishlist-{{ $product->product_id }}" action="{{ route('customer.wishlist.add', $product->product_id) }}" method="POST"
                            style="visibility: hidden; height: 0; width: 0;">
                            @csrf
                        </form>

                    <button type="button" class="upper-section-right-bottom-footer favorite" v-if="!isMobile()"
                        @guest('customer')
                            onclick="document.querySelector('.logged-false').click(); return false;"
                        @else
                            onclick="document.querySelector('.wishlist-{{ $product->product_id }}').submit();"
                        @endguest
                    >
                        <div class="upper-section-right-bottom-footer-img">
                            <img src="{{bagisto_asset($isLiked?'icons/heart.svg':'icons/love.svg')}}" alt="favorite" width="24" height="24">
                        </div>
                        <span class="upper-section-right-bottom-footer-text">{{__($isLiked? 'shop::app.customer.account.wishlist.remove-wishlist-text':'shop::app.customer.account.wishlist.add-wishlist-text')}}</span>
                    </button>
                    @endif
                </div>
            </div>
        </product-view>
        <div class="lower-section" id="spesifications">
            <div class="lower-section-title">
                <div class="title-wrapper">
                    <h2 class="lower-section-title-text initial-trigger">{{__('shop::app.products.description')}}</h2>
                    <h2 class="lower-section-title-text animation-trigger">{{ __('shop::app.products.specification') }}</h2>
                    <h2 class="lower-section-title-text animation-end-trigger">{{__('shop::app.layouts.reviews')}}</h2>
                </div>
                <div class="lower-section-bar">
                    <div class="bar-slider initial"></div>
                </div>
            </div>
            <div class="lower-section-content-container">
                <div class="lower-section-content">
                    <div class="lower-section-content-wrapper">
                        {!! $product->short_description !!}

                    </div>
                </div>
                <div class="lower-section-content lower-section-content-second">
                    <div class="upper-section-middle-header-bottom">
                        <div class="header-char-section">
                            {!! $product->description !!}
                        </div>
                    </div>
                </div>
                <reviews></reviews>

            </div>
        </div>
{{--        @include ('shop::products.view.related-products')--}}

{{--        @include ('shop::products.view.up-sells')--}}
    </main>

@endsection

@push('scripts')

    <script type="text/x-template" id="product-view-template">
        <form method="POST" class="item-inner upper-section" id="product-form" action="{{ route('cart.add', $product->product_id) }}" @click="onSubmit($event)">

            <input type="hidden" name="is_buy_now" v-model="is_buy_now">
            <input type="hidden" name="product_id" value="{{ $product->product_id }}">
            <slot></slot>

        </form>
    </script>

    <script type="text/x-template" id="quantity-changer-template">
        <div class="right-top-line" :class="[errors.has(controlName) ? 'has-error' : '']">
            <span class="right-top-title">{{ __('shop::app.products.quantity') }}</span>
            <div class="quantity-wrapper">
                <button type="button" class="subtract" @click="decreaseQty()"><span>–</span></button>
                <input
                    ref="quantityChanger"
                    :name="controlName"
                    :model="qty"
                    class="quantity"
                    v-validate="validations"
                    data-vv-as="&quot;{{ __('shop::app.products.quantity') }}&quot;"
                    @keyup="setQty($event)">
                <button class="add" type="button" @click="increaseQty()"><span>+</span></button>
                <span class="control-error" v-if="errors.has(controlName)">@{{ errors.first(controlName) }}</span>
            </div>
{{--            <span class="quantity-container">--}}
{{--                <button type="button" class="decrease" @click="decreaseQty()">-</button>--}}

{{--                <input--}}
{{--                    ref="quantityChanger"--}}
{{--                    :name="controlName"--}}
{{--                    :model="qty"--}}
{{--                    class="control"--}}
{{--                    v-validate="validations"--}}
{{--                    data-vv-as="&quot;{{ __('shop::app.products.quantity') }}&quot;"--}}
{{--                    @keyup="setQty($event)">--}}

{{--                <button type="button" class="increase" @click="increaseQty()">+</button>--}}

{{--                <span class="control-error" v-if="errors.has(controlName)">@{{ errors.first(controlName) }}</span>--}}
{{--            </span>--}}
        </div>
    </script>

    <script type="text/x-template" id="reviews-template">
        <div class="lower-section-content lower-section-content-third">
            @auth
                <!-- Add review -->
                <form v-show="showReviewForm" id="review-form" class="lower-section-content-top" @submit.prevent="addReview('review')" data-vv-scope="review">
                    @csrf
                    <h3 class="lower-section-content-title">{{ __('shop::app.reviews.add-review-page-title') }}</h3>

                    <textarea class="comment-text"
                        v-validate="'required'"
                        placeholder="Оставить отзыв о товаре"
                        data-vv-as="&quot;{{ __('admin::app.customers.reviews.comment') }}&quot;"
                        value="{{ old('comment') }}"
                        name="comment"
                        v-model="comment"
                    ></textarea>
                    <span class="control-error" v-if="errors.has('review.comment')">@{{ errors.first('review.comment') }}</span>

                    <div class="button-rating">
                        <div class="rating-range">

                            <input class="hidden-range" type="range" step="1" max="5" min="1"
                                v-model="rateValue"
                                v-validate="'min:1|max:5|required'"
                                data-vv-as="&quot;{{ __('admin::app.customers.reviews.rating') }}&quot;"
                                value="{{ old('rating') }}"
                                name="rating"
                            >


                            <div class="rating-btn" @click="changeRating(1)">
                                <svg class="star" :class="{'red': rateValue >= 1}">
                                    <use xlink:href="#star"></use>
                                </svg>
                            </div>
                            <div class="rating-btn" @click="changeRating(2)">
                                <svg class="star" :class="{'red': rateValue >= 2}">
                                    <use xlink:href="#star"></use>
                                </svg>
                            </div>
                            <div class="rating-btn" @click="changeRating(3)">
                                <svg class="star" :class="{'red': rateValue >= 3}">
                                    <use xlink:href="#star"></use>
                                </svg>
                            </div>
                            <div class="rating-btn" @click="changeRating(4)">
                                <svg class="star" :class="{'red': rateValue >= 4}">
                                    <use xlink:href="#star"></use>
                                </svg>
                            </div>
                            <div class="rating-btn" @click="changeRating(5)">
                                <svg class="star" :class="{'red': rateValue >= 5}">
                                    <use xlink:href="#star"></use>
                                </svg>
                            </div>
                        </div>
                        <span class="control-error" v-if="errors.has('review.rating')">@{{ errors.first('review.rating') }}</span>

                        <button class="submit-rating" type="submit">{{ __('shop::app.reviews.submit') }}</button>
                    </div>
                </form>
                <p v-show="!showReviewForm">{{__('shop::app.reviews.thanks_message')}}</p>
                <!-- Add review End -->
            @else
                    <div class="no-comments">
                        <button disabled>
                            {{__('shop::app.reviews.login_message')}}
                        </button>
                        <button>
                            <span>{{__('shop::app.reviews.sign-in')}}</span>
                            <div class="btn-img">
                                <img src="{{bagisto_asset('icons/in.svg')}}" alt="comment" />
                            </div>
                        </button>
                    </div>
            @endauth

            <div class="horizontal"></div>

            <!-- Reviews -->
            <div class="comment-section">
                <div v-for="review in reviews" class="comment-block">
                    <div class="comment-top-block">
                        <h3 class="comment-user">@{{ review.name }}</h3>
                        <div class="comment-rated">
                            <span class="rating-number">@{{ review.rating }}</span>
                            <div class="rated-range">
                                <div class="rated-btn">
                                    <svg class="rated-star" :class="{'red': review.rating >= 1}">
                                        <use xlink:href="#star"></use>
                                    </svg>
                                </div>
                                <div class="rated-btn">
                                    <svg class="rated-star" :class="{'red': review.rating >= 2}">
                                        <use xlink:href="#star"></use>
                                    </svg>
                                </div>
                                <div class="rated-btn">
                                    <svg class="rated-star" :class="{'red': review.rating >= 3}">
                                        <use xlink:href="#star"></use>
                                    </svg>
                                </div>
                                <div class="rated-btn">
                                    <svg class="rated-star" :class="{'red': review.rating >= 4}">
                                        <use xlink:href="#star"></use>
                                    </svg>
                                </div>
                                <div class="rated-btn">
                                    <svg class="rated-star" :class="{'red': review.rating >= 5}">
                                        <use xlink:href="#star"></use>
                                    </svg>
                                </div>
                            </div>
                        </div>
                    </div>
                    <h4 class="comment-date">@{{ normalizeDate(review.created_at) }}</h4>
                    <span class="comment">@{{ review.comment }}</span>
                    <div class="horizontal"></div>
                </div>
                <button v-show="checkLoadMore()" type="button" @click.prevent="loadMore">{{__('shop::app.reviews.loadMore')}}</button>
            </div>
            <!-- Reviews End -->

        </div>

    </script>

    <script>
        function isMobile() {
            return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i |
                /mobi/i.test(navigator.userAgent);
        }

        Vue.component('product-view', {

            template: '#product-view-template',

            inject: ['$validator'],

            data: function() {
                return {
                    is_buy_now: 0,
                }
            },

            methods: {
                onSubmit: function(e) {
                    if (e.target.getAttribute('type') != 'submit')
                        return;

                    e.preventDefault();

                    var this_this = this;

                    this.$validator.validateAll().then(function (result) {
                        if (result) {
                            this_this.is_buy_now = e.target.classList.contains('buynow') ? 1 : 0;

                            setTimeout(function() {
                                document.getElementById('product-form').submit();
                            }, 0);
                        }
                    });
                }
            }
        });

        Vue.component('quantity-changer', {
            template: '#quantity-changer-template',

            inject: ['$validator'],

            props: {
                controlName: {
                    type: String,
                    default: 'quantity'
                },

                quantity: {
                    type: [Number, String],
                    default: 1
                },

                minQuantity: {
                    type: [Number, String],
                    default: 1
                },

                validations: {
                    type: String,
                    default: 'required|numeric|min_value:1'
                }
            },

            data: function() {
                return {
                    qty: this.quantity
                }
            },

            mounted: function() {
                this.$refs.quantityChanger.value = this.qty > this.minQuantity
                    ? this.qty
                    : this.minQuantity;
            },

            watch: {
                qty: function (val) {
                    this.$refs.quantityChanger.value = ! isNaN(parseFloat(val)) ? val : 0;

                    this.qty = ! isNaN(parseFloat(val)) ? this.qty : 0;

                    this.$emit('onQtyUpdated', this.qty);

                    this.$validator.validate();
                }
            },

            methods: {
                setQty: function({ target }) {
                    this.qty = parseInt(target.value);
                },

                decreaseQty: function() {
                    if (this.qty > this.minQuantity)
                        this.qty = parseInt(this.qty) - 1;
                },

                increaseQty: function() {
                    this.qty = parseInt(this.qty) + 1;
                }
            }
        });

        Vue.component('reviews', {
            template: '#reviews-template',

            inject: ['$validator'],

            data () {
                return {
                    reviews: [],
                    nextPageUrl: '',
                    currentPage: undefined,
                    lastPage: undefined,
                    rateValue: '',
                    comment: '',
                    showReviewForm: true,
                    locale: '{{ app()->getLocale() }}',
                    tmMonths: ['ýanwar', 'fewral', 'mart', 'aprel', 'maý',
                        'iýun', 'iýul', 'awgust', 'sentýabr', 'oktýabr', 'noýabr', 'dekabr']
                }
            },

            created() {
                this.fetchReviews('{{ route('shop.product.reviews.index', ['product_id' => $product->product_id]) }}')
            },

            methods: {
                fetchReviews(url) {
                    axios.get(url)
                    .then(res => {
                        this.reviews.push(...res.data.data)
                        this.nextPageUrl = res.data.next_page_url
                        this.currentPage = res.data.current_page
                        this.lastPage = res.data.last_page
                    })
                    .catch(err => console.log('error 500 vue component reviews fetch'))
                },

                normalizeDate(created_at) {

                    let month = this.locale == 'ru' ? new Date(created_at).toLocaleString(this.locale == 'ru', { month: 'long' }) : this.tmMonth(created_at)

                    let nDate = new Date(created_at).getDate() +
                        ' ' +
                        month +
                        ' ' +
                        new Date(created_at).getFullYear()

                    return nDate
                },

                tmMonth(created_at) {
                    return this.tmMonths[+new Date(created_at).getMonth()]
                },

                addReview(scope) {
                    let self = this;

                    this.$validator.validateAll(scope).then(result => {
                        if (result) {
                            console.log(self.comment)
                            axios.post('{{ route('shop.product.reviews.store', ['product_id' => $product->product_id]) }}', {
                                comment: self.comment,
                                rating: self.rateValue,
                                _token: document.querySelector('#reviewform input[name="_token"]')
                            })
                            .then(res => {
                                self.showReviewForm = false
                            })
                            .catch(err => {
                                console.log('error 500 vue component reviews add')
                            })
                        } else {
                            eventBus.$emit('onFormError')
                        }
                    })


                },

                changeRating(rateValue) {
                    this.rateValue = rateValue
                },

                loadMore() {
                    this.fetchReviews(this.nextPageUrl)
                },

                checkLoadMore() {
                    if(this.reviews.length > 0) {
                        return this.currentPage != this.lastPage
                    } else return false
                }
            }
        });


        $(document).ready(function() {
            // var addTOButton = document.getElementsByClassName('add-to-buttons')[0];
            // document.getElementById('loader').style.display="none";
            // addTOButton.style.display="flex";
            // LOWER SECTION BAR =======================
            let barTrigger = document.querySelector('.initial-trigger');
            let barTrigger2 = document.querySelector('.animation-trigger');
            let barTrigger3 = document.querySelector('.animation-end-trigger');
            let barEl = document.querySelector('.bar-slider');
            let descEl = document.querySelector('.lower-section-content');
            let charEl = document.querySelector('.lower-section-content-second');
            let commentEl = document.querySelector('.lower-section-content-third');
            let more_specifivations = document.querySelector('#more');
            const list = ['animating', 'animated'];
            const unList = ['animating', 'initial'];
            barTrigger.addEventListener('click', () => {
                descEl.style.display = 'block';
                charEl.style.display = 'none';
                commentEl.style.display = 'none';
                barEl.classList.remove('ending');
                barEl.classList.remove('animated');
                barEl.classList.add('initial');
            });

            barTrigger2.addEventListener('click', () => {
                descEl.style.display = 'none';
                charEl.style.display = 'block';
                commentEl.style.display = 'none';
                barEl.classList.remove('ending');
                barEl.classList.remove('initial');
                barEl.classList.add('animated');
            });

            more_specifivations.addEventListener('click', () => {
                descEl.style.display = 'none';
                charEl.style.display = 'block';
                commentEl.style.display = 'none';
                barEl.classList.remove('ending');
                barEl.classList.remove('initial');
                barEl.classList.add('animated');
            });
            barTrigger3.addEventListener('click', () => {
                descEl.style.display = 'none';
                charEl.style.display = 'none';
                commentEl.style.display = 'block';
                barEl.classList.remove('initial');
                barEl.classList.remove('animated');
                barEl.classList.add('ending');
            });

// LOWER SECTION BAR end ===================
        });
        // /////////////////////////////////////////////////

        const sAll = (identifier) => {
            return document.querySelectorAll(identifier);
        };

        const trigs = sAll('.lower-section-title-text');

        trigs.forEach((trig) => {
            trig.addEventListener('click', () => {
                trigs.forEach((el) => el.classList.remove('active'));
                trig.classList.add('active');
            });
        });
    </script>

@endpush
