<?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\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Rinvex\Tags\Traits\Taggable;
use Spatie\MediaLibrary\HasMedia;
use Wildside\Userstamps\Userstamps;

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

    protected $guarded = ['id'];

    protected $table = 'botanic_species';

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

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

    public function Varieties(): HasMany
    {
        return $this->hasMany(Variety::class);
    }

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

    public function scopeByName($query, $name)
    {
        return $query->where($this->table.'.name', $name);
    }

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

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