<?php
$supportedLangs = ['en', 'id'];
$currentLang = 'en';

if (isset($_GET['lang']) && in_array($_GET['lang'], $supportedLangs, true)) {
    $currentLang = $_GET['lang'];
    setcookie('site_lang', $currentLang, time() + (60 * 60 * 24 * 30), '/');
} elseif (isset($_COOKIE['site_lang']) && in_array($_COOKIE['site_lang'], $supportedLangs, true)) {
    $currentLang = $_COOKIE['site_lang'];
}

function current_lang()
{
    global $currentLang;

    return $currentLang;
}

function lang_text($english, $indonesian)
{
    return current_lang() === 'id' ? $indonesian : $english;
}

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

function tr($english, $indonesian)
{
    return h(lang_text($english, $indonesian));
}

function trh($english, $indonesian)
{
    return lang_text($english, $indonesian);
}

function app_url($targetPage = 'home', $langOverride = null, $fragment = '')
{
    $lang = $langOverride ?: current_lang();
    $siteBase = defined('BASE_URL') ? BASE_URL : '/';
    $base = rtrim($siteBase, '/') . '/' . $lang . '/';

    $url = ($targetPage && $targetPage !== 'home')
    ? $base . $targetPage
    : $base;

    if ($fragment !== '') {
        $url .= '#' . rawurlencode(ltrim($fragment, '#'));
    }

    return $url;
}

function lang_switch_url($langOverride)
{
    global $page;
    return app_url($page, $langOverride);
}
