<?php

namespace KeyLair;

// Translations live in src/lang/strings.csv (key,en,de,... one column per
// language) rather than in PHP so the file can be handed to a translation
// service and edited in a spreadsheet. Adding a language is: add a column
// to the CSV, add one entry to AVAILABLE below.
class I18n
{
    public const AVAILABLE = [
        'en' => 'English',
        'de' => 'Deutsch',
        'fr' => 'Français',
        'es' => 'Español',
    ];

    public const DEFAULT_LOCALE = 'en';

    private const CSV_PATH = __DIR__ . '/lang/strings.csv';

    /** @var array<string, array<string, string>>|null */
    private static ?array $strings = null;

    private static string $locale = self::DEFAULT_LOCALE;

    public static function setLocale(?string $locale): void
    {
        self::$locale = isset(self::AVAILABLE[$locale]) ? $locale : self::DEFAULT_LOCALE;
    }

    public static function locale(): string
    {
        return self::$locale;
    }

    public static function t(string $key): string
    {
        $rows = self::load();
        $row = $rows[$key] ?? null;

        if ($row === null) {
            return $key;
        }

        return $row[self::$locale] ?? $row[self::DEFAULT_LOCALE] ?? $key;
    }

    /** @return array<string, array<string, string>> */
    private static function load(): array
    {
        if (self::$strings !== null) {
            return self::$strings;
        }

        self::$strings = [];

        $handle = fopen(self::CSV_PATH, 'r');
        if ($handle === false) {
            return self::$strings;
        }

        $header = fgetcsv($handle);
        if ($header === false) {
            fclose($handle);
            return self::$strings;
        }

        while (($row = fgetcsv($handle)) !== false) {
            $key = $row[0] ?? null;
            if ($key === null || $key === '') {
                continue;
            }

            $values = [];
            foreach ($header as $i => $locale) {
                if ($i === 0) {
                    continue;
                }
                $values[$locale] = $row[$i] ?? '';
            }

            self::$strings[$key] = $values;
        }

        fclose($handle);

        return self::$strings;
    }
}
