<?php
/**
 * Multi-language support functions
 * Çoklu dil desteği fonksiyonları
 */

// Language metadata - will be populated dynamically
$available_languages = [];

// Language metadata mapping (code => [name, flag, locale])
$language_metadata = [
    'tr' => ['Türkçe', '', 'tr_TR.UTF-8'],
    'en' => ['English', '', 'en_US.UTF-8'],
    'de' => ['Deutsch', '', 'de_DE.UTF-8']
    // Add more languages here as needed
];

// Language files directory / Dil dosyaları dizini
define('LANG_DIR', __DIR__ . '/../languages/');

/**
 * Get current user language from session or database
 * Mevcut kullanıcı dilini oturum veya veritabanından al
 */
function getCurrentLanguage() {
    global $db;
    
    // First check session / Önce oturumu kontrol et
    if (isset($_SESSION['user_language'])) {
        return $_SESSION['user_language'];
    }
    
    // If user is logged in, get from database / Kullanıcı giriş yapmışsa veritabanından al
    if (isset($_SESSION['kullanici_id'])) {
        try {
            $stmt = $db->prepare("SELECT dil FROM kullanicilar WHERE id = ?");
            $stmt->execute([$_SESSION['kullanici_id']]);
            $language = $stmt->fetchColumn();
            
            if ($language) {
                $_SESSION['user_language'] = $language;
                return $language;
            }
        } catch (PDOException $e) {
            error_log("Language fetch error: " . $e->getMessage());
        }
    }
    
    // Default language / Varsayılan dil
    return 'tr';
}

/**
 * Set user language
 * Kullanıcı dilini ayarla
 */
function setUserLanguage($language) {
    global $db;
    
    // Validate language / Dili doğrula
    if (!in_array($language, array_keys(getAvailableLanguages()))) {
        return false;
    }
    
    // Update session / Oturumu güncelle
    $_SESSION['user_language'] = $language;
    
    // Update database if user is logged in / Kullanıcı giriş yapmışsa veritabanını güncelle
    if (isset($_SESSION['kullanici_id'])) {
        try {
            $stmt = $db->prepare("UPDATE kullanicilar SET dil = ? WHERE id = ?");
            $stmt->execute([$language, $_SESSION['kullanici_id']]);
            return true;
        } catch (PDOException $e) {
            error_log("Language update error: " . $e->getMessage());
            return false;
        }
    }
    
    return true;
}

/**
 * Load language file
 * Dil dosyasını yükle
 */
function loadLanguageFile($language) {
    $file_path = LANG_DIR . $language . '.php';
    
    if (file_exists($file_path)) {
        return include $file_path;
    }
    
    // Fallback to Turkish if language file doesn't exist
    // Dil dosyası yoksa Türkçe'ye geri dön
    $fallback_path = LANG_DIR . 'tr.php';
    if (file_exists($fallback_path)) {
        return include $fallback_path;
    }
    
    return [];
}

/**
 * Get translation
 * Çeviri al
 */
function __($key, $params = []) {
    static $translations = null;
    
    if ($translations === null) {
        $current_language = getCurrentLanguage();
        $translations = loadLanguageFile($current_language);
    }
    
    // Get translation / Çeviriyi al
    $translation = $translations[$key] ?? $key;
    
    // Replace parameters if provided / Parametreler verilmişse değiştir
    if (!empty($params)) {
        foreach ($params as $param_key => $param_value) {
            $translation = str_replace(':' . $param_key, $param_value, $translation);
        }
    }
    
    return $translation;
}

/**
 * Echo translation
 * Çeviriyi yazdır
 */
function _e($key, $params = []) {
    echo __($key, $params);
}

/**
 * Get available languages
 * Mevcut dilleri al
 */
function getAvailableLanguages() {
    global $available_languages;
    
    // If already populated, return cached version
    if (!empty($available_languages)) {
        return $available_languages;
    }
    
    // Scan languages directory for PHP files
    $language_files = glob(LANG_DIR . '*.php');
    $languages = [];
    
    foreach ($language_files as $file) {
        $lang_code = basename($file, '.php');
        
        // Skip non-language files (like index.php if it exists)
        if (strlen($lang_code) !== 2 && strlen($lang_code) !== 5) {
            continue;
        }
        
        // Get metadata from our mapping or use defaults
        if (isset($GLOBALS['language_metadata'][$lang_code])) {
            $meta = $GLOBALS['language_metadata'][$lang_code];
            $languages[$lang_code] = [
                'name' => $meta[0],
                'flag' => $meta[1],
                'locale' => $meta[2] ?? $lang_code . '_' . strtoupper($lang_code) . '.UTF-8'
            ];
        } else {
            // Fallback for languages not in our metadata
            $lang_name = ucfirst($lang_code);
            $languages[$lang_code] = [
                'name' => $lang_name,
                'flag' => '',
                'locale' => $lang_code . '_' . strtoupper($lang_code) . '.UTF-8'
            ];
        }
    }
    
    // Cache the result
    $available_languages = $languages;
    
    return $languages;
}

/**
 * Initialize language system
 * Dil sistemini başlat
 */
function initLanguageSystem() {
    // Set default timezone
    date_default_timezone_set('Europe/Istanbul');
    
    // Start session if not already started
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // Initialize available languages
    $languages = getAvailableLanguages();
    
    // Get current language
    $current_language = getCurrentLanguage();
    
    // Validate current language exists, if not fallback to first available or 'tr'
    if (!isset($languages[$current_language])) {
        $current_language = !empty($languages) ? key($languages) : 'tr';
        $_SESSION['user_language'] = $current_language;
    }
    
    // Load language file
    $translations = loadLanguageFile($current_language);
    
    // Set locale
    $locale = $languages[$current_language]['locale'] ?? 'tr_TR.UTF-8';
    setlocale(LC_ALL, $locale);
    
    // Set content type and charset
    header('Content-Type: text/html; charset=utf-8');
    
    return $translations;
}

/**
 * Format number according to language
 * Dile göre sayı formatla
 */
function formatNumber($number, $decimals = 2) {
    $current_language = getCurrentLanguage();
    
    if ($current_language === 'tr') {
        return number_format($number, $decimals, ',', '.');
    } else {
        return number_format($number, $decimals, '.', ',');
    }
}

/**
 * Format date according to language
 * Dile göre tarih formatla
 */
function formatDate($date, $format = null) {
    $current_language = getCurrentLanguage();
    
    if ($format === null) {
        $format = ($current_language === 'tr') ? 'd.m.Y' : 'm/d/Y';
    }
    
    return date($format, strtotime($date));
}

/**
 * Format datetime according to language
 * Dile göre tarih-saat formatla
 */
function formatDateTime($datetime, $format = null) {
    $current_language = getCurrentLanguage();
    
    if ($format === null) {
        $format = ($current_language === 'tr') ? 'd.m.Y H:i' : 'm/d/Y H:i';
    }
    
    return date($format, strtotime($datetime));
}
