<?php
declare(strict_types=1);

$config = require dirname(__DIR__) . '/config.php';

function h(?string $value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

/**
 * @return 'de'|'en'
 */
function detect_locale(): string
{
    if (isset($_GET['lang']) && ($_GET['lang'] === 'de' || $_GET['lang'] === 'en')) {
        return $_GET['lang'];
    }

    $header = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
    if ($header === '') {
        return 'de';
    }

    $preferred = [];
    foreach (explode(',', $header) as $part) {
        $part = trim($part);
        if ($part === '') {
            continue;
        }
        [$tag, $q] = array_pad(explode(';q=', $part, 2), 2, '1');
        $lang = strtolower(substr(trim($tag), 0, 2));
        $preferred[$lang] = (float) $q;
    }

    arsort($preferred);
    foreach (array_keys($preferred) as $lang) {
        if ($lang === 'de' || $lang === 'en') {
            return $lang;
        }
    }

    return 'de';
}

/**
 * @return array<string, mixed>
 */
function load_messages(string $locale): array
{
    $path = dirname(__DIR__) . '/lang/' . $locale . '.php';
    /** @var array<string, mixed> $messages */
    $messages = require $path;
    return $messages;
}

function t(array $messages, string $key, ?string $fallback = null): string
{
    $parts = explode('.', $key);
    $value = $messages;
    foreach ($parts as $part) {
        if (!is_array($value) || !array_key_exists($part, $value)) {
            return $fallback ?? $key;
        }
        $value = $value[$part];
    }
    return is_string($value) ? $value : ($fallback ?? $key);
}

function bot_invite_url(array $config): string
{
    return 'https://discord.com/api/oauth2/authorize?' . http_build_query([
        'client_id' => (string) $config['bot_client_id'],
        'permissions' => '4786708802825463',
        'scope' => 'bot applications.commands',
    ], '', '&', PHP_QUERY_RFC3986);
}
