<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class EmailTemplate extends Model
{
    protected $fillable = [
        'name',
        'subject',
        'body',
        'enabled',
    ];

    protected $casts = [
        'enabled' => 'boolean',
    ];

    /**
     * Get template by name
     */
    public static function getTemplate(string $name): ?self
    {
        return self::where('name', $name)->where('enabled', true)->first();
    }

    /**
     * Replace placeholders in template
     */
    public function render(array $data): array
    {
        $subject = $this->subject;
        $body = $this->body;

        // Add default placeholders
        $defaults = [
            'site_name' => Setting::get('site_name', config('app.name')),
            'site_url' => config('app.url'),
            'logo_url' => \App\Helpers\SeoHelper::siteLogo() ? url(\App\Helpers\SeoHelper::siteLogo()) : url('/images/logo.png'),
            'year' => date('Y'),
        ];

        $data = array_merge($defaults, $data);

        // Replace placeholders
        foreach ($data as $key => $value) {
            $subject = str_replace('{{' . $key . '}}', $value, $subject);
            $body = str_replace('{{' . $key . '}}', $value, $body);
        }

        return [
            'subject' => $subject,
            'body' => $body,
        ];
    }
}
