<?php
/**
 * Language Loader - loads translations and sets session language
 * Usage: require_once __DIR__ . '/lang.php';
 *        Then use $t['key'] or the __() helper.
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Determine language: URL param > session > default (Arabic)
if (isset($_GET['lang']) && in_array($_GET['lang'], ['ar', 'en'])) {
    $_SESSION['lang'] = $_GET['lang'];
}
$currentLang = $_SESSION['lang'] ?? 'ar';

// Load translation array
$langFile = dirname(__DIR__, 2) . '/lang/' . $currentLang . '.php';
$t = file_exists($langFile) ? require $langFile : require dirname(__DIR__, 2) . '/lang/ar.php';

/**
 * Translation helper – returns the translated string for a given key.
 */
function __($key) {
    global $t;
    return $t[$key] ?? $key;
}

/**
 * Build a URL that switches to the other language,
 * preserving all existing query parameters except 'lang'.
 */
function lang_switch_url($targetLang) {
    $params = $_GET;
    $params['lang'] = $targetLang;
    // Remove the page itself from params (keep path clean)
    return '?' . http_build_query($params);
}
