<?php

class MailTemplate
{
    private string $basePath;

    public function __construct(string $basePath)
    {
        $this->basePath = rtrim($basePath, '/');
    }

    public function render(string $template, array $params = [], string $lang = 'id'): string
    {
        $headerFile = $this->basePath . '/partials/header.html';
        $footerFile = $this->basePath . '/partials/footer.html';
        $bodyFile   = $this->basePath . '/' . $lang . '/' . $template . '.html';

        // fallback bahasa
        if (!file_exists($bodyFile)) {
            $bodyFile = $this->basePath . '/id/' . $template . '.html';
        }

        if (!file_exists($headerFile) || !file_exists($footerFile) || !file_exists($bodyFile)) {
            throw new Exception("Template tidak ditemukan: {$template}");
        }

        $header = file_get_contents($headerFile);
        $body   = file_get_contents($bodyFile);
        $footer = file_get_contents($footerFile);

        $html = $header . $body . $footer;

        return $this->applyParams($html, $params);
    }

    private function applyParams(string $html, array $params): string
    {
        foreach ($params as $key => $value) {
            $html = str_replace('{{ ' . $key . ' }}', $value, $html);
        }

        return $html;
    }
}