<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

final class EmailTemplateModel extends BaseModel
{
    protected string $table = 'email_templates';
    protected array $fillable = ['business_line_id', 'name', 'category', 'subject', 'body_html'];
    protected bool $softDeletes = true;
    protected bool $auditStamps = true;

    public function allWithBusinessLine(?string $category = null): array
    {
        $sql = "SELECT t.*, bl.name AS business_line_name FROM email_templates t
                LEFT JOIN business_lines bl ON bl.id = t.business_line_id
                WHERE t.deleted_at IS NULL";
        $bindings = [];

        if ($category !== null) {
            $sql .= ' AND t.category = :category';
            $bindings['category'] = $category;
        }

        $sql .= ' ORDER BY t.name';

        $stmt = $this->db->prepare($sql);
        $stmt->execute($bindings);

        return $stmt->fetchAll();
    }

    /** Replaces {{first_name}}, {{last_name}}, {{email}} etc. with real recipient data — used at send time by CampaignService/EmailQueueService. */
    public static function renderMergeFields(string $body, array $recipient): string
    {
        $replacements = [
            '{{first_name}}' => $recipient['first_name'] ?? '',
            '{{last_name}}' => $recipient['last_name'] ?? '',
            '{{email}}' => $recipient['email'] ?? '',
            '{{company_name}}' => $recipient['company_name'] ?? '',
        ];

        return strtr($body, $replacements);
    }
}
