<?php

namespace App\Models\Botanic;

use App\Models\Shop\Article;
use App\Models\Shop\Tag;
use App\Traits\Model\Imageable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Kirschbaum\PowerJoins\PowerJoins;
use Rinvex\Tags\Traits\Taggable;
use Spatie\MediaLibrary\HasMedia;
use Wildside\Userstamps\Userstamps;

class Variety extends Model implements HasMedia
{
    use Imageable, PowerJoins, SoftDeletes, Taggable, UserStamps;

    protected $guarded = ['id'];

    protected $table = 'botanic_varieties';

    public function Specie(): BelongsTo
    {
        return $this->belongsTo(Specie::class);
    }

    public function Articles(): MorphMany
    {
        return $this->morphMany(Article::class, 'product');
    }

    public function tags(): MorphToMany
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }

    public function scopeByTag($query, $tagId)
    {
        return $tagId ? $query->whereHas('tags', function ($query) use ($tagId) {
            $query->byId($tagId);
        })->orWhereHas('Specie', function($query) use ($tagId) {
            $query->byTag($tagId);
        }) : $query;
    }

    public function scopeByTags($query, $tags)
    {
        return $tags ? $query->whereHas('tags', function ($query) use ($tags) {
            $query->byIds($tags);
        })->orWhereHas('Specie', function($query) use ($tags) {
            $query->byTags($tags);
        }) : $query;
    }
}
