<?php

namespace SSCI\Classes;

/**
 * Language/Localization Class
 * Handles bilingual support
 */
class Language
{
    private static ?string $currentLanguage = null;
    private static array $translations = [];

    /**
     * Initialize language
     */
    public static function init(): void
    {
        // Get from session, cookie, or browser
        self::$currentLanguage = $_SESSION['language'] ?? $_COOKIE['language'] ?? 'en';

        if (!in_array(self::$currentLanguage, ['en', 'fr'])) {
            self::$currentLanguage = 'en';
        }

        self::loadLanguage(self::$currentLanguage);
        
        // Handle language switch from URL parameter
        self::handleLanguageSwitch();
    }

    /**
     * Handle language change from URL parameter and redirect
     */
    public static function handleLanguageSwitch(): void
    {
        // Check if language parameter is in URL
        if (isset($_GET['lang']) && in_array($_GET['lang'], ['en', 'fr'])) {
            $newLang = $_GET['lang'];
            
            // Only redirect if language is different from current
            if ($newLang !== self::$currentLanguage) {
                self::loadLanguage($newLang);
                
                // Build redirect URL without the lang parameter
                $currentUrl = strtok($_SERVER['REQUEST_URI'], '?');
                $query = $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : '';
                
                // Remove lang parameter from query string
                $query = preg_replace('/([&?])lang=[^&]*/', '', $query);
                $query = preg_replace('/^\?&/', '?', $query);
                $query = $query === '?' ? '' : $query;
                
                // Redirect to same page without lang parameter
                $redirectUrl = $currentUrl . $query;
                header('Location: ' . $redirectUrl);
                exit();
            }
        }
    }

    /**
     * Load language file
     */
    public static function loadLanguage(string $lang): void
    {
        $path = __DIR__ . '/../../lang/' . $lang . '.php';

        if (file_exists($path)) {
            self::$translations = require $path;
            self::$currentLanguage = $lang;
            $_SESSION['language'] = $lang;
            setcookie('language', $lang, time() + (365 * 24 * 60 * 60), '/');
        }
    }

    /**
     * Get current language
     */
    public static function getCurrentLanguage(): string
    {
        return self::$currentLanguage ?? 'en';
    }

    /**
     * Get translated string
     */
    public static function get(string $key, array $replace = []): string
    {
        $text = self::$translations[$key] ?? $key;

        foreach ($replace as $search => $value) {
            $text = str_replace(':' . $search, $value, $text);
        }

        return $text;
    }

    /**
     * Check if RTL language
     */
    public static function isRTL(): bool
    {
        return false; // EN and FR are LTR languages
    }

    /**
     * Get text direction
     */
    public static function getDirection(): string
    {
        return 'ltr'; // English and French are always left-to-right
    }
}
