<?php

namespace App\Domain\WhatsApp;

use App\Models\Tenant;
use App\Models\WaTemplate;

class TemplateRenderer
{
    /**
     * Resolve a template body for the clinic (custom override or default),
     * in the patient's preferred locale, and fill {tokens}.
     *
     * @return array{0:string, 1:bool} [rendered body, enabled]
     */
    public function render(Tenant $tenant, string $key, array $tokens, string $locale = 'ar'): array
    {
        $template = WaTemplate::where('tenant_id', $tenant->id)->where('key', $key)->first();

        if ($template) {
            $body = $template->body($locale) ?: $template->body($locale === 'ar' ? 'en' : 'ar');
            $enabled = $template->enabled;
        } else {
            $defaults = DefaultTemplates::all()[$key] ?? null;
            $body = $defaults[$locale] ?? $defaults['en'] ?? '';
            $enabled = true;
        }

        return [$this->fill($body, $tokens), $enabled];
    }

    public function fill(string $body, array $tokens): string
    {
        foreach ($tokens as $k => $v) {
            $body = str_replace('{'.$k.'}', (string) $v, $body);
        }

        return $body;
    }
}
