<?php

namespace Axioma;

class Lang
{
    private static $DEFAULT_LANGUAGE = 'ru_RU';

    public static function serverLanguage()
    {
        $server_language = self::$DEFAULT_LANGUAGE;
        if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $parts = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
            $parts = explode(';', $parts[0]);
        }
        if (isset($_COOKIE['lang'])) {
            $server_language = $_COOKIE['lang'];
        } else {
            if (version_compare(PHP_VERSION, '7.3.0', '<')) {
                header("Set-Cookie: lang=$server_language; SameSite=Lax", false);
            } else {
                setcookie(
                    'lang',
                    $server_language,
                    array('expires' => time() + 60 * 60 * 12, 'path' => '/', 'samesite' => 'Lax')
                );
            }
        }
        return $server_language;
    }

    public static function logoPath()
    {
        $supported_languages = array('ru');
        $lang = substr(self::serverLanguage(), 0, 2);
        if (!in_array($lang, $supported_languages)) {
            $lang = $supported_languages[0];
        }
        return "images/logo_$lang.png";
    }

    public static function init()
    {
        if (function_exists('gettext')) {
            $language = self::serverLanguage();
            $codeset = 'UTF8';
            putenv("LANG=$language.$codeset");
            putenv("LANGUAGE=$language.$codeset");
            setlocale(LC_ALL, "$language.$codeset");
            if (is_dir(__DIR__ . "/../locale")) {
                $domain = "axioma-lm";
                bindtextdomain($domain, __DIR__ . "/../locale");
                bind_textdomain_codeset($domain, $codeset);
                textdomain($domain);
            }
        }
    }
}
