<?php
/**
 * Central Settings Management
 * Loads all system settings from database tables (charity_settings, smtp_settings)
 */

if (!function_exists('get_settings')) {
    function get_settings() {
        static $settings = null;
        if ($settings === null) {
            try {
                // Fetch Charity Info
                $charity_stmt = db()->query("SELECT * FROM charity_settings WHERE id = 1");
                $charity = $charity_stmt->fetch();
                
                // Fetch SMTP Info
                $smtp_stmt = db()->query("SELECT * FROM smtp_settings WHERE id = 1");
                $smtp = $smtp_stmt->fetch();
                
                $settings = [
                    'site_name' => $charity['charity_name'] ?? 'نظام إدارة البريد',
                    'site_slogan' => $charity['charity_slogan'] ?? '',
                    'site_email' => $charity['charity_email'] ?? '',
                    'site_phone' => $charity['charity_phone'] ?? '',
                    'site_address' => $charity['charity_address'] ?? '',
                    'site_logo' => $charity['charity_logo'] ?? '',
                    'site_favicon' => $charity['charity_favicon'] ?? '',
                    'site_maintenance' => (bool)($charity['site_maintenance'] ?? 0),
                    'site_footer' => $charity['site_footer'] ?? '',
                    'allow_registration' => (bool)($charity['allow_registration'] ?? 0),
                    
                    'smtp' => [
                        'host' => $smtp['smtp_host'] ?? '',
                        'port' => $smtp['smtp_port'] ?? 587,
                        'secure' => $smtp['smtp_secure'] ?? 'tls',
                        'user' => $smtp['smtp_user'] ?? '',
                        'pass' => $smtp['smtp_pass'] ?? '',
                        'from_email' => $smtp['from_email'] ?? '',
                        'from_name' => $smtp['from_name'] ?? '',
                        'reply_to' => $smtp['reply_to'] ?? '',
                        'enabled' => (bool)($smtp['is_enabled'] ?? 1),
                        'failures' => (int)($smtp['consecutive_failures'] ?? 0),
                        'max_failures' => (int)($smtp['max_failures'] ?? 5)
                    ]
                ];
            } catch (Exception $e) {
                // Fallback settings if DB is not ready
                $settings = [
                    'site_name' => 'نظام إدارة البريد',
                    'site_slogan' => '',
                    'site_maintenance' => false,
                    'smtp' => ['enabled' => false]
                ];
            }
        }
        return $settings;
    }
}

/**
 * Compatibility wrapper for getCharitySettings
 * @return array
 */
if (!function_exists('getCharitySettings')) {
    function getCharitySettings() {
        $settings = get_settings();
        // Return only the keys that might be expected by older code
        return [
            'charity_name' => $settings['site_name'],
            'charity_slogan' => $settings['site_slogan'],
            'charity_email' => $settings['site_email'],
            'charity_phone' => $settings['site_phone'],
            'charity_address' => $settings['site_address'],
            'charity_logo' => $settings['site_logo'],
            'charity_favicon' => $settings['site_favicon'],
            'site_maintenance' => $settings['site_maintenance'],
            'site_footer' => $settings['site_footer'],
            'allow_registration' => $settings['allow_registration']
        ];
    }
}

// Global settings variable
$sys_settings = get_settings();

// Maintenance Mode Check - only if not admin and not on login/logout
// Assuming isAdmin() exists, if not we should be careful
if ($sys_settings['site_maintenance'] && basename($_SERVER['PHP_SELF']) !== 'login.php' && basename($_SERVER['PHP_SELF']) !== 'logout.php') {
    // If isAdmin is not defined, we might need a fallback or just check session
    $is_admin = false;
    if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin') {
        $is_admin = true;
    }
    
    if (!$is_admin) {
        die("<h1>النظام تحت الصيانة حالياً</h1><p>يرجى المحاولة مرة أخرى في وقت لاحق.</p>");
    }
}