<?php
declare(strict_types=1);

namespace App\Core;

class Lang
{
    private static array $config = [];
    private static array $lines = [];

    public static function boot(array $config): void
    {
        self::$config = $config;

        $supported = $config['supported_languages'] ?? ['tr'];
        $default = $config['DEFAULT_LANGUAGE'] ?? 'tr';
        $user = Session::get('auth_user', []);
        $userLang = is_array($user) ? ($user['language'] ?? null) : null;
        $lang = $_GET['lang'] ?? Session::get('lang') ?? $userLang ?? $_COOKIE['lang'] ?? $default;

        if (!in_array($lang, $supported, true)) {
            $lang = $default;
        }

        Session::put('lang', $lang);
        $file = BASE_PATH . '/app/Lang/' . $lang . '.php';
        self::$lines = is_file($file) ? require $file : [];
    }

    public static function current(): string
    {
        return (string) Session::get('lang', self::$config['DEFAULT_LANGUAGE'] ?? 'tr');
    }

    public static function get(string $key, array $replace = []): string
    {
        $text = self::$lines[$key] ?? $key;

        foreach ($replace as $name => $value) {
            $text = str_replace(':' . $name, (string) $value, $text);
        }

        return $text;
    }
}
