<?php

namespace Hilco\Models;


class CustomerPeerGroupSuggestion extends WebModel {
    protected $table = 'CustomerPeerGroupSuggestions';
    protected $fillable = ['customercategory_id', 'webfamily_id'];

    public function customerCategory() {
        return $this->belongsTo(CustomerCategory::class, 'customercategory_id', 'id');
    }

    public function webFamily() {
        return $this->belongsTo(WebFamily::class, 'webfamily_id', 'id')->first();
    }

    public function scopeCategory($query, $customerCategoryId) {
        return $query->where('customercategory_id', $customerCategoryId);
    }

    public function webFamilyToDisplay() {
        $webFamily = WebFamily::webVisible()->where('name', $this->webFamily()->name)->first();
        return (isset($webFamily)) ? $webFamily : null;
    }

    public static function getSuggestedFamilies() {
        $activeCustomer = b2b()->activeCustomer();

        if (!isset($activeCustomer) || !$activeCustomer) return [];

        $activeCustomerCategory = $activeCustomer->overrideCustomerCategory;

        $familiesToSkip = [];
        $webCartItems = WebCart::getWebCartItems();
        foreach($webCartItems as $webCartItem) {
            $webPart = $webCartItem->webPart;
            if ($webPart && $webPart->webFamily) {
                $familiesToSkip[] = $webPart->webFamily;
            }
        }

        $suggestedFamilies = [];
        $suggestions = CustomerPeerGroupSuggestion::category($activeCustomerCategory->id)->get();
        if (count($suggestions) > 0) {
            foreach($suggestions as $suggestion) {
                $suggestedFamily = $suggestion->webFamilyToDisplay();
                if(isset($suggestedFamily) && !in_array($suggestedFamily, $familiesToSkip)) {
                    $suggestedFamilies[] = $suggestedFamily;
                }
                if (count($suggestedFamilies) == 4) break;
            }
        }
        
        if (count($suggestedFamilies) < 4) {
            foreach($suggestedFamilies as $family) {
                $alsoLikeFamilies = $family->alsoLikeFamilies();
                if (count($alsoLikeFamilies)) {
                    $suggestedFamilies[] = $alsoLikeFamilies[0];
                }
                if (count($suggestedFamilies) == 4) break;
            }
        }

        return $suggestedFamilies;
    }
}