<?php
/**
 * (c) ININOUT & PYXIS. All Rights Reserved.
 * Wszelkie modyfikacje tego pliku wymagaja zgloszenia oraz zgody autorow.
 * Any modifications to this file require notification and consent of the authors.
 */
/**
 * i-BOK 5 - System tłumaczeń (i18n)
 *
 * Użycie:
 *   require_once __DIR__ . '/lang/loader.php';
 *   load_language();
 *   echo __('common.save');
 */

define('IBOK_AVAILABLE_LANGS', ['pl', 'en']);
define('IBOK_DEFAULT_LANG', 'pl');

$LANG = [];
$CURRENT_LANG = IBOK_DEFAULT_LANG;

function load_language($lang = null) {
    global $LANG, $CURRENT_LANG;

    if (!$lang) {
        if (isset($_GET['lang']) && in_array($_GET['lang'], IBOK_AVAILABLE_LANGS)) {
            $lang = $_GET['lang'];
        } elseif (isset($_SESSION['lang']) && in_array($_SESSION['lang'], IBOK_AVAILABLE_LANGS)) {
            $lang = $_SESSION['lang'];
        } elseif (isset($_COOKIE['ibok_lang']) && in_array($_COOKIE['ibok_lang'], IBOK_AVAILABLE_LANGS)) {
            $lang = $_COOKIE['ibok_lang'];
        } else {
            $lang = IBOK_DEFAULT_LANG;
        }
    }

    if (!in_array($lang, IBOK_AVAILABLE_LANGS)) {
        $lang = IBOK_DEFAULT_LANG;
    }

    if (session_status() === PHP_SESSION_ACTIVE) {
        $_SESSION['lang'] = $lang;
    }

    if (!headers_sent()) {
        if (!isset($_COOKIE['ibok_lang']) || $_COOKIE['ibok_lang'] !== $lang) {
            setcookie('ibok_lang', $lang, [
                'expires' => time() + 86400 * 365,
                'path' => '/',
                'httponly' => true,
                'samesite' => 'Lax'
            ]);
        }
    }

    $CURRENT_LANG = $lang;

    $langFile = __DIR__ . "/{$lang}.php";
    if (file_exists($langFile)) {
        $LANG = require $langFile;
    } else {
        $LANG = require __DIR__ . "/" . IBOK_DEFAULT_LANG . ".php";
    }

    return $lang;
}

function __($key, $params = []) {
    global $LANG;
    $keys = explode('.', $key);
    $value = $LANG;

    foreach ($keys as $k) {
        if (!is_array($value) || !isset($value[$k])) {
            return "[$key]";
        }
        $value = $value[$k];
    }

    if (!is_string($value)) return "[$key]";

    foreach ($params as $param => $val) {
        $value = str_replace(':' . $param, $val, $value);
    }

    return $value;
}

function t($key, $params = []) {
    return __($key, $params);
}

function get_current_language() {
    global $CURRENT_LANG;
    return $CURRENT_LANG;
}
