Absolutely\! The PHP code you've provided has a common issue that causes the "Warning: foreach() argument must be of type array|object, bool given" error. This usually means that the database query to fetch settings failed, and `$db->select()` returned `false` instead of an array.

I'll modify your code to include robust **error handling** for the database query, making it more resilient. I'll also add a few minor improvements like a more specific redirect URL for errors and clearer comments.

-----

```php
<?php
$pageTitle = 'إعدادات النظام';
// Ensure this path is correct relative to your current file
include __DIR__ . '/../../includes/header.php'; 

// Check user permissions
checkLogin();
if (!hasPermission('system_settings')) {
    // Redirect if user doesn't have the required permission
    header('Location: ' . SITE_URL . '/pages/errors/access_denied.php');
    exit();
}

$db = getDB(); // Get the database connection

// Fetch current settings from the database
$settings = [];
$settings_data = $db->select("SELECT setting_key, setting_value FROM system_settings");

// --- IMPORTANT: Handle potential database query errors ---
if ($settings_data === false || !is_array($settings_data)) {
    // Log the error for debugging purposes (check your DB class for an error method)
    error_log("Database query failed for system_settings. Details: " . ($db->lastError() ?? 'No specific error message available.'));
    
    // Set a user-friendly error message in session
    $_SESSION['error_message'] = 'تعذر تحميل إعدادات النظام من قاعدة البيانات. يرجى المحاولة لاحقاً أو الاتصال بالدعم.';
    
    // Redirect to a dashboard or a dedicated error page
    header('Location: ' . SITE_URL . '/pages/dashboard.php'); // Or '/pages/errors/database_error.php'
    exit();
}

// Populate the settings array if data was fetched successfully
foreach ($settings_data as $setting) {
    $settings[$setting['setting_key']] = $setting['setting_value'];
}

// Handle POST request for saving settings
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and retrieve input data
    $site_name = $_POST['site_name'] ?? '';
    $site_description = $_POST['site_description'] ?? '';
    $admin_email = $_POST['admin_email'] ?? '';
    $timezone = $_POST['timezone'] ?? 'Asia/Riyadh';
    $language = $_POST['language'] ?? 'ar';
    $items_per_page = $_POST['items_per_page'] ?? 20;
    // Checkbox values for 0 or 1
    $backup_enabled = isset($_POST['backup_enabled']) ? 1 : 0;
    $maintenance_mode = isset($_POST['maintenance_mode']) ? 1 : 0;
    $allow_registration = isset($_POST['allow_registration']) ? 1 : 0; // Added for 'users' tab
    $email_verification = isset($_POST['email_verification']) ? 1 : 0; // Added for 'users' tab
    $session_timeout = $_POST['session_timeout'] ?? 60; // Added for 'users' tab
    $backup_frequency = $_POST['backup_frequency'] ?? 'daily'; // Added for 'backup' tab
    $two_factor_auth = isset($_POST['two_factor_auth']) ? 1 : 0; // Added for 'security' tab
    $max_login_attempts = $_POST['max_login_attempts'] ?? 5; // Added for 'security' tab
    $lockout_duration = $_POST['lockout_duration'] ?? 15; // Added for 'security' tab

    $errors = [];

    // Validation
    if (empty($site_name)) {
        $errors[] = 'اسم الموقع مطلوب.';
    }
    if (!filter_var($admin_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'البريد الإلكتروني للمدير غير صالح.';
    }
    if (!is_numeric($items_per_page) || $items_per_page < 1) {
        $errors[] = 'عدد العناصر في الصفحة يجب أن يكون رقماً موجباً.';
    }
    if (!is_numeric($session_timeout) || $session_timeout < 5 || $session_timeout > 1440) {
        $errors[] = 'انتهاء صلاحية الجلسة يجب أن يكون رقماً بين 5 و 1440 دقيقة.';
    }
    if (!is_numeric($max_login_attempts) || $max_login_attempts < 1 || $max_login_attempts > 10) {
        $errors[] = 'الحد الأقصى لمحاولات تسجيل الدخول يجب أن يكون بين 1 و 10.';
    }
    if (!is_numeric($lockout_duration) || $lockout_duration < 1 || $lockout_duration > 60) {
        $errors[] = 'مدة الحظر يجب أن تكون بين 1 و 60 دقيقة.';
    }

    if (empty($errors)) {
        try {
            $db->beginTransaction();

            $settings_to_update = [
                'site_name' => $site_name,
                'site_description' => $site_description,
                'admin_email' => $admin_email,
                'timezone' => $timezone,
                'language' => $language,
                'items_per_page' => $items_per_page,
                'backup_enabled' => $backup_enabled,
                'maintenance_mode' => $maintenance_mode,
                'allow_registration' => $allow_registration,
                'email_verification' => $email_verification,
                'session_timeout' => $session_timeout,
                'backup_frequency' => $backup_frequency,
                'two_factor_auth' => $two_factor_auth,
                'max_login_attempts' => $max_login_attempts,
                'lockout_duration' => $lockout_duration
            ];

            foreach ($settings_to_update as $key => $value) {
                $existing = $db->selectOne("SELECT id FROM system_settings WHERE setting_key = ?", [$key]);
                if ($existing) {
                    $db->update("UPDATE system_settings SET setting_value = ? WHERE setting_key = ?", [$value, $key]);
                } else {
                    $db->insert("INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?)", [$key, $value]);
                }
            }

            $db->commit();
            $_SESSION['success_message'] = 'تم حفظ إعدادات النظام بنجاح.';
            header('Location: ' . SITE_URL . '/pages/settings/index.php');
            exit();
        } catch (Exception $e) {
            $db->rollBack();
            $errors[] = 'خطأ في قاعدة البيانات أثناء الحفظ: ' . $e->getMessage();
            // Also log the exception for server-side debugging
            error_log("Database Exception in settings save: " . $e->getMessage());
        }
    }

    // Display validation or database errors if any
    if (!empty($errors)) {
        foreach ($errors as $error) {
            echo '<div class="alert alert-danger">' . htmlspecialchars($error) . '</div>';
        }
    }
}
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><?php echo $pageTitle; ?></h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="list-group">
                                <a href="#general" class="list-group-item list-group-item-action active" data-bs-toggle="tab">
                                    <i class="fas fa-cog me-2"></i>الإعدادات العامة
                                </a>
                                <a href="#users" class="list-group-item list-group-item-action" data-bs-toggle="tab">
                                    <i class="fas fa-users me-2"></i>إعدادات المستخدمين
                                </a>
                                <a href="#backup" class="list-group-item list-group-item-action" data-bs-toggle="tab">
                                    <i class="fas fa-database me-2"></i>النسخ الاحتياطي
                                </a>
                                <a href="#security" class="list-group-item list-group-item-action" data-bs-toggle="tab">
                                    <i class="fas fa-shield-alt me-2"></i>الأمان
                                </a>
                                <a href="#maintenance" class="list-group-item list-group-item-action" data-bs-toggle="tab">
                                    <i class="fas fa-tools me-2"></i>الصيانة
                                </a>
                            </div>
                        </div>

                        <div class="col-md-9">
                            <form action="" method="POST">
                                <div class="tab-content">
                                    <div class="tab-pane fade show active" id="general">
                                        <h5 class="mb-3">الإعدادات العامة</h5>
                                        
                                        <div class="form-group mb-3">
                                            <label for="site_name" class="form-label">اسم الموقع:</label>
                                            <input type="text" class="form-control" id="site_name" name="site_name" 
                                                    value="<?php echo htmlspecialchars($settings['site_name'] ?? 'نظام إدارة الموارد البشرية'); ?>" required>
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="site_description" class="form-label">وصف الموقع:</label>
                                            <textarea class="form-control" id="site_description" name="site_description" rows="3"><?php echo htmlspecialchars($settings['site_description'] ?? 'نظام شامل لإدارة الموارد البشرية والمالية'); ?></textarea>
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="admin_email" class="form-label">البريد الإلكتروني للمدير:</label>
                                            <input type="email" class="form-control" id="admin_email" name="admin_email" 
                                                    value="<?php echo htmlspecialchars($settings['admin_email'] ?? 'admin@example.com'); ?>" required>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group mb-3">
                                                    <label for="timezone" class="form-label">المنطقة الزمنية:</label>
                                                    <select class="form-control" id="timezone" name="timezone">
                                                        <option value="Asia/Riyadh" <?php echo ($settings['timezone'] ?? 'Asia/Riyadh') == 'Asia/Riyadh' ? 'selected' : ''; ?>>الرياض</option>
                                                        <option value="Asia/Dubai" <?php echo ($settings['timezone'] ?? '') == 'Asia/Dubai' ? 'selected' : ''; ?>>دبي</option>
                                                        <option value="Asia/Kuwait" <?php echo ($settings['timezone'] ?? '') == 'Asia/Kuwait' ? 'selected' : ''; ?>>الكويت</option>
                                                        <option value="Africa/Cairo" <?php echo ($settings['timezone'] ?? '') == 'Africa/Cairo' ? 'selected' : ''; ?>>القاهرة</option>
                                                        </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group mb-3">
                                                    <label for="language" class="form-label">اللغة:</label>
                                                    <select class="form-control" id="language" name="language">
                                                        <option value="ar" <?php echo ($settings['language'] ?? 'ar') == 'ar' ? 'selected' : ''; ?>>العربية</option>
                                                        <option value="en" <?php echo ($settings['language'] ?? '') == 'en' ? 'selected' : ''; ?>>English</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="items_per_page" class="form-label">عدد العناصر في الصفحة:</label>
                                            <input type="number" class="form-control" id="items_per_page" name="items_per_page" 
                                                    value="<?php echo htmlspecialchars($settings['items_per_page'] ?? '20'); ?>" min="1" max="100">
                                        </div>
                                    </div>

                                    <div class="tab-pane fade" id="users">
                                        <h5 class="mb-3">إعدادات المستخدمين</h5>
                                        
                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" id="allow_registration" name="allow_registration" 
                                                    <?php echo ($settings['allow_registration'] ?? 0) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="allow_registration">
                                                السماح بالتسجيل الجديد
                                            </label>
                                        </div>

                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" id="email_verification" name="email_verification" 
                                                    <?php echo ($settings['email_verification'] ?? 0) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="email_verification">
                                                تفعيل التحقق من البريد الإلكتروني
                                            </label>
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="session_timeout" class="form-label">انتهاء صلاحية الجلسة (بالدقائق):</label>
                                            <input type="number" class="form-control" id="session_timeout" name="session_timeout" 
                                                    value="<?php echo htmlspecialchars($settings['session_timeout'] ?? '60'); ?>" min="5" max="1440">
                                        </div>
                                    </div>

                                    <div class="tab-pane fade" id="backup">
                                        <h5 class="mb-3">النسخ الاحتياطي</h5>
                                        
                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" id="backup_enabled" name="backup_enabled" 
                                                    <?php echo ($settings['backup_enabled'] ?? 0) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="backup_enabled">
                                                تفعيل النسخ الاحتياطي التلقائي
                                            </label>
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="backup_frequency" class="form-label">تكرار النسخ الاحتياطي:</label>
                                            <select class="form-control" id="backup_frequency" name="backup_frequency">
                                                <option value="daily" <?php echo ($settings['backup_frequency'] ?? 'daily') == 'daily' ? 'selected' : ''; ?>>يومياً</option>
                                                <option value="weekly" <?php echo ($settings['backup_frequency'] ?? '') == 'weekly' ? 'selected' : ''; ?>>أسبوعياً</option>
                                                <option value="monthly" <?php echo ($settings['backup_frequency'] ?? '') == 'monthly' ? 'selected' : ''; ?>>شهرياً</option>
                                            </select>
                                        </div>

                                        <div class="mb-3">
                                            <a href="<?php echo SITE_URL; ?>/pages/settings/backup.php" class="btn btn-info">
                                                <i class="fas fa-download me-2"></i>إنشاء نسخة احتياطية الآن
                                            </a>
                                        </div>
                                    </div>

                                    <div class="tab-pane fade" id="security">
                                        <h5 class="mb-3">إعدادات الأمان</h5>
                                        
                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" id="two_factor_auth" name="two_factor_auth" 
                                                    <?php echo ($settings['two_factor_auth'] ?? 0) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="two_factor_auth">
                                                تفعيل المصادقة الثنائية
                                            </label>
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="max_login_attempts" class="form-label">الحد الأقصى لمحاولات تسجيل الدخول:</label>
                                            <input type="number" class="form-control" id="max_login_attempts" name="max_login_attempts" 
                                                    value="<?php echo htmlspecialchars($settings['max_login_attempts'] ?? '5'); ?>" min="1" max="10">
                                        </div>

                                        <div class="form-group mb-3">
                                            <label for="lockout_duration" class="form-label">مدة الحظر (بالدقائق):</label>
                                            <input type="number" class="form-control" id="lockout_duration" name="lockout_duration" 
                                                    value="<?php echo htmlspecialchars($settings['lockout_duration'] ?? '15'); ?>" min="1" max="60">
                                        </div>
                                    </div>

                                    <div class="tab-pane fade" id="maintenance">
                                        <h5 class="mb-3">وضع الصيانة</h5>
                                        
                                        <div class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" id="maintenance_mode" name="maintenance_mode" 
                                                    <?php echo ($settings['maintenance_mode'] ?? 0) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="maintenance_mode">
                                                تفعيل وضع الصيانة (سيتم عرض رسالة للمستخدمين بأن الموقع قيد الصيانة)
                                            </label>
                                        </div>
                                        <p class="text-muted"><small>عند تفعيل وضع الصيانة، لن يتمكن سوى المستخدمين ذوي الصلاحيات المحددة من الوصول إلى لوحة التحكم.</small></p>
                                    </div>
                                </div>

                                <div class="card-footer text-end mt-4">
                                    <button type="submit" class="btn btn-primary">حفظ الإعدادات</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var triggerTabList = [].slice.call(document.querySelectorAll('#settingsTabs a'))
    triggerTabList.forEach(function (triggerEl) {
        var tabTrigger = new bootstrap.Tab(triggerEl)

        triggerEl.addEventListener('click', function (event) {
            event.preventDefault()
            tabTrigger.show()
            // Store active tab in local storage
            localStorage.setItem('activeSettingsTab', triggerEl.getAttribute('href'));
        })
    })

    // Activate tab from local storage on page load
    var activeTab = localStorage.getItem('activeSettingsTab');
    if (activeTab) {
        var someTabTriggerEl = document.querySelector('a[href="' + activeTab + '"]');
        if (someTabTriggerEl) {
            var tabTrigger = new bootstrap.Tab(someTabTriggerEl);
            tabTrigger.show();
        }
    }
});
</script>
```