<?php
declare(strict_types=1);

class Languages
{
    private string $file;

    private array $available = [
        ['code' => 'de', 'label' => 'Deutsch'],
        ['code' => 'en', 'label' => 'English'],
        ['code' => 'es', 'label' => 'Español'],
        ['code' => 'fr', 'label' => 'Français'],
        ['code' => 'it', 'label' => 'Italiano'],
        ['code' => 'pt', 'label' => 'Português'],
        ['code' => 'nl', 'label' => 'Nederlands'],
        ['code' => 'pl', 'label' => 'Polski'],
        ['code' => 'ru', 'label' => 'Русский'],
        ['code' => 'tr', 'label' => 'Türkçe'],
    ];

    public function __construct(string $dataDir)
    {
        $this->file = $dataDir . '/languages.json';
    }

    public function get(): array
    {
        if (!file_exists($this->file)) {
            return ['default' => 'de', 'available' => [['code' => 'de', 'label' => 'Deutsch', 'active' => true]]];
        }
        return json_decode(file_get_contents($this->file), true) ?? [];
    }

    public function update(array $input): array
    {
        $current = $this->get();

        // Update default language
        if (!empty($input['default'])) {
            $current['default'] = preg_replace('/[^a-z]/', '', $input['default']);
        }

        // Update available languages list
        if (isset($input['available']) && is_array($input['available'])) {
            $validCodes = array_column($this->available, 'code');
            $updated    = [];

            foreach ($input['available'] as $lang) {
                $code = preg_replace('/[^a-z]/', '', $lang['code'] ?? '');
                if (!in_array($code, $validCodes, true)) continue;
                // Default lang can never be inactive
                $active = ($code === $current['default']) ? true : (bool)($lang['active'] ?? false);
                $label  = array_column($this->available, 'label', 'code')[$code] ?? $code;
                $updated[] = ['code' => $code, 'label' => $label, 'active' => $active];
            }

            // Ensure default is always in the list
            $codes = array_column($updated, 'code');
            if (!in_array($current['default'], $codes, true)) {
                $label = array_column($this->available, 'label', 'code')[$current['default']] ?? $current['default'];
                array_unshift($updated, ['code' => $current['default'], 'label' => $label, 'active' => true]);
            }

            $current['available'] = $updated;
        }

        $tmp = $this->file . '.tmp';
        file_put_contents($tmp, json_encode($current, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
        rename($tmp, $this->file);

        return $current;
    }

    public function getAvailableList(): array
    {
        return $this->available;
    }
}
