<?php
declare(strict_types=1);

class Navigation
{
    private string $file;

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

    public function get(): array
    {
        if (!file_exists($this->file)) return ['enabled' => false, 'labels' => []];
        return json_decode(file_get_contents($this->file), true) ?? ['enabled' => false, 'labels' => []];
    }

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

        if (isset($input['enabled'])) {
            $d['enabled'] = (bool)$input['enabled'];
        }

        if (isset($input['labels']) && is_array($input['labels'])) {
            $labels = [];
            foreach ($input['labels'] as $id => $langs) {
                // Section IDs are UUIDs (hex + dashes)
                if (!preg_match('/^[a-f0-9\-]{8,40}$/', (string)$id)) continue;
                $labels[$id] = [];
                if (is_array($langs)) {
                    foreach ($langs as $lang => $text) {
                        if (!preg_match('/^[a-z]{2}$/', (string)$lang)) continue;
                        $labels[$id][$lang] = htmlspecialchars(strip_tags((string)$text), ENT_QUOTES, 'UTF-8');
                    }
                }
            }
            $d['labels'] = empty($labels) ? new \stdClass() : $labels;
        }

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