<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;use App\Models\Concerns\BelongsToCompany;


class KbCategory extends Model
{
    use BelongsToCompany;
    protected $fillable = ['name','slug','description','icon','color','parent_id','order','active'];
    protected function casts(): array { return ['active' => 'boolean']; }

    protected static function boot(): void {
        parent::boot();
        static::creating(fn($m) => $m->slug = $m->slug ?: Str::slug($m->name));
    }

    public function parent(): BelongsTo    { return $this->belongsTo(KbCategory::class, 'parent_id'); }
    public function children(): HasMany    { return $this->hasMany(KbCategory::class, 'parent_id')->orderBy('order'); }
    public function articles(): HasMany    { return $this->hasMany(KbArticle::class, 'category_id'); }

    public function scopeActive($q)  { return $q->where('active', true); }
    public function scopeRoots($q)   { return $q->whereNull('parent_id'); }

    public function getPublishedCountAttribute(): int {
        return $this->articles()->where('status', 'published')->count();
    }
}
