<?php

require_once __DIR__ . '/auth.php';

function available_languages(): array
{
    return ['de', 'en', 'it', 'fr'];
}

function detect_browser_language(): string
{
    $accept = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
    if ($accept === '') {
        return 'de';
    }

    $langs = explode(',', $accept);
    foreach ($langs as $lang) {
        $lang = strtolower(substr(trim($lang), 0, 2));
        if (in_array($lang, available_languages(), true)) {
            return $lang;
        }
    }

    return 'de';
}

function current_language(?string $forceLang = null): string
{
    static $lang = null;

    if ($forceLang !== null) {
        $forceLang = strtolower(trim($forceLang));

        if (in_array($forceLang, available_languages(), true)) {
            $lang = $forceLang;
            $_SESSION['ui_language'] = $forceLang;
            return $lang;
        }
    }

    if ($lang !== null) {
        return $lang;
    }

    // 1) eingeloggter Benutzer
    $user = current_user();
    if ($user && !empty($user['ui_language'])) {
        $lang = $user['ui_language'];
    }

    // 2) Session
    elseif (!empty($_SESSION['ui_language'])) {
        $lang = $_SESSION['ui_language'];
    }

    // 3) Browser
    else {
        $lang = detect_browser_language();
    }

    if (!in_array($lang, available_languages(), true)) {
        $lang = 'de';
    }

    return $lang;
}

function t(string $key, ?string $fallback = null): string
{
    static $translations = [];

    $lang = current_language();

    if (!isset($translations[$lang])) {
        $file = __DIR__ . '/../i18n/' . $lang . '.php';

        if (is_file($file)) {
            $translations[$lang] = require $file;
        } else {
            $translations[$lang] = [];
        }
    }

    return $translations[$lang][$key] ?? ($fallback ?? $key);
}

function render_language_switcher(?string $redirect = null): string
{
    $currentLang = current_language();
    $langs = available_languages();

    if ($redirect === null || trim($redirect) === '') {
        $redirect = $_SERVER['REQUEST_URI'] ?? '/dashboard.php';
    }

    $parts = [];
    foreach ($langs as $lang) {
        $label = strtoupper($lang);

        if ($lang === $currentLang) {
            $parts[] = '<strong>' . e($label) . '</strong>';
        } else {
            $href = '/set_language.php?lang=' . rawurlencode($lang) . '&redirect=' . rawurlencode($redirect);
            $parts[] = '<a href="' . e($href) . '">' . e($label) . '</a>';
        }
    }

    return t('nav.language', 'Sprache') . ': ' . implode(' | ', $parts);
}
