<?php

namespace App\Models\Shop;

use Cesargb\Database\Support\CascadeDelete;
use Rinvex\Tags\Traits\Taggable;
use Wildside\Userstamps\Userstamps;

use Rinvex\Categories\Models\Category as parentCategory;
use Kalnoy\Nestedset\NestedSet;

use App\Repositories\Shop\SaleChannels;

class Category extends parentCategory
{
    use CascadeDelete, Taggable, Userstamps;

    protected $guarded = ['id'];
    protected $table = 'categories';
    public $translatable = [];
    protected $cascadeDeleteMorph = ['Articles'];
    protected $fillable = [
        'visible',
        'homepage',
        'slug',
        'name',
        'description',
        NestedSet::LFT,
        NestedSet::RGT,
        NestedSet::PARENT_ID,
    ];


    public function Articles()
    {
        return $this->morphedByMany(Article::class, 'categorizable');
    }

    public function ArticlesTagged()
    {
        return $this->tags->articles;
    }

    public function categorizables()
    {
        return $this->hasMany(Categorizable::class);
    }

    public function countArticlesTagged()
    {
        return $this->tags()->withCount('Articles');
    }

    public function scopeByCategory($query, $category_id)
    {
        return $query->where('category_id', $category_id);
    }

    public function scopeVisible($query)
    {
        return $query->where('visible', 1);
    }

    public function scopeHomepage($query)
    {
        return $query->where('homepage', 1);
    }

    public function scopeNotRoot($query)
    {
        return $query->where('id', '<>', 1);
    }

    public function scopeInRange($query, $_lft, $_rgt)
    {
        return $query->where('_lft', '>=', $_lft)->where('_rgt', '<=', $_rgt);
    }

    public function scopeHasAvailableOffers($query, $sale_channel_id = false)
    {
        $sale_channel_id = $sale_channel_id ? $sale_channel_id : SaleChannels::getDefaultID();
        return $query->whereHas('articles', function ($query) use ($sale_channel_id) {
            $query->WithAvailableOffers($sale_channel_id);
        });
    }

    public function scopeHasAvailableOffersByCategoryParent($query, $sale_channel_id = false)
    {
        $sale_channel_id = $sale_channel_id ? $sale_channel_id : SaleChannels::getDefaultID();
        return $query->whereHas('articles', function ($query) use ($sale_channel_id) {
            $query->WithAvailableOffers($sale_channel_id);
        })->orWhereHas('descendants.articles', function ($query) use ($sale_channel_id) {
            $query->WithAvailableOffers($sale_channel_id);
        });
    }
}
