@if($edit)
    <div class="mceNonEditable component-container" data-component-key="bestSellers">
<a href="#" class="btn btn-danger pull-right delete-component">X</a>
        <h4>@lang('hilco::app.best_sellers')</h4>
        <p>@lang('hilco::app.displays_best_selling_families_that_are_children_of_this_container')</p>
    </div>
@endif

@if($script)
    <script type="text/javascript">
        registerComponent('bestSellers', {
            menuText: '@lang('hilco::app.best_sellers')',
            bladeTemplate: 'hilco::components.bestSellers',
            init: function (body) {

            },
            serialize: function (componentNode) {
                return {};
            },
        });
    </script>
@endif

@if($view)
    @if(isset($bestSellers) && count($bestSellers))
        <div class="row container center-block">
            <div class="col-md-12">
                <div class="panel panel-primary">
                    <div class="panel-heading">
                        <h3 class="panel-title text-center">@lang('app.best_sellers')</h3>
                    </div>
                    <div class="panel-body">
                        <div id="best-sellers-carousel" class="owl-carousel owl-theme">
                            @php $position = 0;@endphp
                            @foreach ($bestSellers as $family)
                                @php $position++;@endphp
                                @php $firstCollection = $family->webCollections->first(); @endphp
                                @php $firstCategory = (isset($firstCollection)) ? $firstCollection->webCategories->first() : null; @endphp
                                @php $firstGroup = (isset($firstCategory)) ? $firstCategory->webGroups->first() : null; @endphp
                                @php $brandName = (isset($firstGroup)) ? $firstGroup->name : ""; @endphp
                                @include('partials.family-block', ['family' => $family, 'captionClass' => 'h4', 'containerStyle' => 'display: none;', 'list' => 'bestSellers','position' => $position, 'visibleWebPart' => $family->visibleWebParts->first(), 'brandName' => $brandName])
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <script type="text/javascript">
            var bestSellersPricingData = {!! $bestSellersPricingData !!};
            $('#best-sellers-carousel').find('.quantity-select-box').each(function(){
                $(this).on('change', function(){
                    if (typeof $(this).data('lowstock-max') !== 'undefined'){
                        var maxQuantity = $(this).data('lowstock-max');
                        if($(this).val() > maxQuantity){
                            var message = '{!! trans('messages.only_x_units_remaining', ['count' => '__UNITS__']) !!}'.replace('__UNITS__', maxQuantity);
                            toastr.warning(message);
                            $(this).val(maxQuantity);
                        }
                    }
                });
            });

            $(document).ready(function() {
                var bestSellersCarousel = $('#best-sellers-carousel');
                bestSellersCarousel.on({
                    'initialized.owl.carousel': function() {
                        bestSellersCarousel.find('.family-block-item').show();
                    }
                }).owlCarousel({
                    autoplay: true,
                    autoplayTimeout: 3500,
                    autoplayHoverPause: true,
                    loop: true,
                    responsive: {
                        0: {
                            items: 1,
                        },
                        320: {
                            items: 1
                        },
                        480: {
                            items: @if(auth()->user()) 2 @else 2 @endif,
                        },
                        768: {
                            items: @if(auth()->user()) 3 @else 3 @endif,
                        },
                        992: {
                            items: @if(auth()->user()) 3 @else 3 @endif,
                        },
                        1440: {
                            items: @if(auth()->user()) 4 @else 4 @endif,
                        },
                    },
                });

                @if(auth()->user())
                    @if(count($bestSellers))
                        getBestPricesAsync();
                        getBestATPsAsync();
                    @endif
                @endif
            });

            function getBestPricesAsync(){
                var pricingData = bestSellersPricingData;
                var pricingResponse = null;

                $.ajax({
                    type: 'POST',
                    url: '{{route('families.prices')}}',
                    data: {
                        _token: _csrf_token,
                        pricingData: pricingData
                    },
                    success: function(data){
                        pricingResponse = data;
                    },
                    error: function(){
                        $.each(pricingData, function(familyId, data){
                            if($('#best-sellers-carousel').find('.price-loader-' + familyId).is(":visible")) {
                                $('#best-sellers-carousel').find('.item-price-' + familyId).append('<strong class="price-unavailable" style="color: red">{!! trans('messages.temporarily_unavailable') !!}</strong>');
                                $('#best-sellers-carousel').find('.price-loader-' + familyId).hide();
                            }

                            if($('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').length) {
                                $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').prop('disabled', true);
                                $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').prop('disabled', true);
                                $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').val(0);
                            }
                        });
                    },
                    complete: function(){
                        $.each(pricingResponse, function(familyId, prices){
                            if($('#best-sellers-carousel').find('.price-loader-' + familyId).is(":visible")) {
                                if (prices === '{!! trans('messages.temporarily_unavailable') !!}') {
                                    if($('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').length) {
                                        $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').prop('disabled', true);
                                        $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').prop('disabled', true);
                                        $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').val(0);
                                    }
                                    $('#best-sellers-carousel').find('.item-price-' + familyId).append('<strong class="price-unavailable" style="color: red">{!! trans('messages.temporarily_unavailable') !!}</strong>');
                                }
                                else {
                                    if(prices['minPrice'] != prices['maxPrice']){
                                        $('#best-sellers-carousel').find('.item-price-' + familyId).append(prices['minPriceFormatted'] + ' - ' + prices['maxPriceFormatted']);
                                    }else{
                                        $('#best-sellers-carousel').find('.item-price-' + familyId).append(prices['minPriceFormatted']);
                                    }
                                }
                                $('#best-sellers-carousel').find('.price-loader-' + familyId).hide();
                            }
                        });
                    }
                });
            }

            function getBestATPsAsync(){
                var atpData = {};
                var atpResponse = null;

                @foreach($bestSellers as $family)
                    @if(count($family->visibleWebParts) == 1)
                        @foreach($family->visibleWebParts as $webPart)
                            @if($webPart->part->inventoryItems->where('part_stat', '!=', \Hilco\Models\InventoryItem::STATUS_DONOTREORDER)->count() == 0)
                            atpData['{!! $family->id !!}'] = '{!! $webPart->part_number !!}';
                            @endif
                        @endforeach
                    @endif
                @endforeach

                if(Object.keys(atpData).length > 0){
                    $.ajax({
                        type: 'POST',
                        url: '{{route('families.atps')}}',
                        data: {
                            _token: _csrf_token,
                            atpData: atpData
                        },
                        success: function(data){
                            atpResponse = data;
                        },
                        complete: function(){
                            $.each(atpResponse, function (familyId, atpInfo){
                                if(atpInfo.status == "lowStock"){
                                    if(atpInfo.stock == 0){
                                        $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').prop('disabled', true);
                                        $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').prop('disabled', true);
                                        $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').val(0);
                                    }else{
                                        $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').attr("data-lowstock-max", atpInfo.stock);
                                    }
                                }else if(atpInfo.status == "unknown"){
                                    $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').prop('disabled', true);
                                    $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').prop('disabled', true);
                                    $('#best-sellers-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').val(0);
                                }
                            });
                        }
                    });
                }
            }
        </script>
    @endif
@endif