<?php

namespace Hilco\Models;

use Debugbar;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Venturecraft\Revisionable\RevisionableTrait;

/**
 * Class WebSilo
 * @package Hilco\Models
 * @property integer $id
 * @property string $name
 * @property string $display_name
 * @property string $slug
 * @property integer $is_visible
 * @property integer $is_default
 * @property string $default_price_list
 * @property integer $weblandingpage_id
 * @property integer $allow_private_label
 * @property integer $limit_parts
 * @property integer $catalogs_weblink_id
 * @property integer $approved_parts_navbar
 * @property integer $default_spending_limit
 * @property integer $default_spending_period
 * @property integer $default_minimum_order
 * @property integer $allow_rewards
 * @property integer $allow_credit_cards
 * @property integer $allow_direct_billing
 * @property integer $allow_group_billing
 * @property integer $allow_drop_shipping
 * @property integer $allow_rate_shopping
 * @property integer $webhierarchy_id
 * @property string $allowed_carrier_codes
 * @property string $shipping_note
 * @property string $fob_override
 * @property string $google_tracking
 * @property string $date_activated
 * @property string $google_tagmanager
 * @property integer $send_order_confirmations
 * @property integer $soldto_payer_listprice
 * @property integer $soldtoparent_payer_listprice
 * @property integer $soldtoparent_payerparent_listprice
 * @property string $navbar_phone
 * @property boolean $use_cookie_consent
 * @property string $division_display_name
 * @property boolean $show_tray_info
 * @property boolean $po_number_required
 * @property boolean $same_day_due_date
 * @property boolean $allow_subscribe_and_save
 * @property string $klaviyo_list_id
 * @property string $livechat_license_id
 * @property string $favicon_type
 * @property boolean $show_webfamilylabels
 * @property boolean $send_approval_emails
 * @property boolean $terms_cond_required
 * @property boolean $allow_promotions
 * @property boolean $show_promo_code_field
 * @property boolean $display_pdp_qty_col
 * @property boolean $use_prescription_reorder_page
 * @property string $klaviyo_company_id
 * @property string $klaviyo_api_key
 * @property string $default_ship_policy
 * @property boolean $show_pdp_download
 * @property string $date_created
 * @property string $date_modified
 * @property string $date_uploaded
 * @property string $deleted_at
 */

class WebSilo extends WebModel implements HasLandingPageInterface {
	protected $table = "WebSilos";
    protected $fillable = [
        'name',
        'display_name',
        'slug',
        'webRoleIds',
        'is_visible',
        'is_default',
        'detail',
        'default_price_list',
        'weblandingpage_id',
        'allow_private_label',
        'limit_parts',
        'catalogs_weblink_id',
        'approved_parts_navbar',
        'default_spending_limit',
        'default_spending_period',
        'default_minimum_order',
        'allow_rewards',
        'allow_credit_cards',
        'allow_direct_billing',
        'allow_group_billing',
        'allow_drop_shipping',
        'allow_rate_shopping',
        'webhierarchy_id',
        'allowed_carrier_codes',
        'shipping_note',
        'fob_override',
        'google_tracking',
        'date_activated',
        'google_tagmanager',
        'send_order_confirmations',
        'soldto_payer_listprice',
        'soldtoparent_payer_listprice',
        'soldtoparent_payerparent_listprice',
        'never_override_listprice',
        'navbar_phone',
        'use_cookie_consent',
        'division_display_name',
        'show_tray_info',
        'po_number_required',
        'same_day_due_date',
        'allow_subscribe_and_save',
        'klaviyo_list_id',
        'livechat_license_id',
        'favicon_type',
        'show_webfamilylabels',
        'send_approval_emails',
        'terms_cond_required',
        'allow_promotions',
        'show_promo_code_field',
        'display_pdp_qty_col',
        'use_prescription_reorder_page',
        'klaviyo_api_key',
        'klaviyo_company_id',
        'default_ship_policy',
        'show_pdp_download',
    ];
	protected $casts = [
	    'is_visible' => 'boolean',
        'terms_cond_required' => 'boolean',
        'show_pdp_download' => 'boolean',
	];

	const HILCO_OUTDOOR_SLUG = 'hilco-outdoor';

	public function webHierarchy() {
	    return $this->hasOne(WebHierarchy::class, 'id', 'webhierarchy_id');
    }

    public function scopeHasVisibleChildren(Builder $query, $webSilo = false, $country = false, $plant = false) {
        return $query
            ->whereHas('webGroups', function ($query) use ($webSilo, $country, $plant) {
                return $query->isVisible()->hasVisibleChildren($webSilo, $country, $plant);
            })
        ;
    }

    public function scopeIsActiveWebSilo(Builder $query, $activeWebSilo = false) {
	    if ($activeWebSilo === false) $activeWebSilo = b2b()->activeWebSilo();
	    return $query
            ->where('WebSilos.id', '=', $activeWebSilo->id)
        ;
    }

    public function customers() {
	    return $this->hasMany(Customer::class, 'websilo_id', 'id');
    }

    public function webUsers() {
        return $this->belongsToMany(WebUser::class, 'WebSilo_WebUser', 'websilo_id', 'webuser_id')
            ->withPivot(['spending_limit', 'spending_period', 'minimum_order'])
        ;
    }

    public function webContactBlock() {
        return $this->hasOne(WebContactBlock::class, 'websilo_id', 'id');
    }

    public function webContactBlocks() {
	    return $this->hasMany(WebContactBlock::class, 'websilo_id', 'id');
    }

    public function getContactBlockAttribute() {
	    $webContactBlock = b2b()->activeWebSilo()->webContactBlock;
	    return isset($webContactBlock) ? $webContactBlock->contact_block : '';
    }

	public function webLinkCategories() {
		return $this->belongsToMany(WebCategory::class, 'WebLinkCategory_WebSilo', 'websilo_id', 'weblinkcategory_id');
	}

	public function webLinks() {
		return $this->belongsToMany(WebLink::class, 'WebLink_WebSilo', 'websilo_id', 'weblink_id');
	}

	public function webUrls() {
	    return $this->hasMany(WebUrl::class, 'websilo_id', 'id');
    }

    public function parts() {
	    return $this
            ->belongsToMany(Part::class, 'WebSilo_Part', 'websilo_id', 'part_id')
            ->wherePivot('deleted_at', '0000-00-00 00:00:00')
            ->withPivot(['require_approval'])
        ;
    }

    //This needs to be here, I don't know why every time we merge b2b it wants to remove it. Don't remove it. Keep it.
    public function webSiloParts() {
        return $this->hasMany(WebSilo_Part::class, 'websilo_id', 'id');
    }

    //This needs to be here, I don't know why every time we merge b2b it wants to remove it. Don't remove it. Keep it.
    public function webSiloOverrides() {
        return $this->hasMany(WebSiloOverride::class, 'websilo_id', 'id');
    }

    public function catalogsWebLink() {
	    return $this->belongsTo(WebLink::class, 'catalogs_weblink_id', 'id');
    }

	public function getFeaturedChildrenAttribute() {
        return $this->visibleWebGroups()->wherePivot('is_featured', 1)->get();
    }

    public function getChildrenAttribute() {
        return WebGroup::alphabetical()->webVisible()->webSiloApproved()->get();
    }

    public function divisionRules() {
        return $this->belongsToMany(Division::class, 'WebSilo_Division', 'websilo_id', 'division_id');
    }

    public function customerCategorySummaryRules() {
        return $this->belongsToMany(CustomerCategorySummary::class, 'WebSilo_CustomerCategorySummary', 'websilo_id', 'customercategorysummary_id');
    }

    public function webCustomerTypeRules() {
        return $this->belongsToMany(WebCustomerType::class, 'WebSilo_WebCustomerType', 'websilo_id', 'webcustomertype_id');
    }

    public function getDivisionsAttribute() {
        return $this->divisionRules->pluck('id')->toArray();
    }

    public function setDivisionsAttribute($ids) {
        $this->divisionRules()->sync($ids);
    }

    public function getCustomerCategorySummariesAttribute() {
        return $this->customerCategorySummaryRules->pluck('id')->toArray();
    }

    public function setCustomerCategorySummariesAttribute($ids) {
        $this->customerCategorySummaryRules()->sync($ids);
    }

    public function getWebCustomerTypesAttribute() {
        return $this->webCustomerTypeRules->pluck('id')->toArray();
    }

    public function setWebCustomerTypesAttribute($ids) {
        $this->webCustomerTypeRules()->sync($ids);
    }

    public function getUrlsAttribute() {
        return $this->webUrls->pluck('id')->toArray();
    }

    public function setUrlsAttribute($ids) {
        $this->webUrls()->sync($ids);
    }

    public function getParts(){
	    return WebSilo_Part::where('websilo_id', '=', $this->id)->get();
    }

    public function getWebLandingPageAttribute() {
	    $activeLanguage = b2b()->activeLanguage();
	    $defaultLanguage = b2b()->activeWebSilo()->defaultLanguage();
	    $homePages = $this->webLandingPages->keyBy('language');
        $homePage = Arr::get($homePages, $activeLanguage, Arr::get($homePages, $defaultLanguage->language_code));
	    return $homePage;
    }

