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

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

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

@if($view)
    @if(canUser('b2b-orders'))
        <div class="row container center-block">
            <div class="col-md-4">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">
                            <a href="{{ route('orders.list') }}" class="pull-right">@lang('app.see_all')</a>
                            @lang('app.recent_orders')
                        </h3>
                    </div>
                    <div class="panel-body" style="height: 260px; overflow-y: auto;">
                        @foreach(b2b()->activeCustomer()->recentOrders(4)->groupBy('order_date') as $orderDate => $orders)
                            <div class="row">
                                <div class="col-md-12 h4 nomargin">
                                    {{ date('D, M j Y', strtotime($orderDate)) }}
                                </div>
                            </div>
                            @foreach($orders as $order)
                                <div class="row">
                                    <div class="col-md-12">
                                        <div style="padding-left: 10px">
                                            <a href="{{ route('orders.genericDetails', [$order->hilco_order_number]) }}">{{ $order->hilco_order_number }}</a>
                                            ({{ $order->friendly_order_status }}) - {{ $order->total_quantity }} {{ \Illuminate\Support\Str::plural('item', $order->total_quantity) }},
                                            {{ $order->total_shipped }} @lang('app.shipped_lower_case')
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                            <hr style="margin: 5px;">
                        @endforeach
                    </div>
                </div>
            </div>
            <div class="col-md-8">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">
                            <a href="{{ route('orders.reorder') }}" class="pull-right">@lang('app.see_all')</a>
                            @lang('app.reorder_frequently_ordered_items')
                        </h3>
                    </div>
                    <div class="panel-body">
                        <div id="favorites-carousel" class="owl-carousel owl-theme">
                            @php $position = 0;@endphp
                            @foreach(b2b()->activeCustomer()->topPurchasedItems() 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
                                @if($family->visibleWebParts->count() > 0)
                                    @include('partials.family-block', ['family' => $family, 'captionClass' => 'h4', 'containerStyle' => 'display: none;', 'list' => 'topPurchased', 'position' => $position, 'visibleWebPart' => $family->visibleWebParts->first(), 'brandName' => $brandName])
                                @endif
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @if(\Route::has('orders.orderHistoryDataTable'))
        <script type="text/javascript">
            var topPurchasedItemsPricingData = {!! $topPurchasedItemsPricingData !!};
            $('#favorites-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 favoriteItemsCarousel = $('#favorites-carousel');
                favoriteItemsCarousel.owlCarousel({
                    autoplay: true,
                    autoplayTimeout: 5000,
                    loop: true,
                    responsive: {
                        0: {
                            items: 1,
                        },
                        320: {
                            items: 1
                        },
                        480: {
                            items: 1,
                        },
                        768: {
                            items: 2,
                        },
                        992: {
                            items: 2,
                        },
                        1440: {
                            items: 2,
                        },
                    },
                    smartSpeed: 1250,
                    onInitialized: function (event) {
                        $('#favorites-carousel').find('.family-block-item').show();
                        loadOwlCarouselDotDescs(event);
                    },
                    onResized: loadOwlCarouselDotDescs, // see function definition in B2B html.blade.php
                });

                @if(auth()->user())
                    @if(count(b2b()->activeCustomer()->topPurchasedItems()))
                        getFavoritePricesAsync();
                        getFavoriteATPsAsync();
                    @endif
                @endif
            });

            function getFavoritePricesAsync(){
                var pricingData = topPurchasedItemsPricingData;
                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($('#favorites-carousel').find('.price-loader-' + familyId).is(":visible")) {
                                $('#favorites-carousel').find('.item-price-' + familyId).append('<strong class="price-unavailable" style="color: red">{!! trans('messages.temporarily_unavailable') !!}</strong>');
                                $('#favorites-carousel').find('.price-loader-' + familyId).hide();
                            }

                            let $familyBlockDiv = $('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0);
                            if($familyBlockDiv.find('.quantity-add-to-cart-button').length) {
                                $familyBlockDiv.find('.quantity-add-to-cart-button').prop('disabled', true);
                                $familyBlockDiv.find('.quantity-select-box').prop('disabled', true);
                                $familyBlockDiv.find('.quantity-select-box').val(0);
                                $familyBlockDiv.find('.select-item-link').data('family-price', '');
                            }
                        });
                    },
                    complete: function(){
                        let impressions = [];

                        $.each(pricingResponse, function(familyId, prices){
                            if($('#favorites-carousel').find('.price-loader-' + familyId).is(":visible")) {
                                let $familyBlockDiv = $('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0);
                                if (prices === '{!! trans('messages.temporarily_unavailable') !!}') {
                                    if($familyBlockDiv.find('.quantity-add-to-cart-button').length) {
                                        $familyBlockDiv.find('.quantity-add-to-cart-button').prop('disabled', true);
                                        $familyBlockDiv.find('.quantity-select-box').prop('disabled', true);
                                        $familyBlockDiv.find('.quantity-select-box').val(0);
                                        $familyBlockDiv.find('.select-item-link').data('family-price', '');
                                    }
                                    $('#favorites-carousel').find('.item-price-' + familyId).append('<strong class="price-unavailable" style="color: red">{!! trans('messages.temporarily_unavailable') !!}</strong>');
                                }
                                else {
                                    $familyBlockDiv.find('.select-item-link').data('family-price', prices['minPrice']);
                                    if(prices['minPrice'] != prices['maxPrice']){
                                        $('#favorites-carousel').find('.item-price-' + familyId).append(prices['minPriceFormatted'] + ' - ' + prices['maxPriceFormatted']);
                                    }else{
                                        $('#favorites-carousel').find('.item-price-' + familyId).append(prices['minPriceFormatted']);
                                    }
                                }
                                $('#favorites-carousel').find('.price-loader-' + familyId).hide();
                                impressions.push({
                                    'id': $familyBlockDiv.data('part-number'),
                                    'name': $familyBlockDiv.data('part-name'),
                                    'price': $familyBlockDiv.find('.select-item-link').data('family-price'),
                                    'brand': $familyBlockDiv.data('brand'),
                                    'category': $familyBlockDiv.data('category'),
                                    'position': $familyBlockDiv.data('position'),
                                    'list': 'topPurchased',
                                });
                            }
                        });

                        @if($consentedCookies != null && in_array('marketingConsent', $consentedCookies) && !empty(b2b()->activeWebSilo()->google_tracking))
                        dataLayer.push({
                            'event': 'view_item_list',
                            'ecommerce': {
                                'currencyCode': '{{b2b()->activeCurrency()}}',
                                'impressions': impressions
                            }
                        });
                        @endif
                    }
                });
            }

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

                @foreach($topPurchasedItems 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){
                                        $('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').prop('disabled', true);
                                        $('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').prop('disabled', true);
                                        $('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').val(0);
                                    }else{
                                        $('#favorites-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"){
                                    $('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').prop('disabled', true);
                                    $('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').prop('disabled', true);
                                    $('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-select-box').val(0);
                                }
                            });
                        }
                    });
                }
            }
        </script>
    @endif
    @endif
@endif