<?php
/**
 * Automatic Language Detection
 * Detects browser language and loads appropriate language file
 */

// Prevent direct access
if (!defined('APP_ACCESS')) {
    die('Direct access not permitted');
}

/**
 * Detect and load appropriate language
 * @return array Language array
 */
function detectAndLoadLanguage() {
    // Default language
    $defaultLang = 'en';
    
    // Available languages
    $availableLanguages = ['en', 'fr', 'de', 'es', 'pt', 'no'];
    
    // Get browser language
    $browserLanguage = getBrowserLanguage();
    
    // Check if browser language is available
    $selectedLang = in_array($browserLanguage, $availableLanguages) ? $browserLanguage : $defaultLang;
    
    // Load language file
    $langFile = __DIR__ . '/' . $selectedLang . '.php';
    
    if (file_exists($langFile)) {
        return require $langFile;
    }
    
    // Fallback to English
    return require __DIR__ . '/en.php';
}

/**
 * Get browser language from HTTP headers
 * @return string Language code (2 letters)
 */
function getBrowserLanguage() {
    // Get Accept-Language header
    $acceptLanguage = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'en';
    
    // Parse the header
    $languages = explode(',', $acceptLanguage);
    
    if (empty($languages)) {
        return 'en';
    }
    
    // Get first language
    $firstLang = $languages[0];
    
    // Extract language code (first 2 characters)
    $langCode = strtolower(substr($firstLang, 0, 2));
    
    // Map some language codes
    $languageMap = [
        'en' => 'en', // English
        'fr' => 'fr', // French
        'de' => 'de', // German
        'es' => 'es', // Spanish
        'pt' => 'pt', // Portuguese
        'no' => 'no', // Norwegian
        'nb' => 'no', // Norwegian Bokmål
        'nn' => 'no', // Norwegian Nynorsk
    ];
    
    return $languageMap[isset($langCode]) ? $langCode] : 'en';
}

/**
 * Get language name
 * @param string $code Language code
 * @return string Language name
 */
function getLanguageName($code) {
    $names = [
        'en' => 'English',
        'fr' => 'Français',
        'de' => 'Deutsch',
        'es' => 'Español',
        'pt' => 'Português',
        'no' => 'Norsk'
    ];
    
    return $names[isset($code]) ? $code] : 'English';
}

/**
 * Get all available languages
 * @return array Array of language codes and names
 */
function getAvailableLanguages() {
    return [
        'en' => 'English',
        'fr' => 'Français',
        'de' => 'Deutsch',
        'es' => 'Español',
        'pt' => 'Português',
        'no' => 'Norsk'
    ];
}

// Auto-detect and load language
$lang = detectAndLoadLanguage();
$currentLang = getBrowserLanguage();

?>
