@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-xs-12">
                @if (!rewards()->isRegistered())
                    @if(rewards()->isSelfEligible())
                        @include('hilco::components.rewards.notSignedUp')
                        <br>
                    @endif
                @elseif(rewards()->isEligible())
                    @include(
                        'hilco::components.rewards.member',
                        [
                            'tier' => rewards()->tier(),
                            'tierTextColorHex' => rewards()->tierTextColorHex(),
                            'tierName' => rewards()->tierName(),
                            'nextTierTextColorHex' => rewards()->tierTextColorHex(rewards()->nextTier()),
                            'nextTierName' => rewards()->tierName(rewards()->nextTier()),
                            'categoriesToUpgrade' => rewards()->calculateCategoriesToUpgrade(),
                            'spendingToUpgrade' => rewards()->calculateSpendingToUpgrade(),
                        ]
                    )
                @endif
            </div>
        </div>
        <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.on({
                    'initialized.owl.carousel': function() {
                        favoriteItemsCarousel.find('.family-block-item').show();
                    }
                }).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,
                        },
                    },
                });

                @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();
                            }

                            if($('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').length) {
                                $('#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);
                            }
                        });
                    },
                    complete: function(){
                        $.each(pricingResponse, function(familyId, prices){
                            if($('#favorites-carousel').find('.price-loader-' + familyId).is(":visible")) {
                                if (prices === '{!! trans('messages.temporarily_unavailable') !!}') {
                                    if($('#favorites-carousel').find('.item-price-' + familyId).parents('div[class^="family-block-item"]').eq(0).find('.quantity-add-to-cart-button').length) {
                                        $('#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);
                                    }
                                    $('#favorites-carousel').find('.item-price-' + familyId).append('<strong class="price-unavailable" style="color: red">{!! trans('messages.temporarily_unavailable') !!}</strong>');
                                }
                                else {
                                    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();
                            }
                        });
                    }
                });
            }

            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