<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MessageTemplate extends Model
{
    protected $fillable = [
        'type', 'label', 'email_subject', 'email_body', 'wa_body', 'available_variables',
    ];

    protected function casts(): array
    {
        return [
            'available_variables' => 'array',
        ];
    }

    /**
     * Get a template by type, returns null if not found
     */
    public static function getByType(string $type): ?self
    {
        return static::where('type', $type)->first();
    }

    /**
     * Render a template string by replacing {variable} placeholders
     */
    public static function render(string $template, array $variables): string
    {
        // Decode any HTML-encoded curly braces first (e.g. from form editing)
        $template = str_replace(['&#123;', '&#125;', '&lbrace;', '&rbrace;'], ['{', '}', '{', '}'], $template);

        foreach ($variables as $key => $value) {
            $template = str_replace('{' . $key . '}', (string) $value, $template);
        }
        return $template;
    }
}
