<?php
declare(strict_types=1);

namespace Celena\Core\I18n;

/**
 * Простейший переводчик. Загружает JSON-файлы локалей из указанных каталогов.
 * Ключ → строка с подстановкой :placeholder.
 */
final class Translator
{
    /** @var array<string, array<string, string>> */
    private array $messages = [];
    private string $locale;
    private string $fallback;

    public function __construct(string $locale = 'ru', string $fallback = 'en')
    {
        $this->locale = $locale;
        $this->fallback = $fallback;
    }

    public function setLocale(string $locale): void { $this->locale = $locale; }
    public function locale(): string                 { return $this->locale; }

    /** Подгрузить файл перевода. */
    public function loadFile(string $path, string $locale): void
    {
        if (!is_file($path)) {
            return;
        }
        $data = json_decode((string) file_get_contents($path), true);
        if (!is_array($data)) {
            return;
        }
        $this->messages[$locale] = array_merge($this->messages[$locale] ?? [], $this->flatten($data));
    }

    /** @param array<string, mixed> $params */
    public function translate(string $key, array $params = []): string
    {
        $message = $this->messages[$this->locale][$key]
            ?? $this->messages[$this->fallback][$key]
            ?? $key;
        foreach ($params as $k => $v) {
            $message = str_replace(':' . $k, (string) $v, $message);
        }
        return $message;
    }

    /** @param array<mixed> $array @return array<string, string> */
    private function flatten(array $array, string $prefix = ''): array
    {
        $out = [];
        foreach ($array as $k => $v) {
            $key = $prefix === '' ? (string) $k : $prefix . '.' . $k;
            if (is_array($v)) {
                $out = array_merge($out, $this->flatten($v, $key));
            } else {
                $out[$key] = (string) $v;
            }
        }
        return $out;
    }
}
