<?php

namespace Openguru\OpenCartFramework\Translator;

use RuntimeException;

class Translator implements TranslatorInterface
{
    private $language;
    private $translations;

    public function __construct(string $language, array $translations = [])
    {
        $this->language = $language;
        $this->translations = $translations;
    }

    public function loadTranslationsFromFolder(string $directory): void
    {
        if (!is_dir($directory)) {
            throw new RuntimeException('Translations folder not found.');
        }

        $filename = $directory . "/{$this->language}.php";
        if (!is_file($filename)) {
            throw new RuntimeException("Translation file for language '{$this->language}' not found.");
        }

        $translations = include $filename;
        $this->translations = array_merge($this->translations, $translations);
    }

    public function translate(string $key, array $params = []): string
    {
        if (isset($this->translations[$key])) {
            return $this->substitute($this->translations[$key], $params);
        }

        return $key;
    }

    public function getTranslations(): array
    {
        return $this->translations;
    }

    public function getLanguage(): string
    {
        return $this->language;
    }

    private function substitute($text, array $parameters): string
    {
        if (!$parameters) {
            return $text;
        }

        $search = array_map(static function ($param) {
            return '{' . $param . '}';
        }, array_keys($parameters));

        return str_replace($search, array_values($parameters), $text);
    }
}
