<?php
declare(strict_types=1);

namespace Celena\Core\I18n;

use Celena\Core\Http\Request;

/**
 * Определяет активную локаль: ?lang=en > cookie > Accept-Language > дефолт.
 */
final class Locale
{
    public function __construct(
        private readonly string $default = 'ru',
        /** @var string[] */
        private readonly array $available = ['ru', 'en'],
    ) {
    }

    public function detect(?Request $request = null): string
    {
        if ($request !== null) {
            $q = (string) $request->query('lang', '');
            if ($q !== '' && in_array($q, $this->available, true)) {
                return $q;
            }
            $cookie = $request->cookie('celena_lang');
            if ($cookie !== null && in_array($cookie, $this->available, true)) {
                return $cookie;
            }
            $accept = (string) $request->header('accept-language');
            foreach (explode(',', $accept) as $part) {
                $lang = strtolower(substr(trim(explode(';', $part)[0]), 0, 2));
                if (in_array($lang, $this->available, true)) {
                    return $lang;
                }
            }
        }
        return $this->default;
    }

    public function remember(string $locale): void
    {
        if (!in_array($locale, $this->available, true)) {
            return;
        }
        if (!headers_sent()) {
            setcookie('celena_lang', $locale, [
                'expires' => time() + 86400 * 365,
                'path' => '/',
                'httponly' => false,
                'samesite' => 'Lax',
            ]);
        }
    }

    /** @return string[] */
    public function available(): array { return $this->available; }
    public function default(): string  { return $this->default; }
}
