<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;

class Taxonomy extends Model
{
    use HasFactory, HasTranslations;

    protected $table = 'taxonomy';

    protected $fillable = [
        'parent_id',
        'old_id',
        'name',
        'slug',
        'handle',
        'content',
        'image_path',
        'isSingleSelect',
        'isDeletable',
        'status',
        'ordernum',
    ];

    public $translatable = ['name', 'slug', 'content'];

    public function parent()
    {
        return $this->belongsTo(Taxonomy::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Taxonomy::class, 'parent_id');
    }

    public function childrenCount()
    {
        return $this->hasMany(Taxonomy::class, 'parent_id')->count();
    }

    public function childrenRecursive()
    {
        return $this->children()->with('childrenRecursive')->active();
    }

    public function products()
    {
        return $this->belongsToMany(Product::class, 'taxonomy_product');
    }

    public function scopeActive($query)
    {
        return $query->where('status', true);
    }

    public function ancestors()
    {
        $ancestors = collect();

        $parent = $this->parent;
        while ($parent) {
            $ancestors->push($parent);
            $parent = $parent->parent;
        }

        return $ancestors->reverse();
    }
}
