<?php
declare(strict_types=1);

/**
 * Simple multilingual template loader + renderer.
 * - Loads /i18n/{lang}.json
 * - Renders placeholders like {{name}}
 * - Falls back to English if key/lang missing
 */

function i18n_load(string $lang, string $baseDir): array {
    $lang = preg_replace('/[^a-z]/', '', strtolower($lang)); // keep safe
    if ($lang === '') $lang = 'en';

    $path = rtrim($baseDir, '/')."/i18n/{$lang}.json";
    $fallback = rtrim($baseDir, '/')."/i18n/en.json";

    $json = file_exists($path) ? file_get_contents($path) : false;
    if ($json === false) $json = file_get_contents($fallback);

    $data = json_decode((string)$json, true);
    if (!is_array($data)) {
        // last-resort empty to avoid fatal
        $data = [];
    }
    return $data;
}

function i18n_get(array $dict, string $keyPath, ?string $default = null): string {
    $parts = explode('.', $keyPath);
    $cur = $dict;
    foreach ($parts as $p) {
        if (!is_array($cur) || !array_key_exists($p, $cur)) return (string)($default ?? '');
        $cur = $cur[$p];
    }
    return is_string($cur) ? $cur : (string)($default ?? '');
}

function render_template(string $template, array $vars): string {
    // HTML-escape variables by default; keeps emails safe if rendered as HTML later
    $safeVars = [];
    foreach ($vars as $k => $v) {
        $safeVars[$k] = htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }

    return preg_replace_callback('/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/', function ($m) use ($safeVars) {
        $key = $m[1];
        return array_key_exists($key, $safeVars) ? $safeVars[$key] : '';
    }, $template) ?? $template;
}

/**
 * Build a localized email (subject + body) for a given template key.
 */
function build_localized_email(string $lang, string $templateRootKey, array $vars, string $baseDir): array {
    $dict = i18n_load($lang, $baseDir);

    // fallback dict if missing template in selected language
    $fallbackDict = i18n_load('en', $baseDir);

    $subject = i18n_get($dict, "{$templateRootKey}.subject", i18n_get($fallbackDict, "{$templateRootKey}.subject", ''));
    $body    = i18n_get($dict, "{$templateRootKey}.body",    i18n_get($fallbackDict, "{$templateRootKey}.body", ''));

    return [
        'subject' => render_template($subject, $vars),
        'body'    => render_template($body, $vars),
    ];
}
