<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ProductCategory extends Model
{
    protected $fillable = ['name', 'slug', 'order', 'parent_id'];

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

    public function children(): HasMany
    {
        return $this->hasMany(ProductCategory::class, 'parent_id')->orderBy('order')->orderBy('name');
    }

    public function products(): HasMany
    {
        return $this->hasMany(Product::class)->orderBy('order')->orderBy('name');
    }

    public function allProducts()
    {
        $ids = $this->children()->pluck('id')->push($this->id);
        return Product::whereIn('product_category_id', $ids);
    }

    /** @return \Illuminate\Support\Collection<int, int> */
    public function getSelfAndDescendantIds(): \Illuminate\Support\Collection
    {
        $ids = collect([$this->id]);
        foreach ($this->children as $child) {
            $ids = $ids->merge($child->getSelfAndDescendantIds());
        }
        return $ids->unique();
    }
}
