<?php
/**
 * Block Registry Category Model
 * Categories for organizing blocks in the registry
 */
namespace Mtc\Modules\BlockRegistry\Models;

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

class BlockRegistryCategory extends Model
{
    protected $table = 'block_registry_categories';

    protected $fillable = [
        'name',
        'slug',
        'icon',
        'order_index',
        'parent_id',
    ];

    protected $casts = [
        'order_index' => 'integer',
        'parent_id' => 'integer',
    ];

    /**
     * Get all blocks in this category
     */
    public function blocks(): HasMany
    {
        return $this->hasMany(BlockRegistry::class, 'category_id')
            ->orderBy('order_index');
    }

    /**
     * Get parent category
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(BlockRegistryCategory::class, 'parent_id');
    }

    /**
     * Get child categories
     */
    public function children(): HasMany
    {
        return $this->hasMany(BlockRegistryCategory::class, 'parent_id')
            ->orderBy('order_index');
    }

    /**
     * Generate slug from name
     */
    public static function generateSlug(string $name): string
    {
        return strtolower(preg_replace('/[^a-z0-9]+/i', '-', trim($name)));
    }

    /**
     * Boot method for model events
     */
    protected static function boot(): void
    {
        parent::boot();

        static::creating(function ($category) {
            if (empty($category->slug)) {
                $category->slug = self::generateSlug($category->name);
            }
        });
    }
}
