<?php
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/m_services/MailService.php';

// Only users with settings view permission can access this page
if (!canView('settings')) {
    redirect("index.php");
}

$success_msg = '';
$error_msg = '';

// Handle Re-enable SMTP
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['enable_smtp'])) {
    if (canEdit('settings')) {
        db()->query("UPDATE smtp_settings SET is_enabled = 1, consecutive_failures = 0 WHERE id = 1");
        $_SESSION['success'] = 'تم إعادة تفعيل SMTP وتصفير عداد الأخطاء';
    } else {
        $_SESSION['error'] = 'عذراً، ليس لديك الصلاحية لتعديل الإعدادات';
    }
    redirect('charity-settings.php');
}

// Fetch charity settings
$stmt = db()->query("SELECT * FROM charity_settings WHERE id = 1");
$charity = $stmt->fetch();

// Fetch SMTP settings
$stmt = db()->query("SELECT * FROM smtp_settings WHERE id = 1");
$smtp = $stmt->fetch();

// Handle Charity Settings Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_charity'])) {
    if (!canEdit('settings')) {
        $_SESSION['error'] = 'عذراً، ليس لديك الصلاحية لتعديل الإعدادات';
    } else {
        $charity_name = $_POST['charity_name'];
        $charity_slogan = $_POST['charity_slogan'] ?? null;
        $charity_email = $_POST['charity_email'];
        $charity_phone = $_POST['charity_phone'];
        $charity_address = $_POST['charity_address'];
        $charity_logo = $charity['charity_logo'];
        $charity_favicon = $charity['charity_favicon'];

        $upload_dir = 'uploads/charity/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0775, true);

        if (isset($_FILES['charity_logo']) && $_FILES['charity_logo']['error'] === UPLOAD_ERR_OK) {
            $file_ext = pathinfo($_FILES['charity_logo']['name'], PATHINFO_EXTENSION);
            $new_logo = 'logo_' . time() . '.' . $file_ext;
            if (move_uploaded_file($_FILES['charity_logo']['tmp_name'], $upload_dir . $new_logo)) {
                $charity_logo = $upload_dir . $new_logo;
            }
        }

        if (isset($_FILES['charity_favicon']) && $_FILES['charity_favicon']['error'] === UPLOAD_ERR_OK) {
            $file_ext = pathinfo($_FILES['charity_favicon']['name'], PATHINFO_EXTENSION);
            $new_favicon = 'favicon_' . time() . '.' . $file_ext;
            if (move_uploaded_file($_FILES['charity_favicon']['tmp_name'], $upload_dir . $new_favicon)) {
                $charity_favicon = $upload_dir . $new_favicon;
            }
        }

        $stmt = db()->prepare("UPDATE charity_settings SET charity_name = ?, charity_slogan = ?, charity_email = ?, charity_phone = ?, charity_address = ?, charity_logo = ?, charity_favicon = ? WHERE id = 1");
        $stmt->execute([$charity_name, $charity_slogan, $charity_email, $charity_phone, $charity_address, $charity_logo, $charity_favicon]);
        $_SESSION['success'] = 'تم تحديث إعدادات النظام بنجاح';
    }
    redirect('charity-settings.php');
}

// Handle Advanced Settings Update (Super Admin Only)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_advanced'])) {
    if (!isSuperAdmin()) {
        $_SESSION['error'] = 'عذراً، هذا الإجراء متاح للمدير الخارق فقط';
    } else {
        $site_maintenance = isset($_POST['site_maintenance']) ? 1 : 0;
        $allow_registration = isset($_POST['allow_registration']) ? 1 : 0;
        $site_footer = $_POST['site_footer'];

        $stmt = db()->prepare("UPDATE charity_settings SET site_maintenance = ?, allow_registration = ?, site_footer = ? WHERE id = 1");
        $stmt->execute([$site_maintenance, $allow_registration, $site_footer]);
        $_SESSION['success'] = 'تم تحديث الإعدادات المتقدمة بنجاح';
    }
    redirect('charity-settings.php');
}

// Handle SMTP Settings Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_smtp'])) {
    if (!canEdit('settings')) {
        $_SESSION['error'] = 'عذراً، ليس لديك الصلاحية لتعديل الإعدادات';
    } else {
        $stmt = db()->prepare("UPDATE smtp_settings SET smtp_host = ?, smtp_port = ?, smtp_secure = ?, smtp_user = ?, smtp_pass = ?, from_email = ?, from_name = ?, reply_to = ?, max_failures = ? WHERE id = 1");
        $stmt->execute([
            $_POST['smtp_host'], 
            (int)$_POST['smtp_port'], 
            $_POST['smtp_secure'], 
            $_POST['smtp_user'], 
            $_POST['smtp_pass'], 
            $_POST['from_email'], 
            $_POST['from_name'], 
            $_POST['reply_to'],
            (int)$_POST['max_failures']
        ]);
        $_SESSION['success'] = 'تم تحديث إعدادات البريد (SMTP) بنجاح';
    }
    redirect('charity-settings.php');
}

// Handle Test Email
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_email_addr'])) {
    if (!canEdit('settings')) {
        $_SESSION['error'] = 'عذراً، ليس لديك الصلاحية للقيام بهذا الإجراء';
    } else {
        $to = $_POST['test_email_addr'];
        $res = MailService::sendMail($to, "رسالة تجريبية - Test Email", "<p>إذا كنت ترى هذه الرسالة، فإن إعدادات SMTP تعمل بشكل صحيح.</p>");
        if ($res['success']) {
            $_SESSION['success'] = "تم إرسال الرسالة التجريبية بنجاح إلى $to";
        } else {
            $_SESSION['error'] = "فشل إرسال الرسالة التجريبية: " . $res['error'];
        }
    }
    redirect('charity-settings.php');
}

// Handle Status Operations
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_status'])) {
    if (!canEdit('settings')) {
        $_SESSION['error'] = 'عذراً، ليس لديك الصلاحية لتعديل الإعدادات';
    } else {
        $name = $_POST['status_name'];
        $color = $_POST['status_color'];
        $is_default = isset($_POST['is_default']) ? 1 : 0;
        if ($is_default) db()->query("UPDATE mailbox_statuses SET is_default = 0");
        $stmt = db()->prepare("INSERT INTO mailbox_statuses (name, color, is_default) VALUES (?, ?, ?)");
        $stmt->execute([$name, $color, $is_default]);
        $_SESSION['success'] = 'تم إضافة نوع الحالة بنجاح';
    }
    redirect('charity-settings.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    if (!canEdit('settings')) {
        $_SESSION['error'] = 'عذراً، ليس لديك الصلاحية لتعديل الإعدادات';
    } else {
        $id = $_POST['status_id'];
        $name = $_POST['status_name'];
        $color = $_POST['status_color'];
        $is_default = isset($_POST['is_default']) ? 1 : 0;
        if ($is_default) db()->query("UPDATE mailbox_statuses SET is_default = 0");
        $stmt = db()->prepare("UPDATE mailbox_statuses SET name = ?, color = ?, is_default = ? WHERE id = ?");
        $stmt->execute([$name, $color, $is_default, $id]);
        $_SESSION['success'] = 'تم تحديث نوع الحالة بنجاح';
    }
    redirect('charity-settings.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_status'])) {
    if (!canDelete('settings')) {
        $_SESSION['error'] = 'عذراً، ليس لديك الصلاحية لحذف الإعدادات';
    } else {
        $id = $_POST['status_id'];
        $count = 0; foreach(['inbound_mail', 'outbound_mail', 'internal_mail'] as $t) { $stmt = db()->prepare("SELECT COUNT(*) FROM $t WHERE status_id = ?"); $stmt->execute([$id]); $count += $stmt->fetchColumn(); }
        
        if ($count > 0) {
            $_SESSION['error'] = 'لا يمكن حذف هذه الحالة لأنها مستخدمة في بعض السجلات';
        } else {
            db()->prepare("DELETE FROM mailbox_statuses WHERE id = ?")->execute([$id]);
            $_SESSION['success'] = 'تم حذف نوع الحالة بنجاح';
        }
    }
    redirect('charity-settings.php');
}

// Get session messages
if (isset($_SESSION['success'])) {
    $success_msg = $_SESSION['success'];
    unset($_SESSION['success']);
}
if (isset($_SESSION['error'])) {
    $error_msg = $_SESSION['error'];
    unset($_SESSION['error']);
}

$statuses = db()->query("SELECT * FROM mailbox_statuses ORDER BY id ASC")->fetchAll();
$email_logs = db()->query("SELECT * FROM email_logs ORDER BY id DESC LIMIT 50")->fetchAll();

// System Info
$php_version = phpversion();
$mysql_version = db()->query("SELECT VERSION()")->fetchColumn();
$server_addr = $_SERVER['SERVER_ADDR'] ?? '127.0.0.1';
$upload_max = ini_get('upload_max_filesize');
$post_max = ini_get('post_max_size');
?>

<div class="row">
    <div class="col-md-12 mb-4">
        <h2 class="fw-bold"><i class="fas fa-cog me-2"></i> الإعدادات</h2>
    </div>

    <?php if ($success_msg): ?>
        <div class="alert alert-success border-0 shadow-sm"><i class="fas fa-check-circle me-2"></i> <?= $success_msg ?></div>
    <?php endif; ?>
    <?php if ($error_msg): ?>
        <div class="alert alert-danger border-0 shadow-sm"><i class="fas fa-exclamation-circle me-2"></i> <?= $error_msg ?></div>
    <?php endif; ?>

    <div class="col-md-12">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-white p-0">
                <ul class="nav nav-tabs border-bottom-0" id="settingsTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active px-4 py-3" id="general-tab" data-bs-toggle="tab" data-bs-target="#general" type="button" role="tab">بيانات النظام</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link px-4 py-3" id="smtp-tab" data-bs-toggle="tab" data-bs-target="#smtp" type="button" role="tab">إعدادات SMTP</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link px-4 py-3" id="statuses-tab" data-bs-toggle="tab" data-bs-target="#statuses" type="button" role="tab">حالات البريد</button>
                    </li>
                    <?php if (isSuperAdmin()): ?>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link px-4 py-3 text-danger fw-bold" id="advanced-tab" data-bs-toggle="tab" data-bs-target="#advanced" type="button" role="tab">إعدادات متقدمة</button>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link px-4 py-3" id="logs-tab" data-bs-toggle="tab" data-bs-target="#logs" type="button" role="tab">سجلات البريد</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link px-4 py-3" id="sysinfo-tab" data-bs-toggle="tab" data-bs-target="#sysinfo" type="button" role="tab">معلومات الخادم</button>
                    </li>
                </ul>
            </div>
            <div class="card-body p-4">
                <div class="tab-content" id="settingsTabsContent">
                    <!-- General Settings -->
                    <div class="tab-pane fade show active" id="general" role="tabpanel">
                        <h5 class="fw-bold mb-4 text-primary">بيانات النظام والجهة</h5>
                        <form method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="update_charity" value="1">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">اسم النظام / الجهة</label>
                                    <input type="text" name="charity_name" class="form-control" value="<?= htmlspecialchars($charity['charity_name'] ?? '') ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">شعار الجهة (Slogan)</label>
                                    <input type="text" name="charity_slogan" class="form-control" value="<?= htmlspecialchars($charity['charity_slogan'] ?? '') ?>" placeholder="أدخل شعار الجهة الذي سيظهر تحت الاسم">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">البريد الإلكتروني الرسمي</label>
                                    <input type="email" name="charity_email" class="form-control" value="<?= htmlspecialchars($charity['charity_email'] ?? '') ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">رقم الهاتف</label>
                                    <input type="text" name="charity_phone" class="form-control" value="<?= htmlspecialchars($charity['charity_phone'] ?? '') ?>">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">العنوان</label>
                                <textarea name="charity_address" class="form-control" rows="3"><?= htmlspecialchars($charity['charity_address'] ?? '') ?></textarea>
                            </div>
                            <div class="row mt-4">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">شعار النظام</label>
                                    <input type="file" name="charity_logo" class="form-control" accept="image/*">
                                    <?php if ($charity['charity_logo']): ?>
                                        <div class="mt-3 p-3 bg-light rounded text-center border">
                                            <img src="<?= $charity['charity_logo'] ?>" alt="Logo" style="max-height: 100px;">
                                            <p class="small text-muted mt-2 mb-0">الشعار الحالي</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">أيقونة الموقع (Favicon)</label>
                                    <input type="file" name="charity_favicon" class="form-control" accept="image/x-icon,image/png">
                                    <?php if ($charity['charity_favicon']): ?>
                                        <div class="mt-3 p-3 bg-light rounded text-center border">
                                            <img src="<?= $charity['charity_favicon'] ?>" alt="Favicon" style="max-height: 48px;">
                                            <p class="small text-muted mt-2 mb-0">الأيقونة الحالية</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="text-end mt-4">
                                <?php if (canEdit('settings')): ?>
                                <button type="submit" class="btn btn-dark px-4">حفظ جميع التغييرات</button>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>

                    <!-- SMTP Settings -->
                    <div class="tab-pane fade" id="smtp" role="tabpanel">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h5 class="fw-bold text-primary mb-0">إعدادات البريد (SMTP)</h5>
                            <?php if (!$smtp['is_enabled']): ?>
                                <div class="alert alert-danger py-2 px-3 mb-0 d-flex align-items-center">
                                    <small><i class="fas fa-exclamation-triangle me-2"></i> SMTP معطل حالياً</small>
                                    <?php if (canEdit('settings')): ?>
                                    <form method="POST" class="ms-3">
                                        <button type="submit" name="enable_smtp" class="btn btn-sm btn-outline-danger">تفعيل الآن</button>
                                    </form>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <div class="badge bg-success p-2">
                                    <i class="fas fa-check-circle me-1"></i> SMTP يعمل (الأخطاء: <?= $smtp['consecutive_failures'] ?>/<?= $smtp['max_failures'] ?>)
                                </div>
                            <?php endif; ?>
                        </div>

                        <form method="POST">
                            <input type="hidden" name="update_smtp" value="1">
                            <div class="row">
                                <div class="col-md-8 mb-3">
                                    <label class="form-label fw-bold">SMTP Host</label>
                                    <input type="text" name="smtp_host" class="form-control" value="<?= htmlspecialchars($smtp['smtp_host'] ?? '') ?>" placeholder="smtp.example.com">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label fw-bold">SMTP Port</label>
                                    <input type="number" name="smtp_port" class="form-control" value="<?= htmlspecialchars($smtp['smtp_port'] ?? 587) ?>">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">SMTP Security</label>
                                    <select name="smtp_secure" class="form-select">
                                        <option value="tls" <?= ($smtp['smtp_secure'] ?? '') === 'tls' ? 'selected' : '' ?>>TLS (الأكثر أماناً)</option>
                                        <option value="ssl" <?= ($smtp['smtp_secure'] ?? '') === 'ssl' ? 'selected' : '' ?>>SSL</option>
                                        <option value="none" <?= ($smtp['smtp_secure'] ?? '') === 'none' ? 'selected' : '' ?>>بدون تشفير</option>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">اسم المرسل (Display Name)</label>
                                    <input type="text" name="from_name" class="form-control" value="<?= htmlspecialchars($smtp['from_name'] ?? '') ?>" placeholder="نظام المراسلات">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">SMTP Username</label>
                                    <input type="text" name="smtp_user" class="form-control" value="<?= htmlspecialchars($smtp['smtp_user'] ?? '') ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">SMTP Password</label>
                                    <input type="password" name="smtp_pass" class="form-control" value="<?= htmlspecialchars($smtp['smtp_pass'] ?? '') ?>">
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label fw-bold">From Email</label>
                                    <input type="email" name="from_email" class="form-control" value="<?= htmlspecialchars($smtp['from_email'] ?? '') ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label fw-bold">Reply-To Email</label>
                                    <input type="email" name="reply_to" class="form-control" value="<?= htmlspecialchars($smtp['reply_to'] ?? '') ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label fw-bold">حد الأخطاء قبل التعطيل</label>
                                    <input type="number" name="max_failures" class="form-control" value="<?= htmlspecialchars($smtp['max_failures'] ?? 5) ?>">
                                </div>
                            </div>
                            <?php if (canEdit('settings')): ?>
                            <button type="submit" class="btn btn-primary">حفظ إعدادات البريد</button>
                            <?php endif; ?>
                        </form>

                        <div class="mt-5 p-4 bg-light rounded border">
                            <h6 class="fw-bold mb-3">اختبار الإرسال</h6>
                            <p class="small text-muted mb-3">أدخل بريداً إلكترونياً صالحاً لإرسال رسالة تجريبية للتأكد من صحة الإعدادات.</p>
                            <form method="POST">
                                <div class="input-group" style="max-width: 450px;">
                                    <input type="email" name="test_email_addr" class="form-control" placeholder="بريد الوجهة (example@mail.com)" required>
                                    <button class="btn btn-secondary" type="submit" <?= !canEdit('settings') ? 'disabled' : '' ?>><i class="fas fa-paper-plane me-2"></i> إرسال اختبار</button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Advanced Settings (Super Admin Only) -->
                    <?php if (isSuperAdmin()): ?>
                    <div class="tab-pane fade" id="advanced" role="tabpanel">
                        <h5 class="fw-bold mb-4 text-danger">إعدادات النظام المتقدمة</h5>
                        <form method="POST">
                            <input type="hidden" name="update_advanced" value="1">
                            <div class="row g-4">
                                <div class="col-md-6">
                                    <div class="p-3 border rounded">
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" name="site_maintenance" id="site_maintenance" <?= $charity['site_maintenance'] ? 'checked' : '' ?>>
                                            <label class="form-check-label fw-bold" for="site_maintenance">وضع الصيانة (Maintenance Mode)</label>
                                        </div>
                                        <p class="small text-muted mb-0">عند تفعيل هذا الوضع، لن يتمكن سوى المديرين من الدخول للنظام.</p>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="p-3 border rounded">
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" name="allow_registration" id="allow_registration" <?= $charity['allow_registration'] ? 'checked' : '' ?>>
                                            <label class="form-check-label fw-bold" for="allow_registration">السماح بالتسجيل الذاتي</label>
                                        </div>
                                        <p class="small text-muted mb-0">تفعيل خيار "إنشاء حساب جديد" في صفحة تسجيل الدخول.</p>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="mb-3">
                                        <label class="form-label fw-bold">نص تذييل الموقع (Footer Text)</label>
                                        <textarea name="site_footer" class="form-control" rows="3" placeholder="أدخل النص الذي سيظهر في أسفل جميع الصفحات..."><?= htmlspecialchars($charity['site_footer'] ?? '') ?></textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="text-end mt-4">
                                <button type="submit" class="btn btn-danger px-4">حفظ الإعدادات المتقدمة</button>
                            </div>
                        </form>
                    </div>
                    <?php endif; ?>

                    <!-- Statuses Settings -->
                    <div class="tab-pane fade" id="statuses" role="tabpanel">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h5 class="fw-bold text-primary mb-0">أنواع حالات البريد</h5>
                            <?php if (canAdd('settings')): ?>
                            <button class="btn btn-sm btn-primary" onclick="new bootstrap.Modal(document.getElementById('addStatusModal')).show()"><i class="fas fa-plus me-2"></i> إضافة حالة جديدة</button>
                            <?php endif; ?>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover align-middle border">
                                <thead class="bg-light">
                                    <tr><th>الحالة</th><th>كود اللون</th><th>افتراضية</th><th class="text-end">الإجراء</th></tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($statuses as $status): ?>
                                        <tr>
                                            <td>
                                                <span class="badge px-3 py-2" style="background-color: <?= $status['color'] ?>;">
                                                    <?= htmlspecialchars($status['name']) ?>
                                                </span>
                                            </td>
                                            <td><code><?= $status['color'] ?></code></td>
                                            <td>
                                                <?php if ($status['is_default']): ?>
                                                    <span class="badge bg-success-subtle text-success border border-success px-2 py-1">نعم</span>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end">
                                                <?php if (canEdit('settings')): ?>
                                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="editStatus(<?= $status['id'] ?>, '<?= htmlspecialchars($status['name'], ENT_QUOTES) ?>', '<?= $status['color'] ?>', <?= $status['is_default'] ?>)"><i class="fas fa-edit"></i></button>
                                                <?php endif; ?>
                                                <?php if (canDelete('settings') && !$status['is_default']): ?>
                                                <form method="POST" onsubmit="return confirm('هل أنت متأكد من حذف هذه الحالة؟');" style="display:inline;">
                                                    <input type="hidden" name="status_id" value="<?= $status['id'] ?>">
                                                    <input type="hidden" name="delete_status" value="1">
                                                    <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>
                                                </form>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Email Logs -->
                    <div class="tab-pane fade" id="logs" role="tabpanel">
                        <h5 class="fw-bold text-primary mb-4">سجلات المراسلات البريدية (آخر 50 عملية)</h5>
                        <div class="table-responsive">
                            <table class="table table-sm table-hover border">
                                <thead class="bg-light">
                                    <tr>
                                        <th class="py-3 ps-3">الوقت والتاريخ</th>
                                        <th class="py-3">المستلم</th>
                                        <th class="py-3">الموضوع</th>
                                        <th class="py-3">الحالة</th>
                                        <th class="py-3 pe-3">تفاصيل الخطأ</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($email_logs): ?>
                                        <?php foreach ($email_logs as $log): ?>
                                            <tr>
                                                <td class="ps-3 small"><?= date('Y-m-d H:i:s', strtotime($log['created_at'])) ?></td>
                                                <td><span class="fw-bold"><?= htmlspecialchars($log['recipient']) ?></span></td>
                                                <td class="small"><?= htmlspecialchars($log['subject']) ?></td>
                                                <td>
                                                    <span class="badge bg-<?= $log['status'] === 'success' ? 'success' : 'danger' ?>">
                                                        <?= $log['status'] === 'success' ? 'تم الإرسال' : 'فشل' ?>
                                                    </span>
                                                </td>
                                                <td class="pe-3 small text-danger"><?= htmlspecialchars($log['error_message'] ?? '-') ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr><td colspan="5" class="text-center py-4 text-muted">لا يوجد سجلات حالياً</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- System Info Tab -->
                    <div class="tab-pane fade" id="sysinfo" role="tabpanel">
                        <h5 class="fw-bold text-primary mb-4">معلومات النظام والخادم</h5>
                        <div class="row g-4">
                            <div class="col-md-6">
                                <div class="p-3 border rounded bg-light">
                                    <h6 class="fw-bold border-bottom pb-2 mb-3">بيئة البرمجيات</h6>
                                    <table class="table table-sm table-borderless mb-0">
                                        <tr><td width="150" class="text-muted">نسخة PHP:</td><td class="fw-bold"><?= $php_version ?></td></tr>
                                        <tr><td class="text-muted">نسخة MySQL:</td><td class="fw-bold"><?= $mysql_version ?></td></tr>
                                        <tr><td class="text-muted">نظام التشغيل:</td><td class="fw-bold"><?= PHP_OS ?></td></tr>
                                        <tr><td class="text-muted">عنوان الخادم:</td><td class="fw-bold"><?= $server_addr ?></td></tr>
                                    </table>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="p-3 border rounded bg-light">
                                    <h6 class="fw-bold border-bottom pb-2 mb-3">إعدادات الملفات</h6>
                                    <table class="table table-sm table-borderless mb-0">
                                        <tr><td width="150" class="text-muted">أقصى حجم رفع:</td><td class="fw-bold"><?= $upload_max ?></td></tr>
                                        <tr><td class="text-muted">أقصى حجم POST:</td><td class="fw-bold"><?= $post_max ?></td></tr>
                                        <tr><td class="text-muted">ترميز قاعدة البيانات:</td><td class="fw-bold">utf8mb4_unicode_ci</td></tr>
                                        <tr><td class="text-muted">نطاق النظام:</td><td class="fw-bold"><?= $_SERVER['HTTP_HOST'] ?></td></tr>
                                    </table>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <div class="p-3 border rounded bg-warning bg-opacity-10 border-warning">
                                    <h6 class="fw-bold mb-2 text-warning-emphasis"><i class="fas fa-tools me-2"></i> أدوات الصيانة</h6>
                                    <p class="small mb-3">هذه الأدوات مخصصة لمدير النظام فقط. يرجى توخي الحذر عند الاستخدام.</p>
                                    <div class="d-flex gap-2">
                                        <?php if (canEdit('settings')): ?>
                                        <button class="btn btn-sm btn-outline-warning" onclick="alert('قريباً: نسخة احتياطية لقاعدة البيانات')"><i class="fas fa-database me-1"></i> نسخة احتياطية</button>
                                        <?php endif; ?>
                                        <button class="btn btn-sm btn-outline-secondary" onclick="location.reload()"><i class="fas fa-sync-alt me-1"></i> تحديث الحالة</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Status Modal -->
<div class="modal fade" id="addStatusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold">إضافة حالة جديدة</h5>
                    <button type="button" class="btn-close ms-0 me-auto" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="add_status" value="1">
                    <div class="mb-3">
                        <label class="form-label fw-bold">اسم الحالة</label>
                        <input type="text" name="status_name" class="form-control" placeholder="مثال: تحت الدراسة" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">اللون التعريفي</label>
                        <input type="color" name="status_color" class="form-control form-control-color w-100" value="#0d6efd">
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_default" id="add_is_default">
                        <label class="form-check-label" for="add_is_default">تعيين كحالة افتراضية للبريد الجديد</label>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary px-4">إضافة الحالة</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Status Modal -->
<div class="modal fade" id="editStatusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold">تعديل نوع الحالة</h5>
                    <button type="button" class="btn-close ms-0 me-auto" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="update_status" value="1">
                    <input type="hidden" name="status_id" id="edit_status_id">
                    <div class="mb-3">
                        <label class="form-label fw-bold">اسم الحالة</label>
                        <input type="text" name="status_name" id="edit_status_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">اللون التعريفي</label>
                        <input type="color" name="status_color" id="edit_status_color" class="form-control form-control-color w-100">
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_default" id="edit_is_default">
                        <label class="form-check-label" for="edit_is_default">تعيين كحالة افتراضية</label>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary px-4">حفظ التغييرات</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editStatus(id, name, color, isDefault) {
    document.getElementById('edit_status_id').value = id;
    document.getElementById('edit_status_name').value = name;
    document.getElementById('edit_status_color').value = color;
    document.getElementById('edit_is_default').checked = isDefault == 1;
    new bootstrap.Modal(document.getElementById('editStatusModal')).show();
}

document.addEventListener('DOMContentLoaded', function() {
    // Preserve active tab after redirect
    var activeTab = localStorage.getItem('activeSettingsTab');
    if (activeTab) {
        var tabEl = document.querySelector('button[data-bs-target="' + activeTab + '"]');
        if (tabEl) {
            // Check if it's already shown to avoid flicker
            if (!tabEl.classList.contains('active')) {
                bootstrap.Tab.getInstance(tabEl)?.show() || new bootstrap.Tab(tabEl).show();
            }
        }
    }

    document.querySelectorAll('button[data-bs-toggle="tab"]').forEach(function(tab) {
        tab.addEventListener('shown.bs.tab', function(e) {
            localStorage.setItem('activeSettingsTab', e.target.getAttribute('data-bs-target'));
        });
    });

    // Handle hash in URL for direct tab access
    if (window.location.hash) {
        var hashTab = document.querySelector('button[data-bs-target="' + window.location.hash + '"]');
        if (hashTab) {
            bootstrap.Tab.getInstance(hashTab)?.show() || new bootstrap.Tab(hashTab).show();
        }
    }
});
</script>

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