<?php

namespace App\Models\Tenant;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class MessageTemplate extends Model
{
    use BelongsToTenant, SoftDeletes;

    protected $table = 'msg_templates';

    public const CHANNELS = [
        'telegram' => 'Telegram',
        'whatsapp' => 'WhatsApp',
        'viber' => 'Viber',
        'sms' => 'SMS',
        'email' => 'Email',
    ];

    protected $fillable = [
        'company_id', 'name', 'channel', 'subject',
        'body', 'variables', 'is_active',
    ];

    protected $casts = [
        'variables' => 'array',
        'is_active' => 'boolean',
    ];

    /**
     * Render template body with the given context, replacing {key} tokens.
     */
    public function render(array $context = []): string
    {
        $body = $this->body;
        foreach ($context as $key => $val) {
            $body = str_replace('{' . $key . '}', (string) $val, $body);
        }
        return $body;
    }
}