    public function webLandingPages() {
	    return $this->belongsToMany(WebLandingPage::class, 'WebLandingPage_WebSilo', 'websilo_id', 'weblandingpage_id')
            ->wherePivot('deleted_at', '=', '0000-00-00 00:00:00');
    }

    public function webLandingPageWebSiloJoins() {
        return $this->hasMany(WebLandingPage_WebSilo::class, 'websilo_id', 'id');
    }

    public function webLinkWebSiloJoins() {
	    return $this->hasMany(WebLink_WebSilo::class, 'websilo_id', 'id');
    }

//    /**
//     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
//     */
//    public function webLandingPages() {
//        return $this
//            ->belongsToMany(WebLandingPage::class, 'WebLandingPage_WebSilo', 'websilo_id', 'weblandingpage_id')
//            ->withPivot(['plant_id'])
//            ->where(function ($where) {
//                $where
//                    ->whereNull('plant')
//                    ->orWhere('plant', '=', b2b()->activePlant())
//                ;
//            })
//            ->orderBy('plant')
//        ;
//    }

	public function scopeVisible(Builder $query) {
		return $query->where('WebSilos.is_visible', '1');
	}

	public static function default() {
        return self::where('is_default', '1')->first();
    }

	public function scopeCurrent(Builder $query) {
        $query->where('id', b2b()->activeWebSilo()->id);
    }

    public function getPriceListAttribute() {
        return $this->default_price_list;
    }

    public function scopeNavbarMenu(Builder $query) {
        return $query->with(['webGroups' => function ($query) {
            return $query->orderBy('pivot_display_order', 'asc')->orderBy('name', 'asc');
        }]);
    }

    public static function selectList() {
        return self::orderBy('is_default', 'DESC')->orderBy('name', 'ASC')->get()->map(function ($webSilo) {
            if ($webSilo->is_default) $webSilo->name = $webSilo->name . ' (Default)';
            return $webSilo;
        });
    }

    public function slugUrl() {
        return route('silo.slug', [$this->slug]);
    }

    public function carriers() {
        return $this->belongsToMany(Carrier::class, 'Carrier_WebSilo', 'websilo_id', 'carrier_id');
    }

    public function getDisplayNameForUACAttribute() {
        return $this->name;
    }

    public function getParentRelationName() {
        return false;
    }
    
    public function getIsOutdoorSiteAttribute(){
        return WebSilo::HILCO_OUTDOOR_SLUG == $this->slug;
    }

    public function getShippingNoteAttribute() {
        return $this->getTranslation('shipping_note');
    }
    
    public function allowedDeliveryMethods(){
        $deliveryMethods = [];

        $siloCodesString = $this->allowed_carrier_codes;
        if (strlen($siloCodesString)) {
            $siloCodes = explode(',', $siloCodesString);
            foreach ($siloCodes as $siloCode) {
                $method = DeliveryMethod::where('delivery_method_code', trim($siloCode))->first();
                if($method != null){
                    $deliveryMethods[] = $method->delivery_method_code;
                }
            }
        }

        return $deliveryMethods;
    }

    public function allowedLanguages() {
        return $this->belongsToMany(AvailableLanguage::class, 'WebSilo_AvailableLanguage', 'websilo_id', 'availablelanguage_id')
            ->withPivot(['is_default', 'icon_override_id'])
            ->wherePivot('deleted_at', '=', '0000-00-00 00:00:00');
    }

    public function webSiloAvailableLanguages() {
        return $this->hasMany(WebSilo_AvailableLanguage::class, 'websilo_id', 'id');
    }

    public function defaultLanguage() {
        return $this->allowedLanguages()->wherePivot('is_default', '=', 1)->first();
    }

    public function webSiloBlockedPages() {
        return $this->hasMany(WebSiloBlockedPage::class, 'websilo_id', 'id');
    }

    public function getDivisionDisplayNameAttribute() {
        if (empty($this->attributes['division_display_name'])) {
            return $this->display_name;
        } else {
            return $this->attributes['division_display_name'];
        }
    }

    public function getFaviconType() {
        return $this->favicon_type;
    }

    public function showWebFamilyLabels() {
	    return $this->show_webfamilylabels;
    }

    public function getDefaultShipPolicy() {
        return $this->default_ship_policy;
    }

    /**
     * @return bool
     */
    public function shouldShowPDPDownload(): bool {
        return $this->show_pdp_download;
    }
    
    use HasAssets, HasSlug, HasLandingPage, HasModelTranslations;
}