<?php

require_once __DIR__ . '/env_loader.php';
require_once __DIR__ . '/../src/Translate.php';

session_start();

function getCurrentLanguage(): string
{
    if (isset($_SESSION['user_language'])) {
        return $_SESSION['user_language'];
    }
    
    if (isset($_COOKIE['user_language'])) {
        $_SESSION['user_language'] = $_COOKIE['user_language'];
        return $_COOKIE['user_language'];
    }
    
    $defaultLang = 'es';
    $_SESSION['user_language'] = $defaultLang;
    return $defaultLang;
}

function setCurrentLanguage(string $langCode): void
{
    $_SESSION['user_language'] = $langCode;
    setcookie('user_language', $langCode, [
        'expires' => time() + (365 * 24 * 60 * 60),
        'path' => '/',
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Strict'
    ]);
}

function getActiveLanguages(): array
{
    static $languages = null;
    
    if ($languages !== null) {
        return $languages;
    }
    
    try {
        $pdo = getDbConnection();
        $stmt = $pdo->query("SELECT * FROM supported_languages WHERE is_active = 1 ORDER BY language_name");
        $languages = $stmt->fetchAll();
    } catch (Exception $e) {
        $languages = [];
    }
    
    return $languages;
}

function getBaseLanguage(): string
{
    return 'es';
}

function t(string $text, ?string $targetLang = null): string
{
    if (empty(trim($text))) {
        return $text;
    }
    
    $targetLang = $targetLang ?? getCurrentLanguage();
    $baseLang = getBaseLanguage();
    
    if ($targetLang === $baseLang) {
        return $text;
    }
    
    static $translator = null;
    static $cache = [];
    
    $cacheKey = md5($text . $targetLang);
    
    if (isset($cache[$cacheKey])) {
        return $cache[$cacheKey];
    }
    
    if ($translator === null) {
        $translator = new \src\Translate();
    }
    
    try {
        $translated = $translator->translate($text, $baseLang, $targetLang);
        
        if ($translated !== null) {
            $cache[$cacheKey] = $translated;
            return $translated;
        }
    } catch (Exception $e) {
        error_log("Translation error for '$text': " . $e->getMessage());
    }
    
    return $text;
}

function ta(array $texts): array
{
    $result = [];
    foreach ($texts as $key => $text) {
        $result[$key] = t($text);
    }
    return $result;
}

function handleLanguageChange(): void
{
    if (isset($_GET['lang'])) {
        $lang = $_GET['lang'];
        $activeLanguages = getActiveLanguages();
        $validLangs = array_column($activeLanguages, 'language_code');
        
        if (in_array($lang, $validLangs) || $lang === 'es') {
            setCurrentLanguage($lang);
        }
        
        $redirectUrl = strtok($_SERVER['REQUEST_URI'], '?');
        $queryParams = $_GET;
        unset($queryParams['lang']);
        
        if (!empty($queryParams)) {
            $redirectUrl .= '?' . http_build_query($queryParams);
        }
        
        header('Location: ' . $redirectUrl);
        exit;
    }
}
