<?php

namespace Hilco\Models;

use DB;
use Arr;

use Hilco\Models\SelectsRelatedCount;
use Illuminate\Database\Eloquent\Relations\HasOne;

class WebProductMenuConfiguration extends WebModel
{
    protected $table = 'WebProductMenuConfigurations';
    protected $fillable = ['product_id', 'product_type', 'header_color', 'top_content_type', 'top_content_id', 'bottom_content_type', 'bottom_content_id'];

    public function getAlternatesAttribute(){
        $alternates = [];
        $index = 0;
        foreach ($this->webProductMenuConfigurationAlternates as $alternateObject){
            $menuObject = $alternateObject->alternateWebProductMenuConfiguration;
            $alternates[++$index] = [
                'id' => $alternateObject->id,
                'alternateMenuId' => $menuObject? $menuObject->id : 0,
                'targetCustomers' => json_decode($alternateObject->targetCustomers, true),
                'targetCustomersFormatted' => $alternateObject->targetCustomersFormatted,
                'visibleDates' => json_decode($alternateObject->visibleDates, true),
                'visibleDatesFormatted' => $alternateObject->visibleDatesFormatted,
                'alternateWebProductMenuConfiguration' => $menuObject
            ];
        }
        return $alternates;
    }

    public function webProductMenuConfigurationAlternates(){
        return $this->hasMany(WebProductMenuConfigurationAlternate::class, 'webproductmenuconfiguration_id', 'id');
    }

    public function getIcon()
    {
        $asset = $this->assetsByType('icon')->first();
        return $asset;
    }

    public function iconImage($width = false, $height = false)
    {
        $asset = $this->getIcon();
        if ($height === false && is_string($width)) return WebAsset::getPredefinedSizeUrl($asset, $width);
        return WebAsset::getSizedUrl($asset, $width, $height);
    }

    public function topWebAsset() {
        if($this->top_content_type == 'webAsset'){
            return $this->hasOne(WebAsset::class, 'id', 'top_content_id');
        }else{
            $webAsset = new WebAsset();
            $webProductionMenuConfiguration = new WebProductMenuConfiguration();
            return new HasOne($webAsset->newQuery(), $webProductionMenuConfiguration, 'WebAssets.id', 'top_content_id');
        }
    }

    public function topWebFamily()
    {
        if ($this->top_content_type == 'webFamily') {
            return $this->hasOne(WebFamily::class, 'id', 'top_content_id');
        } else {
            $webFamily = new WebFamily();
            $webProductionMenuConfiguration = new WebProductMenuConfiguration();
            return new HasOne($webFamily->newQuery(), $webProductionMenuConfiguration, 'WebFamilies.id', 'top_content_id');
        }
    }

    public function getTopBestSeller()
    {
        if ($this->top_content_type == 'bestSeller' && $this->product_type == 'webGroup') {
            $webgroup = WebGroup::find($this->product_id);
            if ($webgroup != null) {
                return WebFamily::webVisible()->bestSellers()->inGroup($webgroup)->with('visibleWebParts')->with('visibleWebParts.part.prices')->first();
            }
        }
        return null;
    }

    public function bottomWebAsset()
    {
        if ($this->bottom_content_type == 'webAsset') {
            return $this->hasOne(WebAsset::class, 'id', 'bottom_content_id');
        } else {
            $webAsset = new WebAsset();
            $webProductionMenuConfiguration = new WebProductMenuConfiguration();
            return new HasOne($webAsset->newQuery(), $webProductionMenuConfiguration, 'WebAssets.id', 'bottom_content_id');
        }
    }

    public function bottomWebFamily()
    {
        if ($this->bottom_content_type == 'webFamily') {
            return $this->hasOne(WebFamily::class, 'id', 'bottom_content_id');
        } else {
            $webFamily = new WebFamily();
            $webProductionMenuConfiguration = new WebProductMenuConfiguration();
            return new HasOne($webFamily->newQuery(), $webProductionMenuConfiguration, 'WebFamilies.id', 'bottom_content_id');
        }
    }

    public function getBottomBestSeller()
    {
        if ($this->bottom_content_type == 'bestSeller' && $this->product_type == 'webGroup') {
            $webgroup = WebGroup::find('product_id');
            if ($webgroup != null) {
                return $webgroup->webCategories->webCollections->webFamilies->webVisible()->bestSellers()->with('visibleWebParts')->with('visibleWebParts.part.prices')->first();
            }
        }
        return null;
    }

    public function getTopLink()
    {
        $link = array('type' => $this->top_link_type, 'target' => $this->top_link_target);
        return $link;
    }

    public function getBottomLink()
    {
        $link = array('type' => $this->bottom_link_type, 'target' => $this->bottom_link_target);
        return $link;
    }

    //this field defaults to false. It maps to a PersonalizationUsageLog which can only exist while a page is being loaded and this WebProductMenuConfiguration in memory has been rendered as an alternate.
    public $personalization_log_id = false;

    public function getForCustomer($customer = false){
        if ($customer === false){
            $customer = b2b()->activeCustomer();
        }
        foreach ($this->alternates as $alternate){
            if (inDateRange(Arr::get($alternate, 'visibleDates', [])) && ($targetType = customerIsTargeted(Arr::get($alternate, 'targetCustomers', []), $customer)) !== false){
                $alternateWebProductMenuConfiguration = Arr::get($alternate, 'alternateWebProductMenuConfiguration', $this);

                $personalizationLog = \Hilco\Models\PersonalizationUsageLog::create([
                    'user_id' => auth()->user()->id,
                    'url' => request()->url(),
                    'blade' => 'webProductMenuConfiguration',
                    'alternate_id' => Arr::get($alternate, 'id', 0),
                    'link' => implode(',', ['topLink'=>json_encode($alternateWebProductMenuConfiguration->getTopLink()), 'bottomLink'=>json_encode($alternateWebProductMenuConfiguration->getBottomLink())]),
                    'target_type' => $targetType,
                    'target_customers' => json_encode(Arr::get($alternate, 'targetCustomers', []))
                ]);

                //the field personalization_log_id isn't persisted anywhere, it's just saved in memory for the page loading process.
                $alternateWebProductMenuConfiguration->personalization_log_id = $personalizationLog->id;

                return $alternateWebProductMenuConfiguration;
            }
        }

        $this->personalization_log_id = false;
        return $this;
    }

    use HasAssets;
}
