<?php

namespace Mtc\Modules\BlockRegistry\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class BlockTemplate extends Model
{
    protected $table = 'block_templates';

    protected $fillable = [
        'name',
        'slug',
        'description',
    ];

    /**
     * Get template items ordered by position
     */
    public function items(): HasMany
    {
        return $this->hasMany(BlockTemplateItem::class, 'block_template_id')->orderBy('order_index');
    }

    /**
     * Get template assignments (which page templates this is available on)
     */
    public function templateAssignments(): HasMany
    {
        return $this->hasMany(BlockTemplateAssignment::class, 'block_template_id');
    }

    /**
     * Get assigned template names as array
     */
    public function getTemplatesAttribute(): array
    {
        return $this->templateAssignments->pluck('template_name')->toArray();
    }

    /**
     * Get count of blocks in this template
     */
    public function getBlockCountAttribute(): int
    {
        return $this->items()->count();
    }

    public static function generateSlug(string $name): string
    {
        return Str::slug($name);
    }

    protected static function boot(): void
    {
        parent::boot();

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