<?php

$SYSTEM_SETTINGS = null;

function get_system_settings() {
    global $db, $SYSTEM_SETTINGS;
    
    if ($SYSTEM_SETTINGS !== null) {
        return $SYSTEM_SETTINGS;
    }

    if (!isset($db)) {
        require_once __DIR__ . '/db/config.php';
        try {
            $local_db = db();
        } catch (Exception $e) {
            // If DB connection fails, return empty settings instead of crashing
            return [];
        }
    } else {
        $local_db = $db;
    }
    
    try {
        $stmt = $local_db->query('SELECT setting_key, setting_value FROM settings');
        $settings = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }
        $SYSTEM_SETTINGS = $settings;
        return $settings;
    } catch (Exception $e) {
        return [];
    }
}

function apply_timezone() {
    try {
        $s = get_system_settings();
        if (!empty($s['timezone'])) {
            date_default_timezone_set($s['timezone']);
        }
    } catch (Exception $e) {
        // Ignore timezone errors
    }
}
apply_timezone();

function format_currency($amount) {
    $settings = get_system_settings();
    $currency_symbol = $settings['currency_symbol'] ?? '$';
    $decimal_digits = isset($settings['decimal_digits']) ? (int)$settings['decimal_digits'] : 2;
    
    return $currency_symbol . ' ' . number_format((float)$amount, $decimal_digits);
}

// Only start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/lang.php';

if (!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = 'en';
}

if (isset($_GET['lang'])) {
    if ($_GET['lang'] === 'ar' || $_GET['lang'] === 'en') {
        $_SESSION['lang'] = $_GET['lang'];
        // Redirect to remove lang param
        if (!headers_sent()) {
            header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
            exit;
        }
    }
}

function __($key) {
    global $translations;
    $lang = $_SESSION['lang'] ?? 'en'; // Fallback if session is empty
    return $translations[$lang][$key] ?? $key;
}

function is_rtl() {
    return ($_SESSION['lang'] ?? 'en') === 'ar';
}

function get_dir() {
    return is_rtl() ? 'rtl' : 'ltr';
}

function get_lang_name() {
    return ($_SESSION['lang'] ?? 'en') === 'ar' ? 'English' : 'العربية';
}

function get_lang_code() {
    return $_SESSION['lang'] ?? 'en';
}

function calculate_age($dob) {
    if (empty($dob)) return '-';
    try {
        $birthDate = new DateTime($dob);
        $today = new DateTime('today');
        return $birthDate->diff($today)->y;
    } catch (Exception $e) {
        return '-';
    }
}

if (!function_exists('mb_strimwidth')) {
    function mb_strimwidth($string, $start, $width, $trimmarker = '...', $encoding = null) {
        // Simple polyfill using substr
        // 1. Handle start offset
        $string = (string)$string;
        if ($start > 0) {
            $string = substr($string, $start);
        }
        
        // 2. Check length
        if (strlen($string) <= $width) {
            return $string;
        }
        
        // 3. Truncate
        $targetLen = $width - strlen($trimmarker);
        if ($targetLen < 0) $targetLen = 0;
        
        return substr($string, 0, $targetLen) . $trimmarker;
    }
}