<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Traits\Archivable;

class PageTemplate extends Model
{
    use HasFactory, SoftDeletes, Archivable;

    /**
     * Use UUIDs instead of auto-increment IDs
     */
    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'name',
        'slug',
        'content',
        'is_franchise_template',
    ];

    protected $casts = [
        'content' => 'array', // if using jsonb
        'is_franchise_template' => 'boolean', // ✅ cast to boolean
    ];

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

        static::creating(function ($template) {
            // Set UUID if not already set
            if (empty($template->{$template->getKeyName()})) {
                $template->{$template->getKeyName()} = (string) Str::uuid();
            }

            // Auto-generate slug if empty
            if (empty($template->slug)) {
                $template->slug = Str::slug($template->name);
            }
        });

        static::updating(function ($template) {
            if (empty($template->slug)) {
                $template->slug = Str::slug($template->name);
            }
        });
    }

    /**
     * Relationships
     */
    public function pages()
    {
        return $this->hasMany(Page::class, 'template_id');
    }
}
