<?php
error_reporting(0);
ini_set('display_errors', 0);
require_once 'config.php';
// ══ ADMIN AUTH — صريح وإلزامي ════════════════════════════════
$_admin_user = current_user();
if (!$_admin_user) { header('Location: ' . url('?login=1')); exit; }
$_is_staff = !empty($_admin_user['user_type']) && in_array($_admin_user['user_type'],['admin','staff','moderator']);
$_is_admin = !empty($_admin_user['user_type']) && $_admin_user['user_type']==='admin';
if (!$_is_staff) { http_response_code(403); die('<h2>403 — وصول مرفوض</h2>'); }
define('IS_ADMIN_CHECK_DONE', true);
// ══════════════════════════════════════════════════════════════

// ── ADMIN AUTH GUARD ────────────────────────────────────────
$_admin_user = null;
if (session_status() !== PHP_SESSION_ACTIVE) @session_start();
try {
    $__u = current_user();
    if (!$__u) { header('Location: ' . url('?login=1&next=admin')); exit; }
    $__st = db()->prepare("SELECT user_type, is_admin FROM users WHERE id=? LIMIT 1");
    $__st->execute([$__u['id']]);
    $__row = $__st->fetch();
    if (!($__row['is_admin'] ?? 0) && !in_array($__row['user_type'] ?? '', ['admin','staff','moderator'])) {
        http_response_code(403);
        die('<h1 style="font-family:sans-serif;text-align:center;padding:60px;color:#dc2626">&#128683; غير مصرح لك بالوصول</h1>');
    }
    $_admin_user = $__u;
} catch (Throwable $__e) {
    die('Admin auth error: ' . htmlspecialchars($__e->getMessage()));
}
// ── END AUTH ─────────────────────────────────────────────────

start_secure_session();

// Catch DB connection failure early — show friendly error instead of 500
try { db(); } catch (RuntimeException $e) {
    http_response_code(503);
    die('<!DOCTYPE html><html dir="rtl"><head><meta charset="utf-8"><title>سودانا Admin — v23 Control Panel</title>
<style>body{font-family:Cairo,sans-serif;background:#0a1628;color:#fff;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;flex-direction:column}
/* ── RESPONSIVE + SIDEBAR ────────────────────────────── */
@media(max-width:768px){
  .admin-layout{flex-direction:column!important}
  .admin-sidebar{width:100%!important;flex-direction:row!important;overflow-x:auto;white-space:nowrap;padding:8px!important}
  .admin-sidebar .sb-label{display:none}
  .admin-sidebar a{display:inline-flex!important;padding:8px 12px!important;font-size:.75rem}
  .admin-main{padding:14px!important}
  .stat-grid{grid-template-columns:repeat(2,1fr)!important}
  table{font-size:.72rem}
  .kpi-charts{grid-template-columns:1fr!important}
}
@media(max-width:480px){
  .admin-sidebar a{padding:6px 10px!important;font-size:.7rem}
  .stat-grid{grid-template-columns:1fr!important}
}

/* Sidebar */
.admin-layout{display:flex;min-height:calc(100vh - 52px)}
.admin-sidebar{
  width:220px;flex-shrink:0;
  background:#060d1a;border-left:1px solid #1e3a2a;
  padding:16px 0;position:sticky;top:52px;
  height:calc(100vh - 52px);overflow-y:auto;
}
.admin-sidebar .sb-section{padding:8px 16px;font-size:.65rem;font-weight:700;
  color:#2d5a3d;letter-spacing:.12em;text-transform:uppercase;margin-top:12px}
.admin-sidebar a{
  display:flex;align-items:center;gap:8px;
  padding:9px 16px;color:#94a3b8;text-decoration:none;
  font-size:.78rem;transition:.15s;border-right:2px solid transparent;
}
.admin-sidebar a:hover{color:#fff;background:#0d2137}
.admin-sidebar a.active{color:#00d97e;background:#00d97e10;border-right-color:#00d97e}
.admin-sidebar .sb-icon{width:16px;text-align:center}
.admin-main{flex:1;padding:20px;overflow-y:auto;max-height:calc(100vh - 52px)}

/* KPI Charts */
.kpi-charts{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px;margin-bottom:20px}
.kpi-chart-card{background:linear-gradient(135deg,#0a1f14,#0d2137);border:1px solid #1e3a2a;border-radius:14px;padding:18px}
.kpi-chart-card h4{font-size:.78rem;font-weight:700;color:#64748b;margin-bottom:12px;text-transform:uppercase;letter-spacing:.05em}
.kpi-chart-card svg{width:100%}

/* AI Engine section */
.engine-card{background:#060d1a;border:1px solid #1e3a2a;border-radius:12px;padding:16px;margin-bottom:12px}
.engine-card h3{font-size:.85rem;font-weight:800;color:#00d97e;margin-bottom:10px;display:flex;align-items:center;gap:6px}
.domain-chip{display:inline-flex;align-items:center;gap:5px;background:#00d97e10;border:1px solid #00d97e30;color:#6ee7b7;
  padding:4px 10px;border-radius:20px;font-size:.7rem;margin:3px;font-weight:600}
.sector-bar{display:flex;align-items:center;gap:8px;margin-bottom:6px;font-size:.72rem}
.sector-bar .bar{height:6px;background:linear-gradient(90deg,#00d97e,#0ea5e9);border-radius:3px;transition:.4s}
.sector-bar .label{color:#94a3b8;width:90px;flex-shrink:0}
.sector-bar .num{color:#6ee7b7;width:30px;text-align:right;flex-shrink:0}

/* ── ADDITIONS: Animation + Skeleton + Focus ──────────────── */
*{transition:background .15s,border-color .15s,color .1s}
.sb-link{transition:background .15s,border-right .15s,padding-right .15s!important}
.sb-link:hover{background:#0d2137!important;border-right:3px solid #00d97e!important}
.sb-link.active{background:#0d2137!important;border-right:3px solid #00d97e!important;font-weight:700!important}

.stat:hover{transform:translateY(-2px);box-shadow:0 4px 16px rgba(0,212,126,.15)!important}
.engine-card:hover{border-color:#00d97e55!important}

/* Skeleton loader */
.skel{background:linear-gradient(90deg,#0d2137 25%,#112840 50%,#0d2137 75%);background-size:200% 100%;animation:skel 1.4s infinite;border-radius:8px;height:16px;margin-bottom:8px}
@keyframes skel{0%{background-position:200% 0}100%{background-position:-200% 0}}

/* Fade in */
.fade-in{animation:fi .35s ease}
@keyframes fi{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

/* Status badges */
.badge-ok{background:#064e3b;color:#34d399;padding:2px 8px;border-radius:10px;font-size:.68rem;font-weight:700}
.badge-warn{background:#451a03;color:#f59e0b;padding:2px 8px;border-radius:10px;font-size:.68rem;font-weight:700}
.badge-err{background:#450a0a;color:#f87171;padding:2px 8px;border-radius:10px;font-size:.68rem;font-weight:700}

/* Better table rows */
.admin-table tr:hover td{background:#0a1e30!important}
.admin-table th{background:#060d1a!important;font-size:.72rem;letter-spacing:.05em;text-transform:uppercase;color:#64748b!important}

/* Chart bar */
.bar-wrap{display:flex;align-items:center;gap:8px;margin-bottom:6px}
.bar-track{flex:1;background:#0d2137;border-radius:4px;height:8px;overflow:hidden}
.bar-fill{height:100%;border-radius:4px;background:linear-gradient(90deg,#00d97e,#0ea5e9)}

/* Input focus */
input:focus,select:focus,textarea:focus{outline:none!important;border-color:#00d97e!important;box-shadow:0 0 0 2px rgba(0,217,126,.2)!important}

/* Responsive improvements */
@media(max-width:900px){
  .admin-sidebar{width:56px!important;overflow:hidden}
  .sb-label{display:none!important}
  .sb-section{display:none!important}
  .sb-icon{font-size:1.1rem!important;margin:0 auto!important}
}
@media(max-width:600px){
  .admin-sidebar{width:100%!important;flex-direction:row!important;position:fixed!important;bottom:0!important;top:auto!important;left:0!important;right:0!important;z-index:200!important;display:flex!important;height:52px!important;overflow-x:auto!important;border-left:none!important;border-top:1px solid #1e3a2a!important;padding:0!important}
  .admin-layout{flex-direction:column!important;padding-bottom:60px!important}
  .sb-link{padding:14px 16px!important;flex-shrink:0!important}
}
</style></head>
<body>
<div class="admin-layout" id="admin-layout">

<!-- ══ SIDEBAR ══ -->
<nav class="admin-sidebar" id="admin-sidebar">
  <div class="sb-section">الرئيسية</div>
  <a href="?tab=users" class="sb-link"><span class="sb-icon">👤</span><span class="sb-label">المستخدمون</span></a>
  <a href="?tab=providers" class="sb-link"><span class="sb-icon">👥</span><span class="sb-label">المزودون</span></a>
  <a href="?tab=bookings" class="sb-link"><span class="sb-icon">📅</span><span class="sb-label">الحجوزات</span></a>
  <a href="?tab=subscriptions" class="sb-link"><span class="sb-icon">💳</span><span class="sb-label">الاشتراكات</span></a>
  
  <div class="sb-section">المالية</div>
  <a href="?tab=invoices" class="sb-link"><span class="sb-icon">🧾</span><span class="sb-label">الفواتير</span></a>
  <a href="?tab=reconciliation" class="sb-link"><span class="sb-icon">⚖️</span><span class="sb-label">التسوية</span></a>
  <a href="?tab=settlement" class="sb-link"><span class="sb-icon">💸</span><span class="sb-label">صرف المزودين</span></a>
  
  <div class="sb-section">الذكاء الاصطناعي</div>
  <a href="?tab=ai_engines" class="sb-link"><span class="sb-icon">🧠</span><span class="sb-label">محركات AI</span></a>
  <a href="?tab=policy_editor" class="sb-link"><span class="sb-icon">📋</span><span class="sb-label">محرر السياسات</span></a>
  <a href="?tab=ie_rules" class="sb-link"><span class="sb-icon">⚡</span><span class="sb-label">قواعد الاستدلال</span></a>
  
  <div class="sb-section">المنصة</div>
  <a href="?tab=dashboard" class="sb-link"><span class="sb-icon">📊</span><span class="sb-label">Dashboard KPI</span></a>
  <a href="?tab=broadcast" class="sb-link"><span class="sb-icon">🔔</span><span class="sb-label">الإشعارات</span></a>
  <a href="?tab=items" class="sb-link"><span class="sb-icon">🛒</span><span class="sb-label">سوق الجيران</span></a>
  <a href="?tab=posts" class="sb-link"><span class="sb-icon">📢</span><span class="sb-label">منشورات الحي</span></a>
  <a href="?tab=events" class="sb-link"><span class="sb-icon">🎪</span><span class="sb-label">الفعاليات</span></a>
  <a href="?tab=lessons" class="sb-link"><span class="sb-icon">📚</span><span class="sb-label">الأكاديمية</span></a>
  <a href="?tab=invest" class="sb-link"><span class="sb-icon">💼</span><span class="sb-label">المستثمرون</span></a>
  <a href="?tab=partners" class="sb-link"><span class="sb-icon">🤝</span><span class="sb-label">الشركاء</span></a>
  <a href="?tab=reports" class="sb-link"><span class="sb-icon">📈</span><span class="sb-label">التقارير</span></a>
  
  <div class="sb-section">مالية متقدمة</div>
  <div class="sb-section" style="color:#f59e0b;font-size:.65rem;letter-spacing:.05em;padding:10px 16px 4px">💱 إدارة الأسعار</div>
  <a href="?tab=pricing_exchange"  class="sb-link"><span class="sb-icon">💱</span><span class="sb-label">سعر الصرف</span></a>
  <a href="?tab=pricing_plans"     class="sb-link"><span class="sb-icon">💳</span><span class="sb-label">أسعار الاشتراكات</span></a>
  <a href="?tab=pricing_documents" class="sb-link"><span class="sb-icon">📄</span><span class="sb-label">أسعار الوثائق</span></a>
  <a href="?tab=pricing_corporate" class="sb-link"><span class="sb-icon">🏢</span><span class="sb-label">أسعار الشركات</span></a>
  <a href="?tab=pricing_policies"  class="sb-link"><span class="sb-icon">⚖️</span><span class="sb-label">العمولة والسياسات</span></a>
  <a href="?tab=pricing_images"    class="sb-link"><span class="sb-icon">🖼️</span><span class="sb-label">أسعار الصور</span></a>
  <a href="?tab=pricing_videos"    class="sb-link"><span class="sb-icon">🎬</span><span class="sb-label">أسعار الفيديو</span></a>
  <a href="?tab=ai_usage_dashboard" class="sb-link"><span class="sb-icon">📊</span><span class="sb-label">استخدام AI</span></a>
  <div class="sb-section" style="color:#fbbf24;font-size:.65rem;letter-spacing:.05em;padding:10px 16px 4px">💡 ملاحظات المستخدمين</div>
  <a href="?tab=suggestions" class="sb-link"><span class="sb-icon">💡</span><span class="sb-label">المقترحات</span></a>
  <a href="?tab=fraud" class="sb-link"><span class="sb-icon">🚨</span><span class="sb-label">مكافحة الاحتيال</span></div>
  <div class="sb-section" style="color:#a78bfa;font-size:.65rem;letter-spacing:.05em;padding:10px 16px 4px">🏢 حلول الشركات</div>
  <a href="?tab=corporate"         class="sb-link"><span class="sb-icon">📋</span><span class="sb-label">طلبات الشركات</span></a>
  <div class="sb-section" style="color:#34d399;font-size:.65rem;letter-spacing:.05em;padding:10px 16px 4px">💡 المقترحات</div>
  <a href="?tab=suggestions"       class="sb-link"><span class="sb-icon">💡</span><span class="sb-label">مقترحات المستخدمين</span></a>
  <a href="?tab=fraud"             class="sb-link"><span class="sb-icon">🛡️</span><span class="sb-label">مكافحة الاحتيال</span></a>
  <a href="?tab=ledger_view" class="sb-link"><span class="sb-icon">📒</span><span class="sb-label">دفتر الأستاذ</span></a>
  <a href="?tab=wallet_summary" class="sb-link"><span class="sb-icon">👛</span><span class="sb-label">المحافظ</span></a>
  <a href="?tab=execution_log" class="sb-link"><span class="sb-icon">🔍</span><span class="sb-label">سجل التنفيذ</span></a>
  <a href="?tab=support" class="sb-link"><span class="sb-icon">🎫</span><span class="sb-label">الدعم الفني</span></a>
  <a href="?tab=services" class="sb-link"><span class="sb-icon">🏪</span><span class="sb-label">الخدمات</span></a>
  <a href="?tab=pharmacies" class="sb-link"><span class="sb-icon">💊</span><span class="sb-label">الصيدليات</span></a>
  <a href="?tab=contracts" class="sb-link"><span class="sb-icon">📄</span><span class="sb-label">العقود</span></a>
  <a href="?tab=crm" class="sb-link"><span class="sb-icon">📝</span><span class="sb-label">CRM</span></a>
  
  <div class="sb-section">النظام</div>
  <a href="?tab=staff" class="sb-link"><span class="sb-icon">🔧</span><span class="sb-label">الفريق</span></a>
  <a href="?tab=system_metrics" class="sb-link"><span class="sb-icon">📊</span><span class="sb-label">المقاييس</span></a>
  <a href="?tab=queue" class="sb-link"><span class="sb-icon">⏳</span><span class="sb-label">قائمة الانتظار</span></a>
  
</nav>

<!-- ══ MAIN CONTENT ══ -->
<div class="admin-main" id="admin-main">
<h1 style="color:#f87171">⚠️ قاعدة البيانات غير متاحة</h1>
<p style="color:#94a3b8">تأكد من استيراد database_complete.sql وصحة credentials في config.php</p>
<p style="color:#64748b;font-size:.85rem;margin-top:16px">DB: ' . DB_NAME . ' | Host: ' . DB_HOST . '</p>
        
</body></html>');
}

$csrf = $_SESSION['csrf'] ?? ($_SESSION['csrf'] = bin2hex(random_bytes(16)));

// ── معالجة POST ───────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($csrf, (string)($_POST['csrf'] ?? ''))) { http_response_code(403); die('CSRF Error'); }

    if (($_POST['action'] ?? '') === 'login') {
        if (ADMIN_PASSWORD !== '' && hash_equals(ADMIN_PASSWORD, (string)($_POST['password'] ?? ''))) {
            $_SESSION['admin'] = [
                'id'   => 0,                       // 0 = super-admin (no staff_members row)
                'role' => 'super_admin',
                'name' => 'الأدمن الرئيسي',
            ];
            // Legacy keys (kept for backward-compat with older code)
            $_SESSION['admin_role'] = 'super_admin';
            $_SESSION['admin_name'] = 'الأدمن الرئيسي';
        } else {
            // تحقق من staff_members
            try {
                $st = db()->prepare('SELECT * FROM staff_members WHERE email = ? AND active = 1 LIMIT 1');
                $st->execute([trim(strtolower($_POST['email'] ?? ''))]);
                $staff = $st->fetch();
                if ($staff && password_verify((string)($_POST['password'] ?? ''), (string)$staff['password_hash'])) {
                    $_SESSION['admin'] = [
                        'id'   => (int)$staff['id'],
                        'role' => $staff['role'],
                        'name' => $staff['name'],
                    ];
                    // Legacy keys
                    $_SESSION['admin_role'] = $staff['role'];
                    $_SESSION['admin_name'] = $staff['name'];
                    $_SESSION['staff_id']   = (int)$staff['id'];
                    db()->prepare('UPDATE staff_members SET last_login = NOW() WHERE id = ?')->execute([(int)$staff['id']]);
                }
            } catch (Throwable $ignored) {}
        }
        header('Location: ' . url('admin.php')); exit;
    }

    if (empty($_SESSION['admin'])) { header('Location: ' . url('admin.php')); exit; }
    $action = $_POST['action'] ?? '';
    $tab    = $_POST['tab']    ?? 'users';
    $msg    = '';
    $role   = $_SESSION['admin_role'] ?? 'support';

    // ── دالة تسجيل النشاط ─────────────────────────────────────
    $log_act = function(string $act, string $type='', int $tid=0, string $details='') use ($role) {
        try {
            $sid = $_SESSION['staff_id'] ?? 0;
            db()->prepare('INSERT INTO staff_activity_log (staff_id, action, target_type, target_id, details, ip_address) VALUES (?,?,?,?,?,?)')
                ->execute([$sid, $act, $type, $tid ?: null, $details, $_SERVER['REMOTE_ADDR'] ?? '']);
        } catch (Throwable $ignored) {}
    };

    // ── المستخدمون ────────────────────────────────────────────
    if ($action === 'reset_user_pw') {
        $id = (int)($_POST['uid'] ?? 0); $np = trim($_POST['new_pw'] ?? '');
        if ($id && strlen($np) >= 6) {
            db()->prepare('UPDATE users SET password_hash = ? WHERE id = ?')->execute([password_hash($np, PASSWORD_BCRYPT, ['cost' => 10]), $id]);
            // إرسال إيميل للمستخدم بتغيير كلمة المرور
            try {
                $usr = db()->prepare('SELECT name, email FROM users WHERE id = ? LIMIT 1');
                $usr->execute([$id]);
                $usr_data = $usr->fetch();
                if ($usr_data && $usr_data['email']) {
                    send_password_changed_email($usr_data['email'], $usr_data['name']);
                }
            } catch(Throwable $ignored) {}
            // إلغاء جلسات المستخدم
            db()->prepare('DELETE FROM sessions WHERE user_id = ?')->execute([$id]);
            $msg = "✅ تم تغيير كلمة المرور للمستخدم #$id وإرسال إشعار بالبريد";
            $log_act('reset_password', 'user', $id);
            // إذا جاء الطلب من CRM، العودة لملف المستخدم
            if (($tab = 'crm') && !empty($_POST['user_uid'])) {
                $tab = 'crm';
            }
        }
    }
    if ($action === 'toggle_tier') {
        $id = (int)($_POST['uid'] ?? 0); $tier = $_POST['tier'] ?? 'free';
        $new = $tier === 'free' ? 'paid' : 'free';
        db()->prepare('UPDATE users SET subscription_tier = ? WHERE id = ?')->execute([$new, $id]);
        $msg = "✅ اشتراك المستخدم #$id → $new";
        $log_act('toggle_tier', 'user', $id, $new);
    }
    if ($action === 'delete_user' && in_array($role, ['super_admin','admin'])) {
        $id = (int)($_POST['uid'] ?? 0);
        if ($id) { db()->prepare('DELETE FROM users WHERE id = ?')->execute([$id]); $msg = "✅ حُذف المستخدم #$id"; $log_act('delete_user', 'user', $id); }
    }

    // ── المنشورات ─────────────────────────────────────────────
    if ($action === 'approve_post') { $id=(int)($_POST['post_id']??0); db()->prepare("UPDATE pulse_posts SET status='active' WHERE id=?")->execute([$id]); $msg="✅ قُبل المنشور #$id"; $log_act('approve_post','post',$id); }
    if ($action === 'remove_post')  { $id=(int)($_POST['post_id']??0); db()->prepare("UPDATE pulse_posts SET status='removed' WHERE id=?")->execute([$id]); $msg="✅ حُذف المنشور #$id"; $log_act('remove_post','post',$id); }
    if ($action === 'resolve_post') { $id=(int)($_POST['post_id']??0); db()->prepare("UPDATE pulse_posts SET status='resolved' WHERE id=?")->execute([$id]); $msg="✅ أُغلق المنشور #$id"; }
    if ($action === 'add_admin_post') {
        $content = mb_substr(trim($_POST['content'] ?? ''), 0, 1000);
        $type    = $_POST['type'] ?? 'announcement';
        $hood_id = (int)($_POST['neighborhood_id'] ?? 0);
        if ($content) {
            db()->prepare('INSERT INTO pulse_posts (user_id, neighborhood_id, type, content, is_urgent) VALUES (1,?,?,?,?)')
                ->execute([$hood_id ?: null, $type, $content, $type === 'urgent' ? 1 : 0]);
            $pid = (int)db()->lastInsertId();
            $msg = "✅ تم نشر الإعلان #$pid"; $log_act('add_post','post',$pid,'admin post');
        }
    }

    // ── السوق ─────────────────────────────────────────────────
    if ($action === 'remove_item')  { $id=(int)($_POST['item_id']??0); db()->prepare("UPDATE marketplace_items SET status='removed' WHERE id=?")->execute([$id]); $msg="✅ حُذف الإعلان #$id"; $log_act('remove_item','item',$id); }
    if ($action === 'restore_item') { $id=(int)($_POST['item_id']??0); db()->prepare("UPDATE marketplace_items SET status='active' WHERE id=?")->execute([$id]); $msg="✅ استُعيد الإعلان #$id"; }
    if ($action === 'mark_sold')    { $id=(int)($_POST['item_id']??0); db()->prepare("UPDATE marketplace_items SET status='sold' WHERE id=?")->execute([$id]); $msg="✅ تم وضع الإعلان كمباع"; }

    // ── الأكاديمية ────────────────────────────────────────────
    if ($action === 'add_lesson') {
        $track = in_array($_POST['track'] ?? '', ['foundation','growth','leadership']) ? $_POST['track'] : 'foundation';
        $opts  = array_filter(array_map('trim', [
            $_POST['opt_a'] ?? '', $_POST['opt_b'] ?? '',
            $_POST['opt_c'] ?? '', $_POST['opt_d'] ?? '',
        ]));
        db()->prepare('INSERT INTO lessons (track, title, content, quiz_question, quiz_options, quiz_answer, order_index, is_premium) VALUES (?,?,?,?,?,?,?,?)')
            ->execute([$track, mb_substr($_POST['title'] ?? '', 0, 300), $_POST['content'] ?? '',
                $_POST['quiz_q'] ?? '', $opts ? json_encode(array_values($opts), JSON_UNESCAPED_UNICODE) : null,
                strtoupper($_POST['quiz_ans'] ?? '') ?: null,
                (int)($_POST['order'] ?? 0), (int)($_POST['is_premium'] ?? 0)]);
        $msg = "✅ تم إضافة الدرس"; $log_act('add_lesson','lesson',(int)db()->lastInsertId());
    }
    if ($action === 'delete_lesson') { $id=(int)($_POST['lesson_id']??0); db()->prepare('DELETE FROM lessons WHERE id=?')->execute([$id]); $msg="✅ حُذف الدرس #$id"; }

    // ── الأحياء ───────────────────────────────────────────────
    if ($action === 'add_neighborhood') {
        $name  = mb_substr(trim($_POST['name']  ?? ''), 0, 100);
        $city  = mb_substr(trim($_POST['city']  ?? ''), 0, 100);
        $state = mb_substr(trim($_POST['state'] ?? ''), 0, 100);
        if ($name && $city && $state) {
            db()->prepare('INSERT IGNORE INTO neighborhoods (name, city, state) VALUES (?,?,?)')->execute([$name, $city, $state]);
            $msg = "✅ تم إضافة الحي «$name»";
        }
    }
    if ($action === 'delete_neighborhood') {
        $id = (int)($_POST['nid'] ?? 0);
        db()->prepare('DELETE FROM neighborhoods WHERE id = ?')->execute([$id]);
        $msg = "✅ تم حذف الحي #$id";
    }

    // ── الشركاء ───────────────────────────────────────────────
    if ($action === 'add_partner') {
        $key = bin2hex(random_bytes(32));
        db()->prepare('INSERT INTO partners (name, api_key, track) VALUES (?,?,?)')->execute([$_POST['name'] ?? '', hash('sha256', $key), $_POST['track'] ?? '']);
        $_SESSION['admin_msg'] = "✅ تم إضافة الشريك — API Key: <strong dir='ltr'>$key</strong> — احفظه الآن";
        header('Location: ' . url('admin.php?tab=partners')); exit;
    }
    if ($action === 'toggle_partner') { $id=(int)($_POST['pid']??0); $a=(int)($_POST['active']??0); db()->prepare('UPDATE partners SET active=? WHERE id=?')->execute([$a?0:1,$id]); $msg="✅ تم تحديث حالة الشريك"; }

    // ── الموظفون ──────────────────────────────────────────────
    if ($action === 'add_staff' && in_array($role, ['super_admin'])) {
        $s_email = trim(strtolower($_POST['s_email'] ?? ''));
        $s_pass  = $_POST['s_pass'] ?? '';
        $s_name  = mb_substr(trim($_POST['s_name'] ?? ''), 0, 100);
        $s_role  = in_array($_POST['s_role'] ?? '', ['admin','supervisor','support','finance','content']) ? $_POST['s_role'] : 'support';
        $s_dept  = mb_substr(trim($_POST['s_dept'] ?? ''), 0, 100);
        if ($s_email && strlen($s_pass) >= 6 && $s_name) {
            try {
                db()->prepare('INSERT INTO staff_members (name, email, password_hash, role, department, created_by) VALUES (?,?,?,?,?,?)')
                    ->execute([$s_name, $s_email, password_hash($s_pass, PASSWORD_BCRYPT, ['cost' => 10]), $s_role, $s_dept, $_SESSION['staff_id'] ?? 0]);
                $msg = "✅ تم إضافة الموظف $s_name"; $log_act('add_staff','staff',(int)db()->lastInsertId());
            } catch (Throwable $e) { $msg = '❌ البريد مستخدم مسبقاً'; }
        } else { $msg = '❌ تأكد من كل الحقول (كلمة المرور 6 أحرف+)'; }
    }
    if ($action === 'toggle_staff' && in_array($role, ['super_admin'])) {
        $id=(int)($_POST['sid']??0); $a=(int)($_POST['active']??0);
        db()->prepare('UPDATE staff_members SET active=? WHERE id=?')->execute([$a?0:1,$id]);
        $msg = "✅ تم تحديث حالة الموظف";
    }
    if ($action === 'reset_staff_pw' && in_array($role, ['super_admin'])) {
        $id=(int)($_POST['sid']??0); $np=trim($_POST['np']??'');
        if($id && strlen($np) >= 6) {
            db()->prepare('UPDATE staff_members SET password_hash=? WHERE id=?')->execute([password_hash($np,PASSWORD_BCRYPT,['cost'=>10]),$id]);
            $msg = "✅ تم تغيير كلمة مرور الموظف";
        }
    }

    // ── الفواتير ──────────────────────────────────────────────
    if ($action === 'add_invoice') {
        $uid    = (int)($_POST['inv_uid'] ?? 0);
        $type   = $_POST['inv_type']   ?? 'subscription';
        $desc   = mb_substr(trim($_POST['inv_desc'] ?? ''), 0, 500);
        $amount = (float)($_POST['inv_amount'] ?? 0);
        $curr   = in_array($_POST['inv_curr'] ?? '', ['SDG','USD','SAR','EGP']) ? $_POST['inv_curr'] : 'SDG';
        $method = $_POST['inv_method'] ?? 'cash';
        $due    = $_POST['inv_due'] ?? null;

        if ($amount > 0) {
            $year    = date('Y'); $count = (int)db()->query('SELECT COUNT(*) FROM invoices')->fetchColumn() + 1;
            $inv_no  = 'SD-' . $year . '-' . str_pad($count, 4, '0', STR_PAD_LEFT);
            db()->prepare('INSERT INTO invoices (invoice_no, user_id, staff_id, type, description, amount, currency, payment_method, due_date, created_by) VALUES (?,?,?,?,?,?,?,?,?,?)')
                ->execute([$inv_no, $uid ?: null, $_SESSION['staff_id'] ?? 0, $type, $desc, $amount, $curr, $method, $due ?: null, $_SESSION['staff_id'] ?? 0]);
            $iid = (int)db()->lastInsertId();
            $msg = "✅ تم إنشاء الفاتورة $inv_no";
        }
    }
    if ($action === 'mark_invoice_paid') {
        $id  = (int)($_POST['inv_id'] ?? 0);
        $ref = mb_substr(trim($_POST['pay_ref'] ?? ''), 0, 200);
        db()->prepare("UPDATE invoices SET status='paid', payment_ref=?, paid_at=NOW() WHERE id=?")->execute([$ref, $id]);
        $msg = "✅ تم تسجيل الدفع للفاتورة #$id";
        $log_act('mark_paid','invoice',$id,$ref);
    }
    if ($action === 'cancel_invoice') {
        $id = (int)($_POST['inv_id'] ?? 0);
        db()->prepare("UPDATE invoices SET status='cancelled' WHERE id=?")->execute([$id]);
        $msg = "✅ تم إلغاء الفاتورة #$id";
    }

    // ── الرسائل ───────────────────────────────────────────────
    if ($action === 'mark_inquiry') { $id=(int)($_POST['id']??0); db()->prepare("UPDATE inquiries SET status='replied' WHERE id=?")->execute([$id]); $msg="✅ تم تحديد الرسالة كمقروءة"; }

    // ── مزودو الخدمات ─────────────────────────────────────────
    if ($action === 'approve_provider') {
        $id   = (int)($_POST['app_id'] ?? 0);
        $type = $_POST['prov_type'] ?? 'user';
        $allowed_types = ['teacher','doctor','pharmacist','service_provider','academic','hospital'];
        if (!in_array($type, $allowed_types)) $type = 'user';
        $app = db()->prepare('SELECT * FROM provider_applications WHERE id = ? LIMIT 1');
        $app->execute([$id]);
        $a = $app->fetch();
        if ($a) {
            db()->prepare("UPDATE provider_applications SET status='approved', reviewed_by=?, reviewed_at=NOW() WHERE id=?")->execute([$_SESSION['staff_id']??0, $id]);
            db()->prepare('UPDATE users SET user_type=?, provider_specialty=?, provider_verified=1 WHERE id=?')->execute([$type, $a['specialty'], $a['user_id']]);
            save_notification($a['user_id'], 'provider_approved', '🎉 تمت الموافقة على طلبك', "أنت الآن مزود خدمة موثّق في سودانا! بادجك ✅ سيظهر في كل تفاعلاتك.");
            $log_act('approve_provider','provider',$id,$type);
            $msg = "✅ تمت الموافقة على المزود #$id";
        }
    }
    if ($action === 'reject_provider') {
        $id     = (int)($_POST['app_id'] ?? 0);
        $reason = mb_substr(trim($_POST['reject_reason'] ?? ''), 0, 300);
        $app = db()->prepare('SELECT user_id FROM provider_applications WHERE id = ? LIMIT 1');
        $app->execute([$id]);
        $a = $app->fetch();
        if ($a) {
            db()->prepare("UPDATE provider_applications SET status='rejected', rejection_reason=?, reviewed_by=?, reviewed_at=NOW() WHERE id=?")->execute([$reason, $_SESSION['staff_id']??0, $id]);
            save_notification($a['user_id'], 'provider_rejected', 'بخصوص طلب الانضمام', $reason ?: 'لم تستوفِ الطلب الشروط المطلوبة. يمكنك التقديم مجدداً.');
            $msg = "✅ تم رفض الطلب #$id";
        }
    }
    if ($action === 'needs_docs_provider') {
        $id  = (int)($_POST['app_id'] ?? 0);
        $msg_txt = mb_substr(trim($_POST['docs_msg'] ?? 'يرجى رفع مستندات إضافية'), 0, 300);
        $app = db()->prepare('SELECT user_id FROM provider_applications WHERE id = ? LIMIT 1');
        $app->execute([$id]);
        $a = $app->fetch();
        if ($a) {
            db()->prepare("UPDATE provider_applications SET status='needs_docs', rejection_reason=? WHERE id=?")->execute([$msg_txt, $id]);
            save_notification($a['user_id'], 'provider_needs_docs', '📄 مطلوب مستندات إضافية', $msg_txt);
            $msg = "✅ تم طلب مستندات إضافية للطلب #$id";
        }
    }

    // ── طلبات الاشتراك ────────────────────────────────────────
    if ($action === 'approve_subscription') {
        $id  = (int)($_POST['sub_id'] ?? 0);
        $ref = mb_substr(trim($_POST['pay_ref'] ?? ''), 0, 100);
        $req = db()->prepare('SELECT * FROM subscription_requests WHERE id = ? LIMIT 1');
        $req->execute([$id]);
        $r = $req->fetch();
        if ($r) {
            $months  = (int)($r['duration_months'] ?? 1);
            $expires = date('Y-m-d H:i:s', time() + $months * 30 * 86400);
            db()->prepare("UPDATE subscription_requests SET status='approved', payment_ref=?, reviewed_by=?, reviewed_at=NOW(), expires_at=? WHERE id=?")->execute([$ref, $_SESSION['staff_id']??0, $expires, $id]);
            db()->prepare("UPDATE users SET subscription_tier='paid', subscription_expires_at=? WHERE id=?")->execute([$expires, $r['user_id']]);
            if ($r['invoice_id']) db()->prepare("UPDATE invoices SET status='paid', payment_ref=?, paid_at=NOW() WHERE id=?")->execute([$ref, $r['invoice_id']]);
            save_notification($r['user_id'], 'subscription_activated', '🎉 تم تفعيل اشتراكك!', "اشتراكك المدفوع نشط حتى " . date('Y-m-d', strtotime($expires)) . " — أبشر!");
            $log_act('approve_subscription','subscription',$id);
            $msg = "✅ تم تفعيل الاشتراك للمستخدم #{$r['user_id']}";
        }
    }
    if ($action === 'reject_subscription') {
        $id     = (int)($_POST['sub_id'] ?? 0);
        $reason = mb_substr(trim($_POST['reject_reason'] ?? ''), 0, 300);
        $req = db()->prepare('SELECT user_id FROM subscription_requests WHERE id = ? LIMIT 1');
        $req->execute([$id]);
        $r = $req->fetch();
        if ($r) {
            db()->prepare("UPDATE subscription_requests SET status='rejected', rejection_reason=? WHERE id=?")->execute([$reason, $id]);
            save_notification($r['user_id'], 'subscription_rejected', 'بخصوص طلب الاشتراك', $reason ?: 'لم نتمكن من التحقق من الإيصال. تواصل معنا.');
            $msg = "✅ تم رفض طلب الاشتراك #$id";
        }
    }

    // ── FIX 3: تحديث أسعار وحدود خطط الاشتراك ──────────────────
    if ($action === 'update_plan') {
        $planKey   = trim($_POST['plan_key'] ?? '');
        $priceSdg  = max(0, (int)($_POST['price_sdg'] ?? 0));
        $aiLimit   = max(1, min(1000, (int)($_POST['ai_requests_day'] ?? 20)));
        $bkLimit   = max(1, min(100,  (int)($_POST['booking_per_day']  ?? 2)));
        $bdeLimit  = max(0, min(999,  (int)($_POST['bde_docs_month']   ?? 3)));
        $isActive  = isset($_POST['is_active']) ? 1 : 0;
        $discount  = max(0, min(100, (float)($_POST['discount_pct'] ?? 0)));

        if ($planKey && in_array($planKey, ['free','plus','pro'])) {
            try {
                db()->prepare(
                    "UPDATE subscription_plans SET
                     price_sdg=?, ai_requests_day=?, booking_per_day=?,
                     bde_docs_month=?, is_active=?, discount_pct=?,
                     updated_at=NOW()
                     WHERE plan_key=?"
                )->execute([$priceSdg, $aiLimit, $bkLimit, $bdeLimit, $isActive, $discount, $planKey]);
                $msg = "✅ تم تحديث خطة «{$planKey}» — التغييرات مباشرة في Gateway";
                $log_act('update_plan', 'subscription_plan', 0);
            } catch (Throwable $e) {
                $msg = "❌ خطأ: " . $e->getMessage();
            }
        } else {
            $msg = "❌ خطة غير صالحة";
        }
    }


    if ($action === 'approve_lesson_sub') {
        $id = (int)($_POST['sub_id'] ?? 0);
        $sub = db()->prepare('SELECT * FROM lesson_submissions WHERE id = ? LIMIT 1');
        $sub->execute([$id]);
        $s = $sub->fetch();
        if ($s) {
            db()->prepare('INSERT INTO lessons (partner_id, track, title, content, quiz_question, quiz_options, quiz_answer, order_index) VALUES (?,?,?,?,?,?,?,?)')
                ->execute([null, $s['track'], $s['title'], $s['content'], $s['quiz_question'], $s['quiz_options'], $s['quiz_answer'], 0]);
            $lid = (int)db()->lastInsertId();
            db()->prepare("UPDATE lesson_submissions SET status='approved', reviewed_by=?, reviewed_at=NOW(), published_lesson_id=? WHERE id=?")->execute([$_SESSION['staff_id']??0, $lid, $id]);
            save_notification($s['user_id'], 'lesson_approved', '📚 تم نشر درسك!', "درسك «{$s['title']}» تم نشره في الأكاديمية ✅");
            $log_act('approve_lesson','lesson',$id);
            $msg = "✅ تم نشر الدرس #{$id}";
        }
    }
    if ($action === 'reject_lesson_sub') {
        $id     = (int)($_POST['sub_id'] ?? 0);
        $reason = mb_substr(trim($_POST['reject_reason'] ?? ''), 0, 300);
        $sub = db()->prepare('SELECT user_id, title FROM lesson_submissions WHERE id = ? LIMIT 1');
        $sub->execute([$id]);
        $s = $sub->fetch();
        if ($s) {
            db()->prepare("UPDATE lesson_submissions SET status='rejected', rejection_reason=? WHERE id=?")->execute([$reason, $id]);
            save_notification($s['user_id'], 'lesson_rejected', 'بخصوص درسك', "درسك «{$s['title']}» يحتاج مراجعة: {$reason}");
            $msg = "✅ تم رفض الدرس #$id";
        }
    }
    // ── CRM Notes ─────────────────────────────────────────────
    if ($action === 'add_crm_note') {
        $uid  = (int)($_POST['crm_uid'] ?? 0);
        $note = mb_substr(trim($_POST['crm_note'] ?? ''), 0, 1000);
        $type = in_array($_POST['crm_type']??'', ['general','financial','support','provider','complaint']) ? $_POST['crm_type'] : 'general';
        if ($uid && $note) {
            db()->prepare('INSERT INTO crm_notes (user_id, staff_id, note, type) VALUES (?,?,?,?)')->execute([$uid, $_SESSION['staff_id']??0, $note, $type]);
            $msg = "✅ تم إضافة ملاحظة CRM";
        }
    }

    // ── Dashboard tab (no POST needed) ────────────────────────

    // ── إضافة مزود مباشرة من الأدمن ─────────────────────────
    if ($action === 'admin_add_provider') {
        $uid   = (int)($_POST['user_id'] ?? 0);
        $type  = in_array($_POST['ptype']??'', ['teacher','doctor','pharmacist','service_provider','academic','hospital']) ? $_POST['ptype'] : '';
        $spec  = mb_substr(trim($_POST['specialty']??''), 0, 200);
        $bio   = mb_substr(trim($_POST['bio']??''), 0, 500);
        if ($uid && $type && $spec) {
            db()->prepare('UPDATE users SET user_type=?,provider_specialty=?,provider_bio=?,provider_verified=1 WHERE id=?')->execute([$type,$spec,$bio,$uid]);
            db()->prepare("INSERT IGNORE INTO provider_applications (user_id,type,specialty,bio,status,reviewed_by,reviewed_at) VALUES (?,?,?,?,'approved',?,NOW())")->execute([$uid,$type,$spec,$bio,$_SESSION['staff_id']??0]);
            save_notification($uid,'provider_approved','🎉 تم تفعيل حسابك كمزود','تم تفعيل حسابك كمزود خدمة موثّق في سودانا!');
            $msg = "✅ تم تفعيل المزود #{$uid} كـ $type"; $log_act('admin_add_provider','user',$uid,$type);
        }
    }

    // ── الصيدليات ────────────────────────────────────────────
    if ($action === 'approve_pharmacy') {
        $id = (int)($_POST['pharm_id']??0);
        $ph = db()->prepare('SELECT user_id,name FROM pharmacies WHERE id=? LIMIT 1'); $ph->execute([$id]); $pharmacy=$ph->fetch();
        if ($pharmacy) {
            db()->prepare("UPDATE pharmacies SET status='active',verified=1 WHERE id=?")->execute([$id]);
            db()->prepare("UPDATE neighborhood_services SET status='active',is_verified=1 WHERE pharmacy_id=?")->execute([$id]);
            if ($pharmacy['user_id']) {
                save_notification($pharmacy['user_id'],'pharmacy_approved','✅ صيدليتك مفعّلة!',"تم تفعيل صيدلية «{$pharmacy['name']}» في سودانا");
                db()->prepare('UPDATE users SET user_type="pharmacist",provider_verified=1 WHERE id=?')->execute([$pharmacy['user_id']]);
            }
            $msg = "✅ تم تفعيل الصيدلية #{$id}"; $log_act('approve_pharmacy','pharmacy',$id);
        }
    }
    if ($action === 'reject_pharmacy') {
        $id = (int)($_POST['pharm_id']??0);
        $ph = db()->prepare('SELECT user_id,name FROM pharmacies WHERE id=? LIMIT 1'); $ph->execute([$id]); $pharmacy=$ph->fetch();
        if ($pharmacy) {
            db()->prepare("UPDATE pharmacies SET status='suspended' WHERE id=?")->execute([$id]);
            if ($pharmacy['user_id']) save_notification($pharmacy['user_id'],'pharmacy_rejected','بخصوص طلب صيدليتك',trim($_POST['reject_reason']??'لم تستوفِ الشروط'));
            $msg = "✅ تم رفض الصيدلية #{$id}";
        }
    }
    if ($action === 'admin_add_pharmacy') {
        $name = mb_substr(trim($_POST['ph_name']??''), 0, 200);
        $lic  = mb_substr(trim($_POST['ph_license']??''), 0, 100);
        $addr = mb_substr(trim($_POST['ph_address']??''), 0, 300);
        $phone= mb_substr(trim($_POST['ph_phone']??''), 0, 30);
        $state= mb_substr(trim($_POST['ph_state']??''), 0, 100);
        $city = mb_substr(trim($_POST['ph_city']??''), 0, 100);
        if ($name && $lic) {
            db()->prepare("INSERT INTO pharmacies (name,license_no,address,phone,whatsapp,state,city,status,verified) VALUES (?,?,?,?,?,?,?,'active',1)")->execute([$name,$lic,$addr,$phone,$phone,$state,$city]);
            $pid=(int)db()->lastInsertId();
            db()->prepare("INSERT INTO neighborhood_services (pharmacy_id,state,city,category,name,address,phone,status,is_verified) VALUES (?,?,?,'health',?,?,?,'active',1)")->execute([$pid,$state,$city,"صيدلية: $name",$addr,$phone]);
            $msg = "✅ تمت إضافة الصيدلية «$name»"; $log_act('add_pharmacy','pharmacy',$pid);
        }
    }

    // ── الخدمات ─────────────────────────────────────────────
    if ($action === 'approve_service') {
        $id = (int)($_POST['svc_id']??0);
        db()->prepare("UPDATE neighborhood_services SET status='active',is_verified=1 WHERE id=?")->execute([$id]);
        $svc=db()->prepare('SELECT provider_user_id,name FROM neighborhood_services WHERE id=? LIMIT 1'); $svc->execute([$id]); $s=$svc->fetch();
        if ($s && $s['provider_user_id']) save_notification($s['provider_user_id'],'service_approved','✅ تم نشر خدمتك',"خدمتك «{$s['name']}» ظهرت في دليل الحي");
        $msg = "✅ تم نشر الخدمة #{$id}";
    }
    if ($action === 'reject_service') {
        $id = (int)($_POST['svc_id']??0);
        db()->prepare("UPDATE neighborhood_services SET status='inactive' WHERE id=?")->execute([$id]);
        $msg = "✅ تم رفض الخدمة #{$id}";
    }
    if ($action === 'admin_add_service') {
        $name = mb_substr(trim($_POST['sv_name']??''), 0, 200);
        $cat  = in_array($_POST['sv_cat']??'', ['health','education','food','services','social','religion','security','transport']) ? $_POST['sv_cat'] : 'services';
        $state= mb_substr(trim($_POST['sv_state']??''), 0, 100);
        $city = mb_substr(trim($_POST['sv_city']??''), 0, 100);
        $phone= mb_substr(trim($_POST['sv_phone']??''), 0, 30);
        if ($name) {
            db()->prepare("INSERT INTO neighborhood_services (state,city,category,name,address,phone,status,is_verified) VALUES (?,?,?,?,?,?,'active',1)")->execute([$state,$city,$cat,$name,trim($_POST['sv_address']??''),$phone]);
            $msg = "✅ تمت إضافة الخدمة «$name»";
        }
    }

    // ── الفعاليات ────────────────────────────────────────────
    if ($action === 'approve_event') {
        $id = (int)($_POST['evt_id']??0);
        db()->prepare("UPDATE community_events SET status='active' WHERE id=?")->execute([$id]);
        $ev=db()->prepare('SELECT organizer_id,title FROM community_events WHERE id=? LIMIT 1'); $ev->execute([$id]); $e=$ev->fetch();
        if ($e) save_notification($e['organizer_id'],'event_approved','✅ تمت الموافقة على فعاليتك',"فعاليتك «{$e['title']}» نُشرت في المنصة");
        $msg = "✅ تمت الموافقة على الفعالية";
    }
    if ($action === 'reject_event') {
        $id = (int)($_POST['evt_id']??0);
        db()->prepare("UPDATE community_events SET status='cancelled' WHERE id=?")->execute([$id]);
        $msg = "✅ تم رفض الفعالية";
    }

    // ── العقود ──────────────────────────────────────────────
    if ($action === 'admin_generate_contract') {
        $tpl_id = (int)($_POST['tpl_id']??0);
        $party  = mb_substr(trim($_POST['party_name']??''), 0, 200);
        $email  = mb_substr(trim($_POST['party_email']??''), 0, 191);
        $vars_raw = json_decode($_POST['variables']??'{}', true) ?? [];
        $tpl = db()->prepare('SELECT * FROM contract_templates WHERE id=? LIMIT 1'); $tpl->execute([$tpl_id]); $template=$tpl->fetch();
        if ($template && $party) {
            $body = $template['body_ar'];
            foreach ($vars_raw as $k => $v) $body = str_replace("{{{$k}}}", htmlspecialchars($v), $body);
            $ai_summary = ask_ai("لخّص هذا العقد في 3 نقاط:
$body", 'كن مختصراً.', 'fast', 150, 0.3);
            db()->prepare('INSERT INTO contracts (title,type,party_name,party_email,content,ai_summary,template_id,variables,status,created_by) VALUES (?,?,?,?,?,?,?,?,?,?)')->execute([$template['name'],$template['type'],$party,$email,$body,$ai_summary,$tpl_id,json_encode($vars_raw,JSON_UNESCAPED_UNICODE),'draft',$_SESSION['staff_id']??0]);
            $msg = "✅ تم توليد العقد — يمكن مراجعته في تبويب العقود";
        }
    }

    // ── CRM Notes ─────────────────────────────────────────────
    if ($action === 'add_crm_note') {
        $uid  = (int)($_POST['crm_uid'] ?? 0);
        $note = mb_substr(trim($_POST['crm_note'] ?? ''), 0, 1000);
        $type = in_array($_POST['crm_type']??'', ['general','financial','support','provider','complaint']) ? $_POST['crm_type'] : 'general';
        if ($uid && $note) {
            db()->prepare('INSERT INTO crm_notes (user_id, staff_id, note, type) VALUES (?,?,?,?)')->execute([$uid, $_SESSION['staff_id']??0, $note, $type]);
            db()->prepare('INSERT INTO crm_timeline (user_id,staff_id,event_type,event_data) VALUES (?,?,?,?)')->execute([$uid,$_SESSION['staff_id']??0,'crm_note',json_encode(['note'=>mb_substr($note,0,100),'type'=>$type],JSON_UNESCAPED_UNICODE)]);
            $msg = "✅ تم إضافة ملاحظة CRM";
        }
    }

    // ── Broadcast Push ────────────────────────────────────────
    if ($action === 'broadcast_push') {
        $b_title   = mb_substr(trim($_POST['b_title']   ?? ''), 0, 200);
        $b_body    = mb_substr(trim($_POST['b_body']    ?? ''), 0, 500);
        $b_segment = $_POST['b_segment'] ?? 'all';
        $b_value   = mb_substr(trim($_POST['b_value']   ?? ''), 0, 100);

        $allowed_segments = ['all','paid','free','state','city','hood','track','user_type'];
        if (!in_array($b_segment, $allowed_segments)) $b_segment = 'all';

        if ($b_title && $b_body) {
            $result = broadcast_push($b_title, $b_body, [
                'segment' => $b_segment,
                'value'   => $b_value,
                'limit'   => 2000,
            ], ['tag' => 'broadcast', 'url' => '/']);

            $msg = "✅ تم الإرسال — أُرسل لـ {$result['sent']} مستخدم"
                 . ($result['failed']  > 0 ? " | فشل: {$result['failed']}" : '')
                 . " | إجمالي المستهدفين: {$result['total_targeted']}";
            $log_act('broadcast_push', 'notification', 0, "$b_title → {$b_segment}:{$b_value} sent:{$result['sent']}");
        } else {
            $msg = '❌ أدخل العنوان والمحتوى';
        }
        $tab = 'broadcast';
    }

    // ── تصدير ─────────────────────────────────────────────────
    if ($action === 'sign_contract') {
        $cid = (int)($_POST['contract_id']??0);
        db()->prepare("UPDATE contracts SET status='signed',signed_at=NOW() WHERE id=?")->execute([$cid]);
        $msg = "✅ تم توقيع العقد #$cid"; $log_act('sign_contract','contract',$cid);
    }
    if ($action === 'export_users') {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=users_'.date('Ymd').'.csv');
        $fp=fopen('php://output','w'); fputs($fp,"\xEF\xBB\xBF");
        fputcsv($fp,['ID','الاسم','البريد','الاشتراك','الولاية','المدينة','الحي','المسار','تعلم','تجارة','مجتمع','أسرة','الرتبة','التاريخ']);
        foreach(db()->query('SELECT id,name,email,subscription_tier,state,city,neighborhood,learning_track,points_learn,points_trade,points_community,points_family,rank_title,created_at FROM users ORDER BY id') as $r) fputcsv($fp,$r);
        fclose($fp); exit;
    }
    if ($action === 'export_invoices') {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=invoices_'.date('Ymd').'.csv');
        $fp=fopen('php://output','w'); fputs($fp,"\xEF\xBB\xBF");
        fputcsv($fp,['رقم الفاتورة','المستخدم','النوع','الوصف','المبلغ','العملة','الحالة','طريقة الدفع','مرجع الدفع','تاريخ الاستحقاق','تاريخ الدفع','تاريخ الإنشاء']);
        foreach(db()->query('SELECT i.invoice_no,u.name,i.type,i.description,i.amount,i.currency,i.status,i.payment_method,i.payment_ref,i.due_date,i.paid_at,i.created_at FROM invoices i LEFT JOIN users u ON u.id=i.user_id ORDER BY i.id DESC') as $r) fputcsv($fp,$r);
        fclose($fp); exit;
    }
    if ($action === 'export_investors') {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=investors_'.date('Ymd').'.csv');
        $fp=fopen('php://output','w'); fputs($fp,"\xEF\xBB\xBF");
        fputcsv($fp,['ID','الاسم','البريد','الهاتف','الدولة','الفئة','الحالة','التاريخ']);
        foreach(db()->query('SELECT id,name,email,phone,country,tier,status,created_at FROM investment_applications ORDER BY id') as $r) fputcsv($fp,$r);
        fclose($fp); exit;
    }

    if (!empty($msg) && str_contains($msg, '<strong>')) { $_SESSION['admin_msg'] = $msg; header('Location: ' . url('admin.php?tab=').$tab); exit; }
    header('Location: ' . url('admin.php?tab=').$tab.($msg?'&msg='.urlencode(strip_tags($msg)):'')); exit;
}

$session_msg = $_SESSION['admin_msg'] ?? ''; unset($_SESSION['admin_msg']);
$msg = $session_msg ?: htmlspecialchars($_GET['msg'] ?? '');

// ── صفحة تسجيل الدخول ────────────────────────────────────────
if (empty($_SESSION['admin'])) { ?>
<!DOCTYPE html><html lang="ar" dir="rtl">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin — سودانا</title>
<style>*{box-sizing:border-box}body{background:#073328;display:flex;align-items:center;justify-content:center;min-height:100vh;font-family:Arial,sans-serif;margin:0}.box{background:#fff;padding:36px;border-radius:16px;width:340px;text-align:center}.logo{font-size:1.8rem;font-weight:900;color:#073328;margin-bottom:4px}.sub{color:#888;font-size:.82rem;margin-bottom:20px}label{display:block;text-align:right;font-size:.82rem;color:#555;margin-bottom:4px}input{width:100%;padding:10px;margin-bottom:12px;border:1.5px solid #ddd;border-radius:8px;font-size:.9rem;font-family:Arial}button{width:100%;padding:12px;background:#073328;color:#fff;border:none;border-radius:8px;font-size:1rem;cursor:pointer;font-weight:700}</style>
</head><body><div class="box"><div class="logo">🇸🇩 سودانا</div><div class="sub">لوحة التحكم</div>
<form method="POST">
  <input type="hidden" name="csrf" value="<?= $csrf ?>">
  <input type="hidden" name="action" value="login">
  <label>البريد الإلكتروني (للموظفين)</label>
  <input type="email" name="email" placeholder="admin@sudanna.ai" autocomplete="email">
  <label>كلمة المرور</label>
  <input type="password" name="password" placeholder="••••••" autofocus>
  <button>دخول ←</button>
</form></div>
        <!-- ══════════════════════════════════════════════════
             SUDANNA PAY ADMIN PANEL
             ══════════════════════════════════════════════════ -->
        <div id="sdpay-panel" style="display:none">
          <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;margin-bottom:20px">
            <div class="stat-card" id="sp-total-vol">
              <div style="font-size:.75rem;color:var(--muted)">حجم اليوم</div>
              <div style="font-size:1.4rem;font-weight:900">جاري...</div>
            </div>
            <div class="stat-card" id="sp-txn-count">
              <div style="font-size:.75rem;color:var(--muted)">معاملات اليوم</div>
              <div style="font-size:1.4rem;font-weight:900">—</div>
            </div>
            <div class="stat-card" id="sp-revenue">
              <div style="font-size:.75rem;color:var(--muted)">إيرادات اليوم</div>
              <div style="font-size:1.4rem;font-weight:900">—</div>
            </div>
            <div class="stat-card" id="sp-wallets">
              <div style="font-size:.75rem;color:var(--muted)">إجمالي المحافظ</div>
              <div style="font-size:1.4rem;font-weight:900">—</div>
            </div>
            <div class="stat-card" id="sp-disputes">
              <div style="font-size:.75rem;color:var(--muted);color:#dc2626">نزاعات مفتوحة</div>
              <div style="font-size:1.4rem;font-weight:900;color:#dc2626">—</div>
            </div>
            <div class="stat-card" id="sp-pending">
              <div style="font-size:.75rem;color:var(--muted)">معاملات معلقة</div>
              <div style="font-size:1.4rem;font-weight:900">—</div>
            </div>
          </div>

          <h3 style="margin:16px 0 8px;font-size:.95rem">&#128196; آخر المعاملات</h3>
          <div id="sp-txn-list" style="background:#0d1117;border-radius:10px;padding:12px;font-family:monospace;font-size:.78rem;max-height:300px;overflow-y:auto">جاري التحميل...</div>

          <h3 style="margin:16px 0 8px;font-size:.95rem;color:#dc2626">&#9888; النزاعات المفتوحة</h3>
          <div id="sp-disputes-list" style="background:#1a0a0a;border-radius:10px;padding:12px;font-size:.82rem;max-height:250px;overflow-y:auto">جاري التحميل...</div>

          <h3 style="margin:16px 0 8px;font-size:.95rem;color:#d97706">&#128736; تقارير AML</h3>
          <div id="sp-aml-list" style="background:#1a1500;border-radius:10px;padding:12px;font-size:.82rem;max-height:200px;overflow-y:auto">جاري التحميل...</div>
        </div>

        <script>
        async function loadPayPanel() {
          try {
            const [dash, txns, disputes, aml] = await Promise.all([
              fetch('/api/accounting/dashboard.php').then(r=>r.json()),
              fetch('/api/pay/history.php?limit=20&all=1').then(r=>r.json()),
              fetch('/api/pay/dispute.php?action=list').then(r=>r.json()),
              fetch('/api/admin/aml.php').then(r=>r.json()).catch(()=>({data:[]})),
            ]);
            const d = dash.data || {};
            document.getElementById('sp-total-vol').querySelector('div:last-child').textContent = 
              Number(d.txn_volume_sdg||0).toLocaleString('ar-SA') + ' SDG';
            document.getElementById('sp-txn-count').querySelector('div:last-child').textContent = d.txn_count||0;
            document.getElementById('sp-revenue').querySelector('div:last-child').textContent = 
              Number(d.revenue_sdg||0).toLocaleString('ar-SA') + ' SDG';
            document.getElementById('sp-wallets').querySelector('div:last-child').textContent = 
              Number(d.total_wallets_sdg||0).toLocaleString('ar-SA') + ' SDG';
            document.getElementById('sp-disputes').querySelector('div:last-child').textContent = d.open_disputes||0;
            document.getElementById('sp-pending').querySelector('div:last-child').textContent = d.pending_reconcile||0;

            const tl = txns.data || txns.transactions || [];
            document.getElementById('sp-txn-list').innerHTML = tl.length ? 
              tl.map(t => `<div style="border-bottom:1px solid #222;padding:4px 0">
                <span style="color:#${t.status==='completed'?'3fb950':t.status==='failed'?'f87171':'fbbf24'}">${t.status}</span>
                &nbsp;${t.txn_ref} &nbsp;|&nbsp; ${Number(t.amount_sdg||0).toLocaleString()} SDG
                &nbsp;|&nbsp; ${t.type} &nbsp;|&nbsp; ${(t.created_at||'').substring(0,16)}
              </div>`).join('') : '<p style="color:#666">لا معاملات</p>';

            const dl = disputes.disputes || disputes.data || [];
            document.getElementById('sp-disputes-list').innerHTML = dl.length ?
              dl.map(d => `<div style="border-bottom:1px solid #333;padding:6px 0">
                <span style="color:#f87171;font-weight:700">#${d.id}</span> ${d.subject||''} 
                &nbsp;|&nbsp; <span style="color:#fbbf24">${d.priority||'normal'}</span>
                &nbsp;|&nbsp; ${(d.created_at||'').substring(0,10)}
              </div>`).join('') : '<p style="color:#666">لا نزاعات مفتوحة ✅</p>';
          } catch(e) {
            console.error('Pay panel error:', e);
          }
        }
        document.addEventListener('DOMContentLoaded', () => {
          const btn = document.querySelector('[data-tab="sdpay"]') || document.querySelector('button[onclick*="sdpay"]');
          if (btn) btn.addEventListener('click', loadPayPanel);
          // Auto-load if pay panel visible
          setTimeout(() => { if(document.getElementById('sdpay-panel')?.offsetParent) loadPayPanel(); }, 500);
        });
        </script>

</body></html>
<?php exit; }

// ── إحصائيات ─────────────────────────────────────────────────
$role = $_SESSION['admin_role'] ?? 'support';
$admin_name = $_SESSION['admin_name'] ?? 'الأدمن';
// FIX 2: All stats wrapped in try/catch — HTTP 500 eliminated
$stats = ['users'=>0,'paid'=>0,'items'=>0,'posts'=>0,'lessons'=>0,
          'inquiries'=>0,'invoices_pending'=>0,'staff'=>0];
try { $stats['users']     = (int)db()->query("SELECT COUNT(*) FROM users")->fetchColumn(); } catch(Throwable $i){}
try { $stats['paid']      = (int)db()->query("SELECT COUNT(*) FROM users WHERE subscription_tier IN ('paid','plus','pro')")->fetchColumn(); } catch(Throwable $i){}
try { $stats['items']     = (int)db()->query("SELECT COUNT(*) FROM marketplace_items WHERE status='active'")->fetchColumn(); } catch(Throwable $i){}
try { $stats['posts']     = (int)db()->query("SELECT COUNT(*) FROM pulse_posts WHERE status='active'")->fetchColumn(); } catch(Throwable $i){}
try { $stats['lessons']   = (int)db()->query("SELECT COUNT(*) FROM lessons")->fetchColumn(); } catch(Throwable $i){}
try { $stats['inquiries'] = (int)db()->query("SELECT COUNT(*) FROM inquiries WHERE status='new'")->fetchColumn(); } catch(Throwable $i){}
try { $stats['invoices_pending'] = (int)db()->query("SELECT COUNT(*) FROM invoices WHERE status='pending'")->fetchColumn(); } catch(Throwable $i){}
try { $stats['staff']     = (int)db()->query("SELECT COUNT(*) FROM staff_members WHERE active=1")->fetchColumn(); } catch(Throwable $i){}

$tab = $_GET['tab'] ?? 'users';
?>
<!DOCTYPE html><html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin — سودانا</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:Arial,sans-serif;background:#f0f2f5;color:#1a1a1a;font-size:14px}
.top{background:#073328;color:#fff;padding:12px 20px;display:flex;justify-content:space-between;align-items:center;position:sticky;top:0;z-index:100;gap:12px}
.top-left{display:flex;align-items:center;gap:12px}
.top h1{font-size:1rem;font-weight:700}.role-badge{background:rgba(255,255,255,.15);padding:2px 10px;border-radius:10px;font-size:.72rem}
.top a{color:rgba(255,255,255,.7);text-decoration:none;font-size:.8rem}
.stats{display:flex;gap:8px;padding:12px 20px;flex-wrap:wrap;background:#fff;border-bottom:1px solid #e0e0e0}
.stat{background:#f8faf9;border-radius:10px;padding:10px 14px;text-align:center;min-width:80px;border:1px solid #e8f5e9;cursor:default}
.stat strong{display:block;font-size:1.4rem;color:#073328;font-weight:900}
.stat span{font-size:.7rem;color:#666}
.tabs{display:flex;gap:0;padding:0 12px;background:#fff;border-bottom:2px solid #e0e0e0;overflow-x:auto}
.tab-btn{padding:10px 12px;border:none;background:none;cursor:pointer;font-size:.78rem;border-bottom:3px solid transparent;margin-bottom:-2px;white-space:nowrap;font-family:Arial}
.tab-btn.active{border-bottom-color:#073328;color:#073328;font-weight:700}
.content{padding:16px 20px;max-width:1500px}
.msg{padding:10px 14px;border-radius:8px;margin-bottom:14px;font-size:.85rem;background:#e8f5e9;color:#2e7d32;border:1px solid #a5d6a7}
.sec-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px}
.sec-head h3{font-size:.9rem;color:#073328;font-weight:700}
table{width:100%;border-collapse:collapse;background:#fff;border-radius:10px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,.08);margin-bottom:16px;font-size:.78rem}
th{background:#073328;color:#fff;padding:8px 10px;text-align:right;font-weight:600;font-size:.74rem}
td{padding:7px 10px;border-bottom:1px solid #f0f0f0;vertical-align:middle}
tr:hover td{background:#fafafa}
.badge{padding:2px 8px;border-radius:10px;font-size:.7rem;font-weight:700;display:inline-block}
.b-free{background:#e8f5e9;color:#2e7d32}.b-paid{background:#fff3e0;color:#e65100}
.b-active{background:#e3f2fd;color:#1565c0}.b-removed{background:#ffebee;color:#c62828}
.b-resolved{background:#f3e5f5;color:#6a1b9a}.b-pending{background:#fff8e1;color:#f57f17}
.b-paid-inv{background:#e8f5e9;color:#2e7d32}.b-cancelled{background:#f5f5f5;color:#757575}
.b-medication{background:#fff8e1;color:#f57f17}.b-health{background:#e8f5e9;color:#1b5e20}
.b-urgent{background:#ffebee;color:#c62828}.b-super_admin{background:#e8eaf6;color:#3949ab}
.b-admin{background:#e3f2fd;color:#1565c0}.b-finance{background:#fff3e0;color:#e65100}
.b-support{background:#f3e5f5;color:#6a1b9a}.b-content{background:#e8f5e9;color:#2e7d32}
.form-box{background:#fff;padding:16px 18px;border-radius:10px;margin-bottom:14px;box-shadow:0 1px 3px rgba(0,0,0,.08)}
.form-box h3{margin-bottom:10px;color:#073328;font-size:.85rem;font-weight:700}
.form-row{display:flex;gap:8px;flex-wrap:wrap;align-items:flex-start;margin-bottom:8px}
.form-row input,.form-row select,.form-row textarea{padding:7px 10px;border:1.5px solid #ddd;border-radius:7px;font-size:.8rem;font-family:Arial}
.form-row textarea{resize:vertical}
.btn{padding:5px 12px;border:none;border-radius:7px;cursor:pointer;font-size:.75rem;font-weight:700;font-family:Arial;display:inline-block;text-decoration:none}
.btn-g{background:#073328;color:#fff}.btn-r{background:#e53935;color:#fff}
.btn-o{background:#f57c00;color:#fff}.btn-b{background:#1565c0;color:#fff}
.btn-p{background:#6a1b9a;color:#fff}.btn-s{background:#00695c;color:#fff}
.inline-form{display:inline}
.actions{display:flex;gap:4px;flex-wrap:wrap}
.detail-row{display:grid;grid-template-columns:1fr 1fr;gap:6px;font-size:.78rem}
.detail-row span{color:#666}.detail-row strong{color:#1a1a1a}
details summary{cursor:pointer;color:var(--g1,#073328);font-weight:700;font-size:.8rem;padding:4px 0}
</style>
</head>
<body>
<div class="top">
  <div class="top-left">
    <h1>🇸🇩 سودانا Admin</h1>
    <span class="role-badge"><?= htmlspecialchars($admin_name) ?> · <?= $role ?></span>
  </div>
  <div style="display:flex;gap:14px;align-items:center">
    <span style="font-size:.72rem;color:rgba(255,255,255,.4)"><?= date('Y-m-d H:i') ?></span>
    <a href="/" target="_blank">🌐 الموقع</a>
    <a href="/admin.php" onclick="fetch('/api/auth/logout.php',{method:'POST'}).then(()=>{window.location='/admin.php'});return false">خروج</a>
  </div>
</div>

<?php
// إحصائيات إضافية v17
$stats['pharmacies_pending'] = 0; $stats['events_pending'] = 0; $stats['services_pending'] = 0;
$stats['providers_pending'] = 0; $stats['subs_pending'] = 0; $stats['contracts'] = 0;
$stats['active_flows'] = 0; $stats['bookings_today'] = 0;
try { $stats['active_flows'] = (int)db()->query("SELECT COUNT(*) FROM flow_sessions WHERE status='active' AND updated_at > DATE_SUB(NOW(),INTERVAL 1 HOUR)")->fetchColumn(); } catch(Throwable $ignored){}
// v22 stats
$stats['queue_pending'] = 0; $stats['queue_failed'] = 0; $stats['ai_decisions_today'] = 0;
try { $stats['queue_pending']     = (int)db()->query("SELECT COUNT(*) FROM tasks WHERE status IN ('pending','processing')")->fetchColumn(); } catch(Throwable $ignored){}
try { $stats['queue_failed']      = (int)db()->query("SELECT COUNT(*) FROM tasks WHERE status='failed' AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)")->fetchColumn(); } catch(Throwable $ignored){}
try { $stats['ai_decisions_today']= (int)db()->query("SELECT COUNT(*) FROM ai_decisions WHERE DATE(created_at)=CURDATE()")->fetchColumn(); } catch(Throwable $ignored){}
try { $stats['bookings_today'] = (int)db()->query("SELECT COUNT(*) FROM bookings WHERE DATE(created_at)=CURDATE()")->fetchColumn(); } catch(Throwable $ignored){}
try { $stats['pharmacies_pending'] = (int)db()->query("SELECT COUNT(*) FROM pharmacies WHERE status='pending'")->fetchColumn(); } catch(Throwable $ignored){}
try { $stats['events_pending'] = (int)db()->query("SELECT COUNT(*) FROM community_events WHERE status='upcoming' AND created_at > NOW()-INTERVAL 1 DAY")->fetchColumn(); } catch(Throwable $ignored){}
try { $stats['services_pending'] = (int)db()->query("SELECT COUNT(*) FROM neighborhood_services WHERE status='pending'")->fetchColumn(); } catch(Throwable $ignored){}
try { $stats['providers_pending'] = (int)db()->query("SELECT COUNT(*) FROM provider_applications WHERE status='pending'")->fetchColumn(); } catch(Throwable $ignored){}
try { $stats['subs_pending'] = (int)db()->query("SELECT COUNT(*) FROM subscription_requests WHERE status='pending'")->fetchColumn(); } catch(Throwable $ignored){}
try { $stats['contracts'] = (int)db()->query("SELECT COUNT(*) FROM contracts")->fetchColumn(); } catch(Throwable $ignored){}
$total_pending = $stats['pharmacies_pending']+$stats['providers_pending']+$stats['subs_pending']+$stats['services_pending']+$stats['inquiries'];
?>
<div class="stats">
  <?php if($total_pending>0): ?>
  <div class="stat" style="border-color:#e53935;background:#ffebee;cursor:pointer" onclick="location='?tab=providers'">
    <strong style="color:#e53935"><?= $total_pending ?></strong><span>🔴 معلق</span>
  </div>
  <?php endif; ?>
  <div class="stat" onclick="location='?tab=users'"><strong><?= $stats['users'] ?></strong><span>👤 مستخدم</span></div>
  <div class="stat" onclick="location='?tab=subscriptions'" style="<?= $stats['subs_pending']>0?'border-color:#e65100':'' ?>"><strong style="<?= $stats['subs_pending']>0?'color:#e65100':'' ?>"><?= $stats['subs_pending'] ?></strong><span>💳 اشتراك معلق</span></div>
  <div class="stat"><strong style="color:#2196f3"><?= $stats['active_flows'] ?></strong><span>🔄 تدفقات نشطة</span></div>
  <div class="stat"><strong style="color:#4caf50"><?= $stats['bookings_today'] ?></strong><span>📅 حجوزات اليوم</span></div>
  <div class="stat" onclick="location='?tab=providers'" style="<?= $stats['providers_pending']>0?'border-color:#f57c00':'' ?>"><strong style="<?= $stats['providers_pending']>0?'color:#f57c00':'' ?>"><?= $stats['providers_pending'] ?></strong><span>🏅 مزود معلق</span></div>
  <div class="stat" onclick="location='?tab=pharmacies'" style="<?= $stats['pharmacies_pending']>0?'border-color:#9c27b0':'' ?>"><strong style="<?= $stats['pharmacies_pending']>0?'color:#9c27b0':'' ?>"><?= $stats['pharmacies_pending'] ?></strong><span>💊 صيدلية معلقة</span></div>
  <div class="stat" onclick="location='?tab=services'" style="<?= $stats['services_pending']>0?'border-color:#0097a7':'' ?>"><strong style="<?= $stats['services_pending']>0?'color:#0097a7':'' ?>"><?= $stats['services_pending'] ?></strong><span>🏘️ خدمة معلقة</span></div>
  <div class="stat" onclick="location='?tab=items'"><strong><?= $stats['items'] ?></strong><span>🛒 إعلان</span></div>
  <div class="stat" onclick="location='?tab=lessons'"><strong><?= $stats['lessons'] ?></strong><span>📚 درس</span></div>
  <div class="stat" onclick="location='?tab=contracts'"><strong><?= $stats['contracts'] ?></strong><span>📄 عقد</span></div>
  <div class="stat" onclick="location='?tab=queue'" style="<?= ($stats['queue_failed']??0)>0?'border-color:#e53935':'' ?>"><strong style="<?= ($stats['queue_failed']??0)>0?'color:#e53935':'' ?>"><?= $stats['queue_pending']??0 ?></strong><span>⚙️ Queue</span></div>
  <div class="stat" onclick="location='?tab=system_metrics'"><strong><?= $stats['ai_decisions_today']??0 ?></strong><span>🤖 AI Decisions</span></div>
  <div class="stat" onclick="location='?tab=invoices'" style="<?= $stats['invoices_pending']>0?'border-color:#f57c00':'' ?>"><strong style="<?= $stats['invoices_pending']>0?'color:#f57c00':'' ?>"><?= $stats['invoices_pending'] ?></strong><span>🧾 فاتورة معلقة</span></div>
  <div class="stat" onclick="location='?tab=inquiries'" style="<?= $stats['inquiries']>0?'border-color:#e53935':'' ?>"><strong style="<?= $stats['inquiries']>0?'color:#e53935':'' ?>"><?= $stats['inquiries'] ?></strong><span>✉️ رسالة جديدة</span></div>
  <div class="stat" onclick="location='?tab=staff'"><strong><?= $stats['staff'] ?></strong><span>👷 موظف</span></div>
</div>

<div class="tabs">
  <?php
  $all_tabs = ['dashboard'=>'📊 Dashboard','users'=>'👤 المستخدمون','providers'=>'🏅 المزودون','pharmacies'=>'💊 الصيدليات','subscriptions'=>'💳 الاشتراكات','lesson_subs'=>'📝 دروس المعلمين','services'=>'🏘️ دليل الخدمات','events'=>'🎪 الفعاليات','contracts'=>'📄 العقود','crm'=>'🤝 CRM','posts'=>'📢 الحي','items'=>'🛒 السوق','lessons'=>'📚 الأكاديمية','neighborhoods'=>'🗺️ الأحياء','invoices'=>'🧾 الفواتير','staff'=>'👷 الموظفون','broadcast'=>'🔔 الإشعارات','invest'=>'💼 المستثمرون','inquiries'=>'✉️ الرسائل','partners'=>'🤝 الشركاء','ai_logs'=>'🤖 AI Logs','reports'=>'📊 التقارير','queue'=>'⚙️ Queue Tasks','system_metrics'=>'📈 System Metrics',
    'reconciliation'=>'⚖️ التسوية المحاسبية',
    'settlement'=>'💸 صرف المزودين',
    'ledger_view'=>'📒 دفتر الحسابات'];
  foreach($all_tabs as $k=>$l):
  ?>
  <button class="tab-btn <?= $tab===$k?'active':'' ?>" onclick="location.href='?tab=<?= $k ?>'"><?= $l ?></button>
  <?php endforeach; ?>
</div>

<div class="content">
<?php if($msg): ?><div class="msg"><?= $msg ?></div><?php endif; ?>

<?php
// ══════════════════════════════════════════════════════
// DASHBOARD
// ══════════════════════════════════════════════════════
if($tab==='dashboard'):
// ── Quick Stats for Welcome Cards ─────────────────────────────────
$quick_new_users_today = 0;
$quick_bookings_today  = 0;
$quick_queue_pending   = 0;
try {
    $quick_new_users_today = (int)db()->query("SELECT COUNT(*) FROM users WHERE DATE(created_at)=CURDATE()")->fetchColumn();
    $quick_bookings_today  = (int)db()->query("SELECT COUNT(*) FROM bookings WHERE DATE(created_at)=CURDATE()")->fetchColumn();
    $quick_queue_pending   = (int)db()->query("SELECT COUNT(*) FROM tasks WHERE status='pending'")->fetchColumn();
} catch(Throwable $ignored){}
$d_users_week = (int)db()->query("SELECT COUNT(*) FROM users WHERE created_at >= NOW()-INTERVAL 7 DAY")->fetchColumn();
$d_revenue_month = 0; try { $d_revenue_month=(float)db()->query("SELECT COALESCE(SUM(amount),0) FROM invoices WHERE status='paid' AND paid_at>=DATE_FORMAT(NOW(),'%Y-%m-01')")->fetchColumn(); } catch(Throwable $ignored){}
$d_active_subs=(int)db()->query("SELECT COUNT(*) FROM users WHERE subscription_tier='paid'")->fetchColumn();
$d_pending_items = $stats['providers_pending']+$stats['subs_pending']+($stats['pharmacies_pending']??0)+($stats['services_pending']??0);
$d_recent_users=db()->query("SELECT name,email,subscription_tier,user_type,state,created_at FROM users ORDER BY id DESC LIMIT 50")->fetchAll();
$d_recent_actions=[]; try { $d_recent_actions=db()->query("SELECT action,target_type,details,created_at FROM staff_activity_log ORDER BY id DESC LIMIT 10")->fetchAll(); } catch(Throwable $ignored){}
?>
<!-- ── User Journey KPI Cards ───────────────────────────── -->
<div style="background:linear-gradient(135deg,#061F15,#0d3d24);border-radius:14px;padding:18px;margin-bottom:18px;color:#fff">
  <div style="font-weight:800;margin-bottom:14px;display:flex;align-items:center;gap:8px">
    🔥 حالة المنصة اليوم
    <span style="font-size:.72rem;background:rgba(255,255,255,.12);padding:2px 8px;border-radius:6px;opacity:.8"><?= date('Y-m-d H:i') ?></span>
  </div>
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px">
    <div style="background:rgba(255,255,255,.08);border-radius:10px;padding:14px;text-align:center">
      <div style="font-size:1.6rem;font-weight:900"><?= $quick_new_users_today ?></div>
      <div style="font-size:.7rem;opacity:.75">👥 مستخدمين اليوم</div>
    </div>
    <div style="background:rgba(255,255,255,.08);border-radius:10px;padding:14px;text-align:center">
      <div style="font-size:1.6rem;font-weight:900"><?= $quick_bookings_today ?></div>
      <div style="font-size:.7rem;opacity:.75">📅 حجوزات اليوم</div>
    </div>
    <div style="background:rgba(<?= $quick_queue_pending>10?'239,83,80':'255,255,255' ?>,<?= $quick_queue_pending>10?'.15':'.08' ?>);border-radius:10px;padding:14px;text-align:center;<?= $quick_queue_pending>10?'border:1px solid rgba(239,83,80,.4)':'' ?>">
      <div style="font-size:1.6rem;font-weight:900;<?= $quick_queue_pending>10?'color:#ff5252':'' ?>"><?= $quick_queue_pending ?></div>
      <div style="font-size:.7rem;opacity:.75">⚙️ مهام الصف</div>
    </div>
    <div style="background:rgba(255,255,255,.08);border-radius:10px;padding:14px;text-align:center">
      <div style="font-size:1.6rem;font-weight:900"><?= $d_pending_items ?></div>
      <div style="font-size:.7rem;opacity:.75">⏳ يحتاج مراجعة</div>
    </div>
  </div>
</div>

<!-- ── Quick Admin Actions ───────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:10px;margin-bottom:20px">
  <a href="?tab=subscriptions" style="background:#fff3e0;border:1.5px solid #ffcc80;border-radius:10px;padding:14px;text-align:center;text-decoration:none;color:#e65100;font-weight:700;font-size:.82rem">
    💳 طلبات الاشتراك<br><span style="font-size:1.1rem"><?= $stats['subs_pending'] ?></span>
  </a>
  <a href="?tab=providers" style="background:#f3e5f5;border:1.5px solid #ce93d8;border-radius:10px;padding:14px;text-align:center;text-decoration:none;color:#6a1b9a;font-weight:700;font-size:.82rem">
    🏅 طلبات المزودين<br><span style="font-size:1.1rem"><?= $stats['providers_pending'] ?></span>
  </a>
  <a href="?tab=services" style="background:#e8f5e9;border:1.5px solid #81c784;border-radius:10px;padding:14px;text-align:center;text-decoration:none;color:#2e7d32;font-weight:700;font-size:.82rem">
    🔧 الخدمات المعلّقة<br><span style="font-size:1.1rem"><?= $stats['services_pending'] ?></span>
  </a>
  <a href="?tab=inquiries" style="background:#e3f2fd;border:1.5px solid #90caf9;border-radius:10px;padding:14px;text-align:center;text-decoration:none;color:#1565c0;font-weight:700;font-size:.82rem">
    📧 رسائل التواصل<br><span style="font-size:1.1rem"><?= $stats['inquiries'] ?></span>
  </a>
</div>

<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:10px;margin-bottom:20px">
  <div style="background:linear-gradient(135deg,#073328,#0f5940);color:#fff;border-radius:12px;padding:18px;text-align:center">
    <div style="font-size:2rem;font-weight:900"><?= $stats['users'] ?></div>
    <div style="font-size:.75rem;opacity:.8">👤 إجمالي المستخدمين</div>
    <div style="font-size:.72rem;margin-top:4px;opacity:.6">+<?= $d_users_week ?> هذا الأسبوع</div>
  </div>
  <div style="background:linear-gradient(135deg,#1565c0,#1976d2);color:#fff;border-radius:12px;padding:18px;text-align:center">
    <div style="font-size:2rem;font-weight:900"><?= $d_active_subs ?></div>
    <div style="font-size:.75rem;opacity:.8">💳 مشتركون مدفوعون</div>
    <div style="font-size:.72rem;margin-top:4px;opacity:.6"><?= $d_active_subs>0?round($d_active_subs/$stats['users']*100).'%':'0%' ?> من الإجمالي</div>
  </div>
  <div style="background:linear-gradient(135deg,#e65100,#f57c00);color:#fff;border-radius:12px;padding:18px;text-align:center">
    <div style="font-size:2rem;font-weight:900"><?= number_format($d_revenue_month,0) ?></div>
    <div style="font-size:.75rem;opacity:.8">💰 إيراد هذا الشهر (SDG)</div>
  </div>
  <div style="background:<?= $d_pending_items>0?'linear-gradient(135deg,#c62828,#e53935)':'linear-gradient(135deg,#2e7d32,#43a047)' ?>;color:#fff;border-radius:12px;padding:18px;text-align:center">
    <div style="font-size:2rem;font-weight:900"><?= $d_pending_items ?></div>
    <div style="font-size:.75rem;opacity:.8"><?= $d_pending_items>0?'⚠️ طلبات معلقة':'✅ لا طلبات معلقة' ?></div>
  </div>
</div>

<?php if($d_pending_items>0): ?>
<div style="background:#fff3e0;border:1.5px solid #ffb74d;border-radius:10px;padding:14px;margin-bottom:16px">
  <strong>⚠️ يحتاج انتباهاً:</strong>
  <?php if($stats['providers_pending']>0): ?><a href="?tab=providers" style="color:#e65100;margin-left:12px">🏅 <?= $stats['providers_pending'] ?> مزود معلق</a><?php endif; ?>
  <?php if($stats['subs_pending']>0): ?><a href="?tab=subscriptions" style="color:#e65100;margin-left:12px">💳 <?= $stats['subs_pending'] ?> اشتراك معلق</a><?php endif; ?>
  <?php if(($stats['pharmacies_pending']??0)>0): ?><a href="?tab=pharmacies" style="color:#9c27b0;margin-left:12px">💊 <?= $stats['pharmacies_pending'] ?> صيدلية معلقة</a><?php endif; ?>
  <?php if(($stats['services_pending']??0)>0): ?><a href="?tab=services" style="color:#0097a7;margin-left:12px">🏘️ <?= $stats['services_pending'] ?> خدمة معلقة</a>
<?php elseif($tab==='reconciliation'): ?>
<div style="max-width:900px">
<h2 style="margin-bottom:20px;color:var(--g1)">⚖️ التسوية المحاسبية اليومية</h2>

<?php
// Load recent reconciliation results from audit_logs
$recon_results = [];
try {
    $rq = db()->query("SELECT action, data, created_at FROM audit_logs
                       WHERE action IN ('reconciliation.passed','reconciliation.failed')
                       ORDER BY id DESC LIMIT 10");
    $recon_results = $rq->fetchAll(PDO::FETCH_ASSOC);
} catch(Throwable $e) {}
?>

<div style="background:#fff;border:1px solid var(--border);border-radius:12px;margin-bottom:20px;overflow:hidden">
  <div style="padding:16px 20px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center">
    <strong>آخر نتائج التسوية</strong>
    <button onclick="runReconciliation()" style="background:var(--g1);color:#fff;padding:8px 18px;border-radius:8px;border:none;cursor:pointer;font-weight:700">▶ تشغيل التسوية</button>
  </div>
  <div id="recon-status" style="padding:12px 20px;background:#f0f9ff;border-bottom:1px solid #bae6fd;font-size:.85rem;color:#075985">
    ⏳ جاري تحميل نتائج التسوية...
  </div>
  <table style="width:100%;border-collapse:collapse;font-size:.85rem">
    <tr style="background:var(--sand);border-bottom:1px solid var(--border)">
      <th style="padding:10px 16px;text-align:right">التاريخ</th>
      <th style="padding:10px 16px">الحالة</th>
      <th style="padding:10px 16px">المجموع النظامي</th>
      <th style="padding:10px 16px">الـ Ledger</th>
      <th style="padding:10px 16px">المشاكل</th>
    </tr>
    <?php foreach($recon_results as $r):
      $d = json_decode($r['data'], true);
      $passed = $r['action'] === 'reconciliation.passed';
    ?>
    <tr style="border-bottom:1px solid var(--border)">
      <td style="padding:10px 16px"><?= date('d/m/Y H:i', strtotime($r['created_at'])) ?></td>
      <td style="padding:10px 16px">
        <span style="background:<?= $passed?'#D1FAE5':'#FEE2E2' ?>;color:<?= $passed?'#065F46':'#991B1B' ?>;padding:3px 10px;border-radius:20px;font-size:.78rem;font-weight:700">
          <?= $passed ? '✅ ناجحة' : '❌ فشلت' ?>
        </span>
      </td>
      <td style="padding:10px 16px"><?= number_format($d['system_total']??0,2) ?> SDG</td>
      <td style="padding:10px 16px"><?= ($d['ledger_balanced']??false) ? '✅ متوازن' : '❌ غير متوازن' ?></td>
      <td style="padding:10px 16px"><?= $d['mismatch_count']??0 ?></td>
    </tr>
    <?php endforeach; ?>
    <?php if(empty($recon_results)): ?>
    <tr><td colspan="5" style="padding:24px;text-align:center;color:var(--text2)">⏳ لا توجد نتائج بعد — شغّل أول تسوية</td></tr>
    <?php endif; ?>
  </table>
</div>
</div>

<script>
function runReconciliation() {
  const btn = document.querySelector('[onclick="runReconciliation()"]');
  const status = document.getElementById('recon-status');
  btn.disabled = true;
  btn.textContent = '⏳ جاري التسوية...';
  status.style.background = '#FEF3C7';
  status.style.color = '#92400E';
  status.textContent = '⏳ جاري تشغيل التسوية...';
  fetch('<?= SITE_URL ?>/api/reconcile/run.php', {
    method:'POST', credentials:'include',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({date: new Date().toISOString().split('T')[0]})
  }).then(r=>r.json()).then(data => {
    btn.disabled = false; btn.textContent = '▶ تشغيل التسوية';
    if (data.passed) {
      status.style.background='#D1FAE5'; status.style.color='#065F46';
      status.textContent = '✅ التسوية ناجحة — المجموع: ' + (data.system_total||0) + ' SDG';
    } else {
      status.style.background='#FEE2E2'; status.style.color='#991B1B';
      status.textContent = '❌ التسوية فشلت — ' + (data.mismatch_count||0) + ' مشكلة';
    }
    setTimeout(() => location.reload(), 2000);
  }).catch(()=>{btn.disabled=false;btn.textContent='▶ تشغيل التسوية';status.textContent='❌ خطأ في الاتصال';});
}
// Auto-load ledger balance
fetch('<?= SITE_URL ?>/api/financial/ledger_summary.php',{credentials:'include'}).then(r=>r.json()).then(d=>{
  const b = d.balance;
  const status = document.getElementById('recon-status');
  if (b && b.balanced) {
    status.style.background='#D1FAE5';status.style.color='#065F46';
    status.textContent = `✅ الـ Ledger متوازن: إجمالي المدين = ${parseFloat(b.total_debit).toLocaleString()} SDG`;
  } else if(b) {
    status.style.background='#FEE2E2';status.style.color='#991B1B';
    status.textContent = `❌ الـ Ledger غير متوازن! الفرق: ${b.difference} SDG`;
  }
}).catch(()=>{});
</script>

<?php elseif($tab==='settlement'): ?>
<div style="max-width:900px">
<h2 style="margin-bottom:20px;color:var(--g1)">💸 صرف المزودين (Settlement)</h2>

<?php
$earnings = [];
$settledTotal = 0;
$pendingTotal = 0;
try {
    $eq = db()->query(
        "SELECT pe.*, u.name, u.email, u.provider_bank_account, u.provider_bank_name
         FROM provider_earnings pe JOIN users u ON u.id=pe.provider_id
         WHERE pe.status='pending' AND pe.net_sdg > 0
         ORDER BY pe.created_at DESC LIMIT 50"
    );
    $earnings = $eq->fetchAll(PDO::FETCH_ASSOC);
    $pendingTotal = array_sum(array_column($earnings, 'net_sdg'));
    $settled = db()->query("SELECT COALESCE(SUM(net_sdg),0) FROM provider_earnings WHERE status='settled'")->fetchColumn();
    $settledTotal = (float)$settled;
} catch(Throwable $e) { $dbErr = $e->getMessage(); }

// Check if reconciliation passed today
$reconPassed = false;
try {
    $rc = db()->prepare("SELECT COUNT(*) FROM audit_logs WHERE action='reconciliation.passed' AND DATE(created_at)=CURDATE()");
    $rc->execute();
    $reconPassed = (int)$rc->fetchColumn() > 0;
} catch(Throwable $e){}
?>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px">
  <div style="background:<?= $reconPassed?'#D1FAE5':'#FEF3C7' ?>;border-radius:12px;padding:16px">
    <p style="font-size:.78rem;color:<?= $reconPassed?'#065F46':'#92400E' ?>;font-weight:700">حالة التسوية اليوم</p>
    <p style="font-size:1.3rem;font-weight:900;color:<?= $reconPassed?'#065F46':'#92400E' ?>"><?= $reconPassed?'✅ مكتملة — الصرف مسموح':'⚠️ غير مكتملة — الصرف محجوب' ?></p>
  </div>
  <div style="background:#fff;border:1px solid var(--border);border-radius:12px;padding:16px">
    <p style="font-size:.78rem;color:var(--text2)">إجمالي المعلق</p>
    <p style="font-size:1.5rem;font-weight:900;color:var(--g1)"><?= number_format($pendingTotal,2) ?> SDG</p>
  </div>
</div>

<?php if(!$reconPassed): ?>
<div style="background:#FEF3C7;border:1px solid #FCD34D;border-radius:10px;padding:14px;margin-bottom:16px;font-size:.88rem;color:#92400E">
  ⚠️ يجب إتمام التسوية المحاسبية قبل الصرف. <a href="?tab=reconciliation" style="color:#92400E;font-weight:700">اذهب للتسوية →</a>
</div>
<?php endif; ?>

<?php if(!empty($earnings)): ?>
<div style="background:#fff;border:1px solid var(--border);border-radius:12px;overflow:hidden;margin-bottom:16px">
  <div style="padding:14px 18px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center">
    <strong>مزودون بأرباح معلقة (<?= count($earnings) ?>)</strong>
    <button onclick="processBatch()" <?= !$reconPassed?'disabled':'' ?> style="background:<?= $reconPassed?'var(--g1)':'#ccc' ?>;color:#fff;padding:8px 18px;border-radius:8px;border:none;cursor:pointer;font-weight:700">
      💸 صرف الجميع (<?= number_format($pendingTotal,2) ?> SDG)
    </button>
  </div>
  <table style="width:100%;border-collapse:collapse;font-size:.85rem">
    <tr style="background:var(--sand)"><th style="padding:10px 16px;text-align:right">المزوّد</th><th>الصافي</th><th>حساب البنك</th><th>الإجراء</th></tr>
    <?php foreach($earnings as $e): ?>
    <tr style="border-bottom:1px solid var(--sand2)">
      <td style="padding:10px 16px"><?= htmlspecialchars($e['name']??'—') ?></td>
      <td style="padding:10px 16px;font-weight:700;color:var(--success)"><?= number_format($e['net_sdg'],2) ?> SDG</td>
      <td style="padding:10px 16px;font-family:monospace;font-size:.78rem"><?= htmlspecialchars($e['provider_bank_account']??'غير محدد') ?></td>
      <td style="padding:10px 16px">
        <button onclick="processOne(<?= $e['id'] ?>)" <?= !$reconPassed?'disabled':'' ?> style="background:<?= $reconPassed?'var(--g2)':'#ccc' ?>;color:#fff;padding:4px 12px;border-radius:6px;border:none;cursor:pointer;font-size:.78rem">
          صرف
        </button>
      </td>
    </tr>
    <?php endforeach; ?>
  </table>
</div>
<?php else: ?>
<div style="text-align:center;padding:40px;background:#fff;border-radius:12px;color:var(--text2)">
  💡 لا توجد أرباح معلقة للصرف حالياً
</div>
<?php endif; ?>
</div>
<script>
function processBatch() {
  if (!confirm('تأكيد صرف جميع المزودين?')) return;
  fetch('<?= SITE_URL ?>/api/payout/process.php', {
    method:'POST',credentials:'include',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({date: new Date(Date.now()-86400000).toISOString().split('T')[0]})
  }).then(r=>r.json()).then(d=>{
    alert(d.success ? `✅ تم الصرف: ${d.paid||0} مزودين` : '❌ ' + (d.error||d.reason||'خطأ'));
    if(d.success) location.reload();
  });
}
function processOne(id) { alert('صرف فردي — قريباً'); }
</script>

<?php elseif($tab==='ledger_view'): ?>
<div style="max-width:900px">
<h2 style="margin-bottom:20px;color:var(--g1)">📒 دفتر الحسابات (Double-Entry Ledger)</h2>

<?php
$accounts = []; $recent = []; $balance = [];
try {
    $ledgerData = [];
    $aq = db()->query("SELECT a.code, a.name, a.type,
        COALESCE(SUM(l.debit),0) AS total_debit,
        COALESCE(SUM(l.credit),0) AS total_credit,
        COALESCE(SUM(l.credit-l.debit),0) AS net
        FROM accounts a LEFT JOIN ledger l ON l.account_id=a.id
        GROUP BY a.id ORDER BY a.code");
    $accounts = $aq->fetchAll(PDO::FETCH_ASSOC);
    $totalDeb = array_sum(array_column($accounts,'total_debit'));
    $totalCred = array_sum(array_column($accounts,'total_credit'));
    $balanced = abs($totalDeb-$totalCred) < 0.01;
    $rq = db()->query("SELECT l.*, a.code, a.name as account_name
        FROM ledger l JOIN accounts a ON a.id=l.account_id
        ORDER BY l.id DESC LIMIT 20");
    $recent = $rq->fetchAll(PDO::FETCH_ASSOC);
} catch(Throwable $e) { $dbErr = $e->getMessage(); }
?>

<?php if(isset($balanced)): ?>
<div style="background:<?= $balanced?'#D1FAE5':'#FEE2E2' ?>;border-radius:12px;padding:20px;margin-bottom:20px;display:flex;justify-content:space-between;align-items:center">
  <div>
    <p style="font-size:.82rem;font-weight:700;color:<?= $balanced?'#065F46':'#991B1B' ?>">التوازن المحاسبي</p>
    <p style="font-size:1.8rem;font-weight:900;color:<?= $balanced?'#065F46':'#991B1B' ?>"><?= $balanced?'✅ متوازن':'❌ غير متوازن' ?></p>
  </div>
  <div style="text-align:right">
    <p style="font-size:.78rem;color:<?= $balanced?'#065F46':'#991B1B' ?>">إجمالي مدين: <?= number_format($totalDeb,2) ?> SDG</p>
    <p style="font-size:.78rem;color:<?= $balanced?'#065F46':'#991B1B' ?>">إجمالي دائن: <?= number_format($totalCred,2) ?> SDG</p>
    <p style="font-size:.78rem;color:<?= $balanced?'#065F46':'#991B1B' ?>">الفرق: <?= number_format(abs($totalDeb-$totalCred),2) ?> SDG</p>
  </div>
</div>

<div style="background:#fff;border:1px solid var(--border);border-radius:12px;overflow:hidden;margin-bottom:20px">
  <div style="padding:14px 18px;border-bottom:1px solid var(--border);font-weight:700">دليل الحسابات (Chart of Accounts)</div>
  <table style="width:100%;border-collapse:collapse;font-size:.85rem">
    <tr style="background:var(--sand)"><th style="padding:10px 16px;text-align:right">الكود</th><th>الحساب</th><th>النوع</th><th>مدين</th><th>دائن</th><th>الصافي</th></tr>
    <?php foreach($accounts as $a): ?>
    <tr style="border-bottom:1px solid var(--sand2)">
      <td style="padding:10px 16px;font-family:monospace;font-weight:700"><?= $a['code'] ?></td>
      <td style="padding:10px 16px"><?= htmlspecialchars($a['name']) ?></td>
      <td style="padding:10px 16px"><span style="font-size:.75rem;background:var(--sand);padding:2px 6px;border-radius:4px"><?= $a['type'] ?></span></td>
      <td style="padding:10px 16px;color:var(--danger);font-weight:600"><?= number_format($a['total_debit'],2) ?></td>
      <td style="padding:10px 16px;color:var(--success);font-weight:600"><?= number_format($a['total_credit'],2) ?></td>
      <td style="padding:10px 16px;font-weight:700"><?= number_format($a['net'],2) ?></td>
    </tr>
    <?php endforeach; ?>
  </table>
</div>

<div style="background:#fff;border:1px solid var(--border);border-radius:12px;overflow:hidden">
  <div style="padding:14px 18px;border-bottom:1px solid var(--border);font-weight:700">آخر 20 قيد</div>
  <table style="width:100%;border-collapse:collapse;font-size:.82rem">
    <tr style="background:var(--sand)"><th style="padding:8px 14px;text-align:right">التاريخ</th><th>الحساب</th><th>النوع</th><th>مدين</th><th>دائن</th><th>البيان</th></tr>
    <?php foreach($recent as $r): ?>
    <tr style="border-bottom:1px solid var(--sand2)">
      <td style="padding:8px 14px;white-space:nowrap"><?= date('d/m H:i', strtotime($r['created_at'])) ?></td>
      <td style="padding:8px 14px;font-family:monospace"><?= $r['code'] ?></td>
      <td style="padding:8px 14px"><?= $r['reference_type'] ?></td>
      <td style="padding:8px 14px;color:var(--danger)"><?= $r['debit']>0 ? number_format($r['debit'],2) : '—' ?></td>
      <td style="padding:8px 14px;color:var(--success)"><?= $r['credit']>0 ? number_format($r['credit'],2) : '—' ?></td>
      <td style="padding:8px 14px;font-size:.75rem;color:var(--text2)"><?= htmlspecialchars(mb_substr($r['description']??'',0,30)) ?></td>
    </tr>
    <?php endforeach; ?>
    <?php if(empty($recent)): ?>
    <tr><td colspan="6" style="padding:20px;text-align:center;color:var(--text2)">⏳ لا قيود بعد</td></tr>
    <?php endif; ?>
  </table>
</div>
<?php endif; ?>
</div>

<?php endif; ?>
</div>
<?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
  <div>
    <div class="sec-head"><h3>👤 آخر المسجّلين</h3></div>
    <table><tr><th>الاسم</th><th>البريد</th><th>الاشتراك</th><th>التاريخ</th></tr>
    <?php foreach($d_recent_users as $r): ?>
    <tr><td><strong><?= htmlspecialchars($r['name']) ?></strong></td><td style="font-size:.72rem"><?= htmlspecialchars($r['email']) ?></td>
    <td><span class="badge <?= $r['subscription_tier']==='paid'?'b-paid':'b-free' ?>"><?= $r['subscription_tier'] ?></span></td>
    <td style="font-size:.72rem"><?= substr($r['created_at'],0,10) ?></td></tr>
    <?php endforeach; ?>
    </table>
  </div>
  <div>
    <div class="sec-head"><h3>📋 آخر الإجراءات</h3></div>
    <?php if($d_recent_actions): ?>
    <table><tr><th>الإجراء</th><th>النوع</th><th>الوقت</th></tr>
    <?php foreach($d_recent_actions as $a): ?>
    <tr><td style="font-size:.75rem"><?= htmlspecialchars($a['action']) ?></td>
    <td style="font-size:.72rem;color:#666"><?= htmlspecialchars($a['target_type']??'') ?></td>
    <td style="font-size:.7rem"><?= substr($a['created_at'],0,16) ?></td></tr>
    <?php endforeach; ?>
    </table>
    <?php else: ?>
    <div style="text-align:center;padding:20px;color:#999;font-size:.82rem">لا توجد إجراءات بعد</div>
    <?php endif; ?>
  </div>
</div>

<?php
// ══════════════════════════════════════════════════════
// الصيدليات
// ══════════════════════════════════════════════════════
elseif($tab==='pharmacies'):
$ph_status = in_array($_GET['phs']??'pending',['pending','active','suspended'])?$_GET['phs']:'pending';
$pharmacies_list=[]; try { $pharmacies_list=db()->query("SELECT * FROM pharmacies WHERE status='$ph_status' ORDER BY id DESC LIMIT 200")->fetchAll(); } catch(Throwable $ignored){ echo '<div style="background:#fff3e0;padding:12px;border-radius:8px;margin-bottom:12px">⚠️ شغّل migrate.sql أولاً</div>'; }
$ph_counts=[]; foreach(['pending','active','suspended'] as $s) { try { $ph_counts[$s]=(int)db()->query("SELECT COUNT(*) FROM pharmacies WHERE status='$s'")->fetchColumn(); } catch(Throwable $ignored){ $ph_counts[$s]=0; } }
?>
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap">
  <?php foreach(['pending'=>'⏳ معلقة','active'=>'✅ نشطة','suspended'=>'❌ موقوفة'] as $s=>$l): ?>
  <a href="?tab=pharmacies&phs=<?= $s ?>" class="btn <?= $ph_status===$s?'btn-g':'btn-b' ?>"><?= $l ?> (<?= $ph_counts[$s]??0 ?>)</a>
  <?php endforeach; ?>
</div>

<div class="form-box">
  <h3>➕ إضافة صيدلية مباشرة</h3>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="admin_add_pharmacy"><input type="hidden" name="tab" value="pharmacies">
    <div class="form-row">
      <input type="text" name="ph_name" placeholder="اسم الصيدلية *" required style="flex:2">
      <input type="text" name="ph_license" placeholder="رقم الترخيص *" required style="flex:1">
      <input type="tel" name="ph_phone" placeholder="الهاتف *" required style="flex:1">
    </div>
    <div class="form-row">
      <input type="text" name="ph_state" placeholder="الولاية" style="flex:1">
      <input type="text" name="ph_city" placeholder="المدينة" style="flex:1">
      <input type="text" name="ph_address" placeholder="العنوان" style="flex:2">
      <button class="btn btn-g">إضافة</button>
    </div>
  </form>
</div>

<?php if($pharmacies_list): ?>
<table>
<tr><th>ID</th><th>الاسم</th><th>الترخيص</th><th>الولاية/المدينة</th><th>الهاتف</th><th>التاريخ</th><th>إجراء</th></tr>
<?php foreach($pharmacies_list as $p): ?>
<tr>
  <td><?= $p['id'] ?></td>
  <td><strong><?= htmlspecialchars($p['name']) ?></strong><?= $p['verified']?' ✅':'' ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($p['license_no']??'—') ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars(($p['state']??'').' / '.($p['city']??'')) ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($p['phone']??'') ?></td>
  <td style="font-size:.7rem"><?= substr($p['created_at'],0,10) ?></td>
  <td>
    <?php if($p['status']==='pending'): ?>
    <div class="actions">
      <form method="POST"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="approve_pharmacy"><input type="hidden" name="pharm_id" value="<?= $p['id'] ?>"><input type="hidden" name="tab" value="pharmacies"><button class="btn btn-g">✅ تفعيل</button></form>
      <form method="POST" onsubmit="return confirm('رفض الصيدلية؟')">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="reject_pharmacy"><input type="hidden" name="pharm_id" value="<?= $p['id'] ?>"><input type="hidden" name="tab" value="pharmacies">
        <input type="text" name="reject_reason" placeholder="سبب الرفض" style="padding:4px;border:1px solid #ddd;border-radius:5px;font-size:.72rem">
        <button class="btn btn-r">❌</button>
      </form>
    </div>
    <?php else: ?><span class="badge <?= $p['status']==='active'?'b-active':'b-removed' ?>"><?= $p['status'] ?></span><?php endif; ?>
  </td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<div style="text-align:center;padding:28px;color:#999">لا توجد صيدليات</div>
<?php endif; ?>

<?php
// ══════════════════════════════════════════════════════
// دليل الخدمات
// ══════════════════════════════════════════════════════
elseif($tab==='services'):
$svc_status = in_array($_GET['svcs']??'pending',['pending','active','inactive'])?$_GET['svcs']:'pending';
$svc_cat    = trim($_GET['svc_cat'] ?? '');
$svcs=[]; try {
  // FIX: prepared statement — no injection possible
  if ($svc_cat !== '') {
    $st = db()->prepare("SELECT s.*,u.name AS provider_name FROM neighborhood_services s LEFT JOIN users u ON u.id=s.provider_user_id WHERE s.status=? AND s.category=? ORDER BY s.id DESC LIMIT 200");
    $st->execute([$svc_status, $svc_cat]);
  } else {
    $st = db()->prepare("SELECT s.*,u.name AS provider_name FROM neighborhood_services s LEFT JOIN users u ON u.id=s.provider_user_id WHERE s.status=? ORDER BY s.id DESC LIMIT 200");
    $st->execute([$svc_status]);
  }
  $svcs = $st->fetchAll();
} catch(Throwable $ignored){ echo '<div style="background:#fff3e0;padding:12px;border-radius:8px;margin-bottom:12px">⚠️ شغّل migrate.sql أولاً</div>'; $svcs=[]; }
?>
<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:16px">
  <?php foreach(['pending'=>'⏳ معلقة','active'=>'✅ نشطة','inactive'=>'❌ غير نشطة'] as $s=>$l): ?>
  <a href="?tab=services&svcs=<?= $s ?>" class="btn <?= $svc_status===$s?'btn-g':'btn-b' ?>"><?= $l ?></a>
  <?php endforeach; ?>
  <?php foreach(['health'=>'🏥','education'=>'📚','food'=>'🍽️','services'=>'🔧','social'=>'🤝'] as $c=>$ic): ?>
  <a href="?tab=services&svcs=<?= $svc_status ?>&svc_cat=<?= $c ?>" class="btn <?= $svc_cat===$c?'btn-s':'btn-b' ?>"><?= $ic ?> <?= $c ?></a>
  <?php endforeach; ?>
</div>

<div class="form-box">
  <h3>➕ إضافة خدمة للدليل</h3>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="admin_add_service"><input type="hidden" name="tab" value="services">
    <div class="form-row">
      <input type="text" name="sv_name" placeholder="اسم الخدمة *" required style="flex:2">
      <select name="sv_cat" style="flex:1;padding:7px;border:1.5px solid #ddd;border-radius:7px">
        <option value="health">🏥 صحة</option><option value="education">📚 تعليم</option>
        <option value="food">🍽️ طعام</option><option value="services">🔧 خدمات</option>
        <option value="social">🤝 اجتماعي</option><option value="transport">🚌 مواصلات</option>
      </select>
      <input type="tel" name="sv_phone" placeholder="الهاتف" style="flex:1">
    </div>
    <div class="form-row">
      <input type="text" name="sv_state" placeholder="الولاية" style="flex:1">
      <input type="text" name="sv_city" placeholder="المدينة" style="flex:1">
      <input type="text" name="sv_address" placeholder="العنوان" style="flex:2">
      <button class="btn btn-g">إضافة</button>
    </div>
  </form>
</div>

<?php if($svcs): ?>
<table><tr><th>الاسم</th><th>الفئة</th><th>الولاية/المدينة</th><th>المزود</th><th>التقييم</th><th>إجراء</th></tr>
<?php foreach($svcs as $s): ?>
<tr>
  <td><strong><?= htmlspecialchars($s['name']) ?></strong><?= $s['is_verified']?' ✅':'' ?></td>
  <td><span class="badge b-active"><?= $s['category'] ?></span></td>
  <td style="font-size:.72rem"><?= htmlspecialchars(($s['state']??'').'/'.$s['city']??'') ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($s['provider_name']??'—') ?></td>
  <td>⭐ <?= $s['rating_avg'] ?> (<?= $s['rating_count'] ?>)</td>
  <td>
    <?php if($s['status']==='pending'): ?>
    <div class="actions">
      <form method="POST"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="approve_service"><input type="hidden" name="svc_id" value="<?= $s['id'] ?>"><input type="hidden" name="tab" value="services"><button class="btn btn-g">✅ نشر</button></form>
      <form method="POST"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="reject_service"><input type="hidden" name="svc_id" value="<?= $s['id'] ?>"><input type="hidden" name="tab" value="services"><button class="btn btn-r">❌</button></form>
    </div>
    <?php else: ?><span class="badge <?= $s['status']==='active'?'b-active':'b-removed' ?>"><?= $s['status'] ?></span><?php endif; ?>
  </td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?><div style="text-align:center;padding:28px;color:#999">لا توجد خدمات</div><?php endif; ?>

<?php
// ══════════════════════════════════════════════════════
// الفعاليات
// ══════════════════════════════════════════════════════
elseif($tab==='events'):
$evt_status = in_array($_GET['evts']??'upcoming',['upcoming','active','completed','cancelled'])?$_GET['evts']:'upcoming';
$evts=[]; try { $evts=db()->query("SELECT e.*,u.name AS organizer FROM community_events e JOIN users u ON u.id=e.organizer_id WHERE e.status='$evt_status' ORDER BY e.event_date ASC LIMIT 100")->fetchAll(); } catch(Throwable $ignored){ echo '<div style="background:#fff3e0;padding:12px;border-radius:8px;margin-bottom:12px">⚠️ شغّل migrate.sql أولاً</div>'; $evts=[]; }
?>
<div style="display:flex;gap:6px;margin-bottom:16px">
  <?php foreach(['upcoming'=>'⏳ قادمة','active'=>'✅ نشطة','completed'=>'🏁 منتهية','cancelled'=>'❌ ملغاة'] as $s=>$l): ?>
  <a href="?tab=events&evts=<?= $s ?>" class="btn <?= $evt_status===$s?'btn-g':'btn-b' ?>"><?= $l ?></a>
  <?php endforeach; ?>
</div>
<?php if($evts): ?>
<table><tr><th>العنوان</th><th>الفئة</th><th>التاريخ</th><th>المكان</th><th>المنظّم</th><th>المشاركون</th><th>إجراء</th></tr>
<?php foreach($evts as $e):
$part_cnt=0; try { $part_st=db()->prepare('SELECT COUNT(*) FROM event_participants WHERE event_id=?'); $part_st->execute([$e['id']]); $part_cnt=(int)$part_st->fetchColumn(); } catch(Throwable $ignored){}
?>
<tr>
  <td><strong><?= htmlspecialchars($e['title']) ?></strong></td>
  <td><span class="badge b-active"><?= $e['category'] ?></span></td>
  <td style="font-size:.72rem"><?= substr($e['event_date'],0,16) ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($e['location']??'—') ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($e['organizer']) ?></td>
  <td><strong><?= $part_cnt ?></strong><?= $e['max_participants']?' / '.$e['max_participants']:'' ?></td>
  <td>
    <?php if($e['status']==='upcoming'): ?>
    <div class="actions">
      <form method="POST"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="approve_event"><input type="hidden" name="evt_id" value="<?= $e['id'] ?>"><input type="hidden" name="tab" value="events"><button class="btn btn-g">✅ نشر</button></form>
      <form method="POST"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="reject_event"><input type="hidden" name="evt_id" value="<?= $e['id'] ?>"><input type="hidden" name="tab" value="events"><button class="btn btn-r">❌</button></form>
    </div>
    <?php else: ?><span class="badge b-active"><?= $e['status'] ?></span><?php endif; ?>
  </td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?><div style="text-align:center;padding:28px;color:#999">لا توجد فعاليات</div><?php endif; ?>

<?php
// ══════════════════════════════════════════════════════
// العقود
// ══════════════════════════════════════════════════════
elseif($tab==='contracts'):
$contracts_list=[]; try { $contracts_list=db()->query("SELECT c.*,u.name AS party_uname FROM contracts c LEFT JOIN users u ON u.id=c.party_user_id ORDER BY c.id DESC LIMIT 100")->fetchAll(); } catch(Throwable $ignored){ echo '<div style="background:#fff3e0;padding:12px;border-radius:8px;margin-bottom:12px">⚠️ شغّل migrate.sql أولاً</div>'; }
$tpls=[]; try { $tpls=db()->query('SELECT * FROM contract_templates ORDER BY type')->fetchAll(); } catch(Throwable $ignored){}
?>
<div class="form-box">
  <h3>📄 توليد عقد جديد من قالب</h3>
  <form method="POST" id="contract-form">
    <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="admin_generate_contract"><input type="hidden" name="tab" value="contracts">
    <div class="form-row">
      <select name="tpl_id" id="tpl_select" onchange="loadContractVars(this.value)" style="flex:1;padding:8px;border:1.5px solid #ddd;border-radius:7px">
        <option value="">— اختر قالباً —</option>
        <?php foreach($tpls as $t): ?><option value="<?= $t['id'] ?>" data-vars="<?= htmlspecialchars($t['variables']??'[]') ?>"><?= htmlspecialchars($t['name']) ?></option><?php endforeach; ?>
      </select>
      <input type="text" name="party_name" placeholder="اسم الطرف الثاني *" style="flex:1">
      <input type="email" name="party_email" placeholder="البريد الإلكتروني" style="flex:1">
    </div>
    <div id="contract-vars" style="display:flex;gap:8px;flex-wrap:wrap;margin-top:8px"></div>
    <button class="btn btn-g" style="margin-top:8px">🤖 توليد العقد بـ AI</button>
  </form>
</div>
<script>
function loadContractVars(tpl_id){
  const sel=document.getElementById('tpl_select');
  const opt=sel.options[sel.selectedIndex];
  const vars=JSON.parse(opt.dataset.vars||'[]');
  const container=document.getElementById('contract-vars');
  container.innerHTML='';
  vars.forEach(v=>{
    container.innerHTML+=`<div><label style="font-size:.75rem;display:block;color:#555">${v.label}</label><input type="text" name="variables[${v.key}]" placeholder="${v.label}" style="padding:6px;border:1.5px solid #ddd;border-radius:6px;font-size:.82rem"></div>`;
  });
}
</script>

<?php if($contracts_list): ?>
<div class="sec-head" style="margin-top:16px"><h3>قائمة العقود</h3></div>
<table><tr><th>العنوان</th><th>النوع</th><th>الطرف الثاني</th><th>الحالة</th><th>AI ملخص</th><th>التاريخ</th><th>إجراء</th></tr>
<?php foreach($contracts_list as $c):
  $status_badge=['draft'=>'b-pending','sent'=>'b-active','signed'=>'b-paid-inv','cancelled'=>'b-removed','expired'=>'b-removed','negotiating'=>'b-health'];
?>
<tr>
  <td><strong><?= htmlspecialchars($c['title']) ?></strong></td>
  <td><span class="badge b-active"><?= $c['type'] ?></span></td>
  <td style="font-size:.78rem"><?= htmlspecialchars($c['party_name']??$c['party_uname']??'—') ?></td>
  <td><span class="badge <?= $status_badge[$c['status']]??'b-pending' ?>"><?= $c['status'] ?></span></td>
  <td style="font-size:.72rem;max-width:200px;color:#555"><?= htmlspecialchars(mb_substr($c['ai_summary']??'—',0,80)) ?></td>
  <td style="font-size:.7rem"><?= substr($c['created_at'],0,10) ?></td>
  <td>
    <details><summary class="btn btn-b" style="cursor:pointer;list-style:none;padding:4px 10px;font-size:.72rem">عرض</summary>
    <div style="background:#f9f9f9;padding:10px;border-radius:6px;font-size:.75rem;white-space:pre-wrap;max-height:200px;overflow-y:auto;margin-top:6px"><?= htmlspecialchars($c['content']) ?></div>
    <?php if($c['status']!=='signed'): ?>
    <form method="POST" style="margin-top:6px"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="sign_contract"><input type="hidden" name="contract_id" value="<?= $c['id'] ?>"><input type="hidden" name="tab" value="contracts"><button class="btn btn-g">✅ توقيع</button></form>
    <?php endif; ?>
    </details>
  </td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?><div style="text-align:center;padding:28px;color:#999">لا توجد عقود</div><?php endif; ?>

<?php
// ══════════════════════════════════════════════════════
// CRM
// ══════════════════════════════════════════════════════
elseif($tab==='crm'):
$crm_uid = (int)($_GET['uid']??0);
if($crm_uid) {
  $crm_user=db()->prepare('SELECT * FROM users WHERE id=? LIMIT 1'); $crm_user->execute([$crm_uid]); $cu=$crm_user->fetch();
  $crm_notes=[]; try { $ns=db()->prepare('SELECT cn.*,s.name AS staff_name FROM crm_notes cn LEFT JOIN staff_members s ON s.id=cn.staff_id WHERE cn.user_id=? ORDER BY cn.id DESC'); $ns->execute([$crm_uid]); $crm_notes=$ns->fetchAll(); } catch(Throwable $ignored){}
  $crm_timeline=[]; try { $tl=db()->prepare('SELECT * FROM crm_timeline WHERE user_id=? ORDER BY id DESC LIMIT 30'); $tl->execute([$crm_uid]); $crm_timeline=$tl->fetchAll(); } catch(Throwable $ignored){}
  $crm_subs=[]; try { $sb=db()->prepare('SELECT * FROM subscription_requests WHERE user_id=? ORDER BY id DESC'); $sb->execute([$crm_uid]); $crm_subs=$sb->fetchAll(); } catch(Throwable $ignored){}
  if($cu):
  ?>
  <a href="?tab=crm" class="btn btn-b" style="margin-bottom:12px;display:inline-block">← العودة</a>
  <div style="display:grid;grid-template-columns:300px 1fr;gap:16px">
    <div>
      <div class="form-box">
        <h3>👤 ملف المستخدم</h3>
        <div style="font-size:.82rem;line-height:2">
          <div><strong>الاسم:</strong> <?= htmlspecialchars($cu['name']) ?></div>
          <div><strong>البريد:</strong> <?= htmlspecialchars($cu['email']) ?></div>
          <div><strong>الاشتراك:</strong> <span class="badge <?= $cu['subscription_tier']==='paid'?'b-paid':'b-free' ?>"><?= $cu['subscription_tier'] ?></span></div>
          <div><strong>الولاية:</strong> <?= htmlspecialchars($cu['state']??'—') ?></div>
          <div><strong>المسار:</strong> <?= htmlspecialchars($cu['learning_track']??'—') ?></div>
          <div><strong>الرتبة:</strong> <?= htmlspecialchars($cu['rank_title']??'—') ?></div>
          <div><strong>نوع المستخدم:</strong> <?= htmlspecialchars($cu['user_type']??'user') ?></div>
          <div><strong>نقاط التعلم:</strong> <?= $cu['points_learn'] ?></div>
          <div><strong>تاريخ التسجيل:</strong> <?= substr($cu['created_at'],0,10) ?></div>
        </div>
      </div>
      <div class="form-box">
        <h3>🔧 إجراءات سريعة</h3>
        <form method="POST" style="margin-bottom:6px"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="admin_add_provider"><input type="hidden" name="user_id" value="<?= $crm_uid ?>"><input type="hidden" name="tab" value="crm"><input type="hidden" name="uid" value="<?= $crm_uid ?>">
          <select name="ptype" style="width:100%;padding:6px;border:1.5px solid #ddd;border-radius:6px;font-size:.78rem;margin-bottom:4px"><option value="">— نوع المزود —</option><option value="teacher">👨‍🏫 معلم</option><option value="doctor">👨‍⚕️ طبيب</option><option value="pharmacist">💊 صيدلاني</option><option value="service_provider">🔧 مقدم خدمة</option><option value="academic">🎓 أكاديمي</option></select>
          <input type="text" name="specialty" placeholder="التخصص" style="width:100%;padding:6px;border:1.5px solid #ddd;border-radius:6px;font-size:.78rem;margin-bottom:4px">
          <input type="text" name="bio" placeholder="نبذة مختصرة" style="width:100%;padding:6px;border:1.5px solid #ddd;border-radius:6px;font-size:.78rem;margin-bottom:4px">
          <button class="btn btn-g" style="width:100%">🏅 تفعيل كمزود</button>
        </form>
        <form method="POST"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="reset_user_pw"><input type="hidden" name="uid" value="<?= $crm_uid ?>"><input type="hidden" name="tab" value="crm"><input type="hidden" name="user_uid" value="<?= $crm_uid ?>">
          <input type="text" name="new_pw" placeholder="كلمة مرور جديدة" style="width:100%;padding:6px;border:1.5px solid #ddd;border-radius:6px;font-size:.78rem;margin-bottom:4px">
          <button class="btn btn-o" style="width:100%">🔑 تغيير كلمة المرور</button>
        </form>
      </div>
    </div>
    <div>
      <div class="form-box">
        <h3>📝 إضافة ملاحظة CRM</h3>
        <form method="POST">
          <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="add_crm_note"><input type="hidden" name="tab" value="crm"><input type="hidden" name="uid" value="<?= $crm_uid ?>"><input type="hidden" name="crm_uid" value="<?= $crm_uid ?>">
          <div class="form-row">
            <select name="crm_type" style="padding:7px;border:1.5px solid #ddd;border-radius:7px"><option value="general">عام</option><option value="financial">مالي</option><option value="support">دعم</option><option value="provider">مزود</option><option value="complaint">شكوى</option></select>
            <textarea name="crm_note" placeholder="الملاحظة..." rows="2" style="flex:3;padding:7px;border:1.5px solid #ddd;border-radius:7px;font-family:Arial;resize:vertical"></textarea>
            <button class="btn btn-g">إضافة</button>
          </div>
        </form>
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
        <div>
          <div class="sec-head"><h3>📋 الملاحظات</h3></div>
          <?php if($crm_notes): ?>
          <?php foreach($crm_notes as $n): ?>
          <div style="background:#fff;padding:10px;border-radius:8px;margin-bottom:8px;border-right:3px solid <?= ['general'=>'#1565c0','financial'=>'#e65100','support'=>'#2e7d32','provider'=>'#6a1b9a','complaint'=>'#c62828'][$n['type']]??'#ddd' ?>">
            <div style="font-size:.82rem"><?= htmlspecialchars($n['note']) ?></div>
            <div style="font-size:.7rem;color:#999;margin-top:4px"><?= htmlspecialchars($n['staff_name']??'الأدمن') ?> · <?= substr($n['created_at'],0,10) ?></div>
          </div>
          <?php endforeach; ?>
          <?php else: ?><div style="color:#999;font-size:.82rem">لا توجد ملاحظات</div><?php endif; ?>
        </div>
        <div>
          <div class="sec-head"><h3>📅 سجل التفاعل</h3></div>
          <?php if($crm_timeline): ?>
          <?php foreach($crm_timeline as $t): ?>
          <div style="background:#f9f9f9;padding:8px;border-radius:6px;margin-bottom:6px;font-size:.75rem">
            <strong><?= htmlspecialchars($t['event_type']) ?></strong>
            <span style="color:#999;float:left"><?= substr($t['created_at'],0,10) ?></span>
          </div>
          <?php endforeach; ?>
          <?php else: ?><div style="color:#999;font-size:.82rem">لا توجد سجلات</div><?php endif; ?>
          <?php if($crm_subs): ?>
          <div class="sec-head" style="margin-top:12px"><h3>💳 الاشتراكات</h3></div>
          <?php foreach($crm_subs as $s): ?><div style="font-size:.75rem;background:#fff;padding:6px;border-radius:6px;margin-bottom:4px"><span class="badge <?= $s['status']==='approved'?'b-active':'b-pending' ?>"><?= $s['status'] ?></span> <?= number_format($s['amount'],0) ?> SDG · <?= substr($s['created_at'],0,10) ?></div><?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
  <?php else: ?><div style="text-align:center;padding:28px;color:#999">المستخدم غير موجود</div><?php endif; ?>
<?php } else { // CRM list
  $crm_search = trim($_GET['q']??'');
  $crm_users=[];
  if($crm_search) {
    $cs=db()->prepare("SELECT id,name,email,subscription_tier,state,user_type,provider_verified,created_at FROM users WHERE name LIKE ? OR email LIKE ? ORDER BY id DESC LIMIT 50");
    $cs->execute(["%$crm_search%","%$crm_search%"]); $crm_users=$cs->fetchAll();
  } else {
    $crm_users=db()->query("SELECT id,name,email,subscription_tier,state,user_type,provider_verified,created_at FROM users ORDER BY id DESC LIMIT 100")->fetchAll();
  }
  ?>
  <div class="form-box">
    <form method="GET"><input type="hidden" name="tab" value="crm">
      <div class="form-row"><input type="text" name="q" value="<?= htmlspecialchars($crm_search) ?>" placeholder="ابحث باسم المستخدم أو بريده..." style="flex:3"><button class="btn btn-g">بحث</button></div>
    </form>
  </div>
  <table><tr><th>الاسم</th><th>البريد</th><th>الاشتراك</th><th>النوع</th><th>الولاية</th><th>التاريخ</th><th>ملف CRM</th></tr>
  <?php foreach($crm_users as $u_crm): ?>
  <tr>
    <td><strong><?= htmlspecialchars($u_crm['name']) ?></strong><?= $u_crm['provider_verified']?' ✅':'' ?></td>
    <td style="font-size:.72rem"><?= htmlspecialchars($u_crm['email']) ?></td>
    <td><span class="badge <?= $u_crm['subscription_tier']==='paid'?'b-paid':'b-free' ?>"><?= $u_crm['subscription_tier'] ?></span></td>
    <td style="font-size:.72rem"><?= htmlspecialchars($u_crm['user_type']??'user') ?></td>
    <td style="font-size:.72rem"><?= htmlspecialchars($u_crm['state']??'—') ?></td>
    <td style="font-size:.7rem"><?= substr($u_crm['created_at'],0,10) ?></td>
    <td><a href="?tab=crm&uid=<?= $u_crm['id'] ?>" class="btn btn-b">📋 فتح الملف</a></td>
  </tr>
  <?php endforeach; ?>
  </table>
<?php } ?>
<?php endif; ?>


<?php
if($tab==='providers'):
// ══════════════════════════════════════════════════════
// تبويب مزودو الخدمات
// ══════════════════════════════════════════════════════
$prov_status = $_GET['ps'] ?? 'pending';
$allowed_ps = ['pending','approved','rejected','needs_docs'];
$prov_status = in_array($prov_status, $allowed_ps) ? $prov_status : 'pending';
$apps = []; try { $apps = db()->query("SELECT pa.*, u.name AS uname, u.email AS uemail FROM provider_applications pa JOIN users u ON u.id=pa.user_id WHERE pa.status='$prov_status' ORDER BY pa.id DESC LIMIT 100")->fetchAll(); } catch(Throwable $ignored) { echo '<div style="background:#fff3e0;padding:12px;border-radius:8px;margin-bottom:16px">⚠️ شغّل migrate.sql أولاً</div>'; $apps=[]; }
$prov_counts = []; try { foreach(['pending','approved','rejected','needs_docs'] as $s) $prov_counts[$s] = (int)db()->query("SELECT COUNT(*) FROM provider_applications WHERE status='$s'")->fetchColumn(); } catch(Throwable $ignored) {}
?>
<div class="sec-head">
  <h3>طلبات مزودي الخدمات</h3>
  <div style="display:flex;gap:6px;flex-wrap:wrap">
    <?php foreach(['pending'=>'⏳ معلق','approved'=>'✅ موافق','rejected'=>'❌ مرفوض','needs_docs'=>'📄 يحتاج مستندات'] as $s=>$l): ?>
    <a href="?tab=providers&ps=<?= $s ?>" class="btn <?= $prov_status===$s?'btn-g':'btn-b' ?>"><?= $l ?> <?= isset($prov_counts[$s])&&$prov_counts[$s]>0?"({$prov_counts[$s]})":'' ?></a>
    <?php endforeach; ?>
  </div>
</div>
<?php if($apps): ?>
<table>
<tr><th>ID</th><th>المتقدم</th><th>النوع</th><th>التخصص</th><th>الجهة المرخصة</th><th>الترخيص</th><th>الشهادة</th><th>التاريخ</th><th>إجراء</th></tr>
<?php foreach($apps as $a): ?>
<?php $type_ar=['teacher'=>'👨‍🏫 معلم','doctor'=>'👨‍⚕️ طبيب','pharmacist'=>'💊 صيدلاني','service_provider'=>'🔧 مقدم خدمة','academic'=>'🎓 أكاديمي','hospital'=>'🏥 مستشفى']; ?>
<tr>
  <td><?= $a['id'] ?></td>
  <td><strong><?= htmlspecialchars($a['uname']) ?></strong><div style="font-size:.7rem;color:#999"><?= htmlspecialchars($a['uemail']) ?></div></td>
  <td><span class="badge b-active"><?= $type_ar[$a['type']]??$a['type'] ?></span></td>
  <td><?= htmlspecialchars(mb_substr($a['specialty'],0,40)) ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($a['issuing_authority']??'—') ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($a['license_number']??'—') ?></td>
  <td><?= $a['credentials_url']?'<a href="'.htmlspecialchars($a['credentials_url']).'" target="_blank" class="btn btn-b" style="font-size:.7rem">📄 عرض</a>':'—' ?></td>
  <td style="font-size:.7rem"><?= substr($a['created_at'],0,10) ?></td>
  <td>
    <?php if($a['status']==='pending'||$a['status']==='needs_docs'): ?>
    <div class="actions" style="flex-direction:column;gap:6px">
      <form method="POST"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="approve_provider"><input type="hidden" name="app_id" value="<?= $a['id'] ?>"><input type="hidden" name="tab" value="providers"><input type="hidden" name="prov_type" value="<?= $a['type'] ?>"><button class="btn btn-g">✅ موافقة</button></form>
      <form method="POST">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="needs_docs_provider"><input type="hidden" name="app_id" value="<?= $a['id'] ?>"><input type="hidden" name="tab" value="providers">
        <input type="text" name="docs_msg" placeholder="المستندات المطلوبة..." style="width:100%;padding:4px 8px;border:1px solid #ddd;border-radius:5px;font-size:.72rem;margin-bottom:3px">
        <button class="btn btn-o" style="width:100%">📄 طلب مستندات</button>
      </form>
      <form method="POST" onsubmit="return confirm('رفض الطلب؟')">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="reject_provider"><input type="hidden" name="app_id" value="<?= $a['id'] ?>"><input type="hidden" name="tab" value="providers">
        <input type="text" name="reject_reason" placeholder="سبب الرفض..." style="width:100%;padding:4px 8px;border:1px solid #ddd;border-radius:5px;font-size:.72rem;margin-bottom:3px">
        <button class="btn btn-r" style="width:100%">❌ رفض</button>
      </form>
    </div>
    <?php elseif($a['status']==='approved'): ?>
    <span class="badge b-active">✅ موافق عليه</span>
    <?php else: ?>
    <span class="badge b-removed">❌ مرفوض</span>
    <?php endif; ?>
  </td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<div style="text-align:center;padding:32px;color:#999">لا توجد طلبات <?= $prov_status === 'pending' ? 'معلقة' : '' ?></div>
<?php endif; ?>

<?php
// ══════════════════════════════════════════════════════
// تبويب طلبات الاشتراك
// ══════════════════════════════════════════════════════
elseif($tab==='subscriptions'):
$sub_status = $_GET['ss'] ?? 'pending';
$sub_status = in_array($sub_status, ['pending','approved','rejected']) ? $sub_status : 'pending';
$subs = []; try { $subs = db()->query("SELECT sr.*, u.name AS uname, u.email AS uemail, i.invoice_no FROM subscription_requests sr JOIN users u ON u.id=sr.user_id LEFT JOIN invoices i ON i.id=sr.invoice_id WHERE sr.status='$sub_status' ORDER BY sr.id DESC LIMIT 100")->fetchAll(); } catch(Throwable $ignored) { echo '<div style="background:#fff3e0;padding:12px;border-radius:8px;margin-bottom:16px">⚠️ شغّل migrate.sql أولاً</div>'; $subs=[]; }
?>
<div class="sec-head">
  <h3>طلبات الاشتراك المدفوع</h3>
  <div style="display:flex;gap:6px">
    <?php foreach(['pending'=>'⏳ معلق','approved'=>'✅ مُفعَّل','rejected'=>'❌ مرفوض'] as $s=>$l): ?>
    <a href="?tab=subscriptions&ss=<?= $s ?>" class="btn <?= $sub_status===$s?'btn-g':'btn-b' ?>"><?= $l ?></a>
    <?php endforeach; ?>
  </div>
</div>
<div style="background:#f0faf4;border-radius:10px;padding:12px 16px;margin-bottom:16px;font-size:.82rem">
  💳 بيانات الاستلام: <strong>بنك الخرطوم</strong> — حساب <strong dir="ltr">1821425</strong> — حامد مختار
</div>
<?php if($subs): ?>
<table>
<tr><th>ID</th><th>المستخدم</th><th>المبلغ</th><th>المدة</th><th>رقم الفاتورة</th><th>المرجع</th><th>الإيصال</th><th>التاريخ</th><th>إجراء</th></tr>
<?php foreach($subs as $r): ?>
<tr>
  <td><?= $r['id'] ?></td>
  <td><strong><?= htmlspecialchars($r['uname']) ?></strong><div style="font-size:.7rem;color:#999"><?= htmlspecialchars($r['uemail']) ?></div></td>
  <td><strong><?= number_format($r['amount'],0) ?></strong> <?= $r['currency'] ?></td>
  <td><?= $r['duration_months'] ?> شهر</td>
  <td dir="ltr" style="font-size:.75rem"><?= htmlspecialchars($r['invoice_no']??'—') ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($r['bank_ref']??'—') ?></td>
  <td><?= $r['receipt_url']?'<a href="'.htmlspecialchars($r['receipt_url']).'" target="_blank" class="btn btn-b" style="font-size:.7rem">🖼️ عرض</a>':'—' ?></td>
  <td style="font-size:.7rem"><?= substr($r['created_at'],0,16) ?></td>
  <td>
    <?php if($r['status']==='pending'): ?>
    <div class="actions" style="flex-direction:column;gap:6px">
      <form method="POST">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="approve_subscription"><input type="hidden" name="sub_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="subscriptions">
        <input type="text" name="pay_ref" placeholder="مرجع التأكيد..." style="width:100%;padding:4px 8px;border:1px solid #ddd;border-radius:5px;font-size:.72rem;margin-bottom:3px">
        <button class="btn btn-g" style="width:100%">✅ تفعيل الاشتراك</button>
      </form>
      <form method="POST" onsubmit="return confirm('رفض الطلب؟')">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="reject_subscription"><input type="hidden" name="sub_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="subscriptions">
        <input type="text" name="reject_reason" placeholder="سبب الرفض..." style="width:100%;padding:4px 8px;border:1px solid #ddd;border-radius:5px;font-size:.72rem;margin-bottom:3px">
        <button class="btn btn-r" style="width:100%">❌ رفض</button>
      </form>
    </div>
    <?php elseif($r['status']==='approved'): ?>
    <div><span class="badge b-active">✅ مُفعَّل</span><div style="font-size:.7rem;color:#666;margin-top:4px">ينتهي: <?= $r['expires_at']?substr($r['expires_at'],0,10):'—' ?></div></div>
    <?php else: ?>
    <span class="badge b-removed">❌ مرفوض</span>
    <?php endif; ?>
  </td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<div style="text-align:center;padding:32px;color:#999">لا توجد طلبات <?= $sub_status === 'pending'?'معلقة':'' ?></div>
<?php endif; ?>


<?php
// ── FIX 3: Plan Pricing Editor ────────────────────────────────
$plans_data = [];
try {
    $plans_data = db()->query("SELECT * FROM subscription_plans ORDER BY price_sdg ASC")->fetchAll();
} catch(Throwable $e) { $plans_data = []; }
?>
<div style="background:#f0faf4;border:2px solid #073328;border-radius:12px;padding:20px;margin-top:24px">
  <h3 style="color:#073328;margin-bottom:16px">⚙️ إدارة الخطط والأسعار (تأثير فوري على Gateway)</h3>
  <div style="font-size:.78rem;color:#555;margin-bottom:12px">
    ⚡ التغييرات تُطبَّق فوراً — Gateway يقرأ الحدود من DB مباشرة (لا cache)
  </div>
  <?php foreach($plans_data as $plan): ?>
  <div style="background:#fff;border-radius:10px;padding:16px;margin-bottom:12px;border:1px solid #ddd">
    <form method="POST">
      <input type="hidden" name="csrf" value="<?= $csrf ?>">
      <input type="hidden" name="action" value="update_plan">
      <input type="hidden" name="tab" value="subscriptions">
      <input type="hidden" name="plan_key" value="<?= htmlspecialchars($plan['plan_key']) ?>">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;flex-wrap:wrap;gap:8px">
        <div>
          <strong style="font-size:1rem"><?= htmlspecialchars($plan['name_ar']) ?></strong>
          <span style="background:<?= $plan['is_active']?'#e8f5e9':'#fbe9e7' ?>;color:<?= $plan['is_active']?'#2e7d32':'#c62828' ?>;padding:2px 8px;border-radius:8px;font-size:.75rem;margin-right:8px"><?= $plan['is_active']?'✅ نشطة':'⏸️ موقوفة' ?></span>
        </div>
        <div style="display:flex;align-items:center;gap:8px">
          <label style="font-size:.82rem"><input type="checkbox" name="is_active" value="1" <?= $plan['is_active']?'checked':'' ?>> تفعيل</label>
        </div>
      </div>
      <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px">
        <div>
          <label style="font-size:.78rem;color:#555">السعر (SDG)</label>
          <input type="number" name="price_sdg" value="<?= $plan['price_sdg'] ?>" min="0" style="width:100%;padding:7px;border:1.5px solid #ddd;border-radius:6px">
        </div>
        <div>
          <label style="font-size:.78rem;color:#555">حد AI/يوم</label>
          <input type="number" name="ai_requests_day" value="<?= $plan['ai_requests_day'] ?>" min="1" max="1000" style="width:100%;padding:7px;border:1.5px solid #ddd;border-radius:6px">
        </div>
        <div>
          <label style="font-size:.78rem;color:#555">حجوزات/يوم</label>
          <input type="number" name="booking_per_day" value="<?= $plan['booking_per_day'] ?>" min="1" max="100" style="width:100%;padding:7px;border:1.5px solid #ddd;border-radius:6px">
        </div>
        <div>
          <label style="font-size:.78rem;color:#555">وثائق BDE/شهر</label>
          <input type="number" name="bde_docs_month" value="<?= $plan['bde_docs_month'] ?>" min="0" max="999" style="width:100%;padding:7px;border:1.5px solid #ddd;border-radius:6px">
        </div>
        <div>
          <label style="font-size:.78rem;color:#555">خصم %</label>
          <input type="number" name="discount_pct" value="<?= $plan['discount_pct'] ?>" min="0" max="100" step="0.5" style="width:100%;padding:7px;border:1.5px solid #ddd;border-radius:6px">
        </div>
      </div>
      <div style="margin-top:12px">
        <button type="submit" style="background:#073328;color:#fff;border:none;padding:8px 20px;border-radius:8px;cursor:pointer;font-family:inherit">💾 حفظ التعديلات</button>
        <span style="font-size:.75rem;color:#888;margin-right:12px">آخر تحديث: <?= $plan['updated_at'] ?? 'غير محدد' ?></span>
      </div>
    </form>
  </div>
  <?php endforeach; ?>
  <?php if(empty($plans_data)): ?>
  <p style="color:#999;text-align:center;padding:16px">لا توجد خطط — شغّل database_complete.sql أولاً</p>
  <?php endif; ?>
</div>

<?php
// ══════════════════════════════════════════════════════
// تبويب دروس المعلمين
// ══════════════════════════════════════════════════════
elseif($tab==='lesson_subs'):
$ls_status = $_GET['lss'] ?? 'pending';
$ls_status = in_array($ls_status, ['pending','approved','rejected','needs_revision']) ? $ls_status : 'pending';
$lsubs = []; try { $lsubs = db()->query("SELECT ls.*, u.name AS teacher_name FROM lesson_submissions ls JOIN users u ON u.id=ls.user_id WHERE ls.status='$ls_status' ORDER BY ls.id DESC LIMIT 100")->fetchAll(); } catch(Throwable $ignored) { echo '<div style="background:#fff3e0;padding:12px;border-radius:8px;margin-bottom:16px">⚠️ شغّل migrate.sql أولاً</div>'; $lsubs=[]; }
?>
<div class="sec-head">
  <h3>دروس المعلمين قيد المراجعة</h3>
  <div style="display:flex;gap:6px">
    <?php foreach(['pending'=>'⏳ قيد المراجعة','approved'=>'✅ منشور','rejected'=>'❌ مرفوض','needs_revision'=>'📝 يحتاج تعديل'] as $s=>$l): ?>
    <a href="?tab=lesson_subs&lss=<?= $s ?>" class="btn <?= $ls_status===$s?'btn-g':'btn-b' ?>"><?= $l ?></a>
    <?php endforeach; ?>
  </div>
</div>
<?php if($lsubs): ?>
<table>
<tr><th>ID</th><th>المعلم</th><th>المسار</th><th>العنوان</th><th>تقييم AI</th><th>التاريخ</th><th>إجراء</th></tr>
<?php foreach($lsubs as $r): ?>
<tr>
  <td><?= $r['id'] ?></td>
  <td><?= htmlspecialchars($r['teacher_name']) ?></td>
  <td><span class="badge b-active"><?= $r['track'] ?></span></td>
  <td>
    <strong><?= htmlspecialchars(mb_substr($r['title'],0,60)) ?></strong>
    <details style="margin-top:4px"><summary style="font-size:.72rem;cursor:pointer;color:var(--g1)">عرض المحتوى</summary>
    <div style="font-size:.75rem;color:#555;padding:6px;background:#f9f9f9;border-radius:6px;max-height:100px;overflow-y:auto;margin-top:4px"><?= htmlspecialchars(mb_substr($r['content'],0,300)) ?>...</div>
    <?php if($r['ai_feedback']): ?><div style="font-size:.72rem;color:var(--g2);margin-top:4px">🤖 <?= htmlspecialchars($r['ai_feedback']) ?></div><?php endif; ?>
    </details>
  </td>
  <td>
    <div style="font-size:.85rem;font-weight:700;color:<?= $r['ai_score']>=70?'#2e7d32':($r['ai_score']>=50?'#f57f17':'#c62828') ?>"><?= $r['ai_score'] ?>/100</div>
  </td>
  <td style="font-size:.7rem"><?= substr($r['created_at'],0,10) ?></td>
  <td>
    <?php if($r['status']==='pending'): ?>
    <div class="actions" style="flex-direction:column;gap:5px">
      <form method="POST"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="approve_lesson_sub"><input type="hidden" name="sub_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="lesson_subs"><button class="btn btn-g">✅ نشر</button></form>
      <form method="POST" onsubmit="return confirm('رفض الدرس؟')">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="reject_lesson_sub"><input type="hidden" name="sub_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="lesson_subs">
        <input type="text" name="reject_reason" placeholder="سبب الرفض..." style="width:100%;padding:4px 8px;border:1px solid #ddd;border-radius:5px;font-size:.72rem;margin-bottom:3px">
        <button class="btn btn-r" style="width:100%">❌ رفض</button>
      </form>
    </div>
    <?php elseif($r['status']==='approved'): ?>
    <span class="badge b-active">✅ منشور</span>
    <?php else: ?>
    <span class="badge b-removed">❌ مرفوض</span>
    <?php endif; ?>
  </td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<div style="text-align:center;padding:32px;color:#999">لا توجد دروس قيد المراجعة</div>
<?php endif; ?>

<?php
elseif($tab==='users'):
$search = trim($_GET['q'] ?? '');
$where  = $search ? "WHERE u.name LIKE ? OR u.email LIKE ? OR u.state LIKE ?" : '';
$params = $search ? ["%$search%","%$search%","%$search%"] : [];
$users_st = db()->prepare("SELECT u.*, n.name AS hood_name FROM users u LEFT JOIN neighborhoods n ON n.id=u.neighborhood_id $where ORDER BY u.id DESC LIMIT 300");
$users_st->execute($params);
$users = $users_st->fetchAll();
?>
<div class="sec-head">
  <h3>المستخدمون (<?= count($users) ?>)</h3>
  <div style="display:flex;gap:6px;flex-wrap:wrap">
    <form method="GET" style="display:flex;gap:6px">
      <input type="hidden" name="tab" value="users">
      <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="بحث باسم أو بريد..." style="padding:5px 10px;border:1.5px solid #ddd;border-radius:7px;font-size:.8rem">
      <button class="btn btn-b">🔍</button>
    </form>
    <form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="export_users"><button class="btn btn-g">⬇ CSV</button></form>
  </div>
</div>
<table>
<tr><th>ID</th><th>الاسم</th><th>البريد</th><th>الاشتراك</th><th>الولاية/المدينة</th><th>الحي</th><th>المسار</th><th>الرتبة</th><th>النقاط</th><th>الإنجاز</th><th>التسجيل</th><th>إجراءات</th></tr>
<?php foreach($users as $r): ?>
<tr>
  <td><?= $r['id'] ?></td>
  <td><strong><?= htmlspecialchars($r['name']) ?></strong></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($r['email']) ?></td>
  <td><span class="badge b-<?= $r['subscription_tier'] ?>"><?= $r['subscription_tier']==='paid'?'💳 مدفوع':'🆓 مجاني' ?></span></td>
  <td><?= htmlspecialchars(($r['state']??'').' / '.($r['city']??'')) ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($r['hood_name']??$r['neighborhood']??'—') ?></td>
  <td style="font-size:.72rem"><?= $r['learning_track']??'—' ?></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($r['rank_title']??'—') ?></td>
  <td style="font-size:.72rem">📚<?= (int)$r['points_learn'] ?> 🛒<?= (int)$r['points_trade'] ?> 📡<?= (int)$r['points_community'] ?> 👨‍👩‍👧<?= (int)$r['points_family'] ?></td>
  <td><?= $r['onboarding_done']?'✅':'⏳' ?></td>
  <td style="font-size:.7rem"><?= substr($r['created_at'],0,10) ?></td>
  <td>
    <div class="actions">
      <form method="POST" class="inline-form">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="toggle_tier">
        <input type="hidden" name="uid" value="<?= $r['id'] ?>"><input type="hidden" name="tier" value="<?= $r['subscription_tier'] ?>"><input type="hidden" name="tab" value="users">
        <button class="btn <?= $r['subscription_tier']==='paid'?'btn-o':'btn-b' ?>"><?= $r['subscription_tier']==='paid'?'⬇مجاني':'⬆مدفوع' ?></button>
      </form>
      <form method="POST" class="inline-form">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="reset_user_pw">
        <input type="hidden" name="uid" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="users">
        <input type="text" name="new_pw" placeholder="كلمة مرور" style="width:110px;padding:4px 8px;border:1.5px solid #ddd;border-radius:6px;font-size:.75rem">
        <button class="btn btn-r">🔑</button>
      </form>
      <?php if(in_array($role,['super_admin','admin'])): ?>
      <form method="POST" class="inline-form" onsubmit="return confirm('حذف المستخدم نهائياً؟')">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="delete_user">
        <input type="hidden" name="uid" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="users">
        <button class="btn btn-r">🗑</button>
      </form>
      <?php endif; ?>
    </div>
    <!-- تفاصيل إضافية -->
    <details style="margin-top:6px"><summary>تفاصيل</summary>
      <div class="detail-row" style="margin-top:6px">
        <span>المستوى التعليمي</span><strong><?= htmlspecialchars($r['education_level']??'—') ?></strong>
        <span>الفئة العمرية</span><strong><?= htmlspecialchars($r['age_group']??'—') ?></strong>
        <span>الهدف</span><strong style="font-size:.72rem"><?= htmlspecialchars(mb_substr($r['goals']??'—',0,60)) ?></strong>
        <span>FCM Token</span><strong style="font-size:.65rem"><?= $r['fcm_token']?'✅ موجود':'❌ غير موجود' ?></strong>
      </div>
    </details>
  </td>
</tr>
<?php endforeach; ?>
</table>

<?php
// ══════════════════════════════════════════════════════
// المنشورات
// ══════════════════════════════════════════════════════
elseif($tab==='posts'):
$pf_raw = $_GET['pf'] ?? 'active';
$pf = in_array($pf_raw, ['active','removed','resolved','all']) ? $pf_raw : 'active';
$pq = ''; $pq_params = [];
if($pf !== 'all'){ $pq = 'WHERE p.status = ?'; $pq_params = [$pf]; }
$posts_st = db()->prepare("SELECT p.*, u.name AS author, u.email AS author_email FROM pulse_posts p JOIN users u ON u.id=p.user_id $pq ORDER BY p.id DESC LIMIT 300");
$posts_st->execute($pq_params);
$posts = $posts_st->fetchAll();
// أجلب الأحياء للنشر من الأدمن
$hoods = []; try { $hoods = db()->query('SELECT id, name, city FROM neighborhoods ORDER BY city, name LIMIT 200')->fetchAll(); } catch(Throwable $ignored) {}
?>
<div class="form-box">
  <h3>📢 إضافة إعلان رسمي من المنصة</h3>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="add_admin_post"><input type="hidden" name="tab" value="posts">
    <div class="form-row">
      <select name="type" style="min-width:130px"><option value="announcement">إعلان</option><option value="news">أخبار</option><option value="urgent">عاجل 🆘</option><option value="health">صحي 💊</option><option value="initiative">مبادرة</option></select>
      <select name="neighborhood_id" style="min-width:150px"><option value="0">— جميع الأحياء —</option><?php foreach($hoods as $h) echo "<option value='{$h['id']}'>{$h['name']} ({$h['city']})</option>"; ?></select>
    </div>
    <textarea name="content" placeholder="محتوى الإعلان..." rows="2" style="width:100%;margin-bottom:8px"></textarea>
    <button class="btn btn-g">📤 نشر</button>
  </form>
</div>
<div class="sec-head">
  <h3>منشورات نبض الحي (<?= count($posts) ?>)</h3>
  <div style="display:flex;gap:6px">
    <?php foreach(['all'=>'الكل','active'=>'نشط','removed'=>'محذوف','resolved'=>'مغلق'] as $s=>$l): ?>
    <a href="?tab=posts&pf=<?= $s ?>" class="btn <?= $pf===$s?'btn-g':'btn-b' ?>"><?= $l ?></a>
    <?php endforeach; ?>
  </div>
</div>
<table>
<tr><th>ID</th><th>المحتوى</th><th>النوع</th><th>الكاتب</th><th>AI ملاحظة</th><th>الحالة</th><th>التاريخ</th><th>إجراءات</th></tr>
<?php foreach($posts as $r): ?>
<tr>
  <td><?= $r['id'] ?></td>
  <td style="max-width:200px"><?= htmlspecialchars(mb_substr($r['content'],0,80)) ?>...</td>
  <td><span class="badge b-<?= $r['type'] ?>"><?= $r['type'] ?></span><?= $r['is_urgent']?' 🆘':'' ?></td>
  <td><?= htmlspecialchars($r['author']) ?></td>
  <td style="font-size:.7rem;color:#555;max-width:150px"><?= htmlspecialchars(mb_substr($r['ai_health_note']??'',0,50)) ?></td>
  <td><span class="badge b-<?= $r['status'] ?>"><?= $r['status'] ?></span></td>
  <td style="font-size:.7rem"><?= substr($r['created_at'],0,16) ?></td>
  <td><div class="actions">
    <?php if($r['status']!=='active'): ?><form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="approve_post"><input type="hidden" name="post_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="posts"><button class="btn btn-g">✅</button></form><?php endif; ?>
    <?php if($r['status']==='active'): ?><form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="resolve_post"><input type="hidden" name="post_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="posts"><button class="btn btn-p">🔒</button></form><?php endif; ?>
    <?php if($r['status']!=='removed'): ?><form method="POST" class="inline-form" onsubmit="return confirm('حذف؟')"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="remove_post"><input type="hidden" name="post_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="posts"><button class="btn btn-r">🗑</button></form><?php endif; ?>
  </div></td>
</tr>
<?php endforeach; ?>
</table>

<?php
// ══════════════════════════════════════════════════════
// السوق
// ══════════════════════════════════════════════════════
elseif($tab==='items'):
$isf_raw = $_GET['isf'] ?? 'active';
$isf = in_array($isf_raw, ['active','removed','sold','expired']) ? $isf_raw : 'active';
try {
    $items = db()->query("SELECT i.*, u.name AS seller, u.email AS seller_email FROM marketplace_items i JOIN users u ON u.id=i.seller_id WHERE i.status='$isf' ORDER BY i.id DESC LIMIT 300")->fetchAll();
} catch(Throwable $e) {
    $items = [];
    $msg = '⚠️ جدول marketplace_items: '.htmlspecialchars($e->getMessage());
}
?>
<div class="sec-head">
  <h3>السوق — <?= $isf ?> (<?= count($items) ?>)</h3>
  <div style="display:flex;gap:6px">
    <?php foreach(['active'=>'نشط','removed'=>'محذوف','sold'=>'مباع','expired'=>'منتهي'] as $s=>$l): ?>
    <a href="?tab=items&isf=<?= $s ?>" class="btn <?= $isf===$s?'btn-g':'btn-b' ?>"><?= $l ?></a>
    <?php endforeach; ?>
  </div>
</div>
<table>
<tr><th>ID</th><th>الصورة</th><th>العنوان</th><th>الفئة</th><th>السعر</th><th>البائع</th><th>❤️ اهتمام</th><th>👁 مشاهدة</th><th>انتهاء</th><th>إجراءات</th></tr>
<?php foreach($items as $r): ?>
<tr>
  <td><?= $r['id'] ?></td>
  <td><?php if($r['image_url']): ?><img src="<?= htmlspecialchars($r['image_url']) ?>" style="width:44px;height:44px;object-fit:cover;border-radius:6px"><?php else: ?>—<?php endif; ?></td>
  <td style="max-width:180px"><strong><?= htmlspecialchars(mb_substr($r['title'],0,55)) ?></strong></td>
  <td><span class="badge b-active"><?= $r['category'] ?></span></td>
  <td><?= $r['price']?number_format($r['price'],0).' '.$r['currency']:'تفاوض' ?></td>
  <td><span title="<?= htmlspecialchars($r['seller_email']) ?>"><?= htmlspecialchars($r['seller']) ?></span></td>
  <td><?= $r['interest_count'] ?></td>
  <td><?= $r['views_count'] ?></td>
  <td style="font-size:.7rem"><?= $r['expires_at']?substr($r['expires_at'],0,10):'—' ?></td>
  <td><div class="actions">
    <?php if($r['status']==='active'): ?>
      <form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="mark_sold"><input type="hidden" name="item_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="items"><button class="btn btn-s">✅ مباع</button></form>
      <form method="POST" class="inline-form" onsubmit="return confirm('حذف؟')"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="remove_item"><input type="hidden" name="item_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="items"><button class="btn btn-r">🗑</button></form>
    <?php else: ?>
      <form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="restore_item"><input type="hidden" name="item_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="items"><button class="btn btn-g">↩</button></form>
    <?php endif; ?>
  </div></td>
</tr>
<?php endforeach; ?>
</table>

<?php
// ══════════════════════════════════════════════════════
// الأكاديمية
// ══════════════════════════════════════════════════════
elseif($tab==='lessons'):
?>
<div class="form-box">
  <h3>➕ إضافة درس جديد (مع اختبار)</h3>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="add_lesson"><input type="hidden" name="tab" value="lessons">
    <div class="form-row">
      <select name="track" style="min-width:120px"><option value="foundation">🌱 الأساس</option><option value="growth">🚀 النمو</option><option value="leadership">🏆 القيادة</option></select>
      <input type="text" name="title" placeholder="عنوان الدرس *" style="flex:2;min-width:180px">
      <input type="number" name="order" placeholder="ترتيب" style="width:70px" value="1">
      <label style="display:flex;align-items:center;gap:4px;font-size:.8rem;white-space:nowrap"><input type="checkbox" name="is_premium" value="1"> مدفوع فقط</label>
    </div>
    <textarea name="content" placeholder="محتوى الدرس التعليمي *" rows="3" style="width:100%;margin-bottom:8px"></textarea>
    <hr style="margin:10px 0;border-color:#eee">
    <p style="font-size:.78rem;color:#666;margin-bottom:8px">📝 الاختبار (اختياري — اتركه فارغاً إذا لم يكن هناك اختبار)</p>
    <div class="form-row">
      <input type="text" name="quiz_q" placeholder="سؤال الاختبار" style="flex:2;min-width:200px">
      <select name="quiz_ans" style="min-width:80px"><option value="">الإجابة الصحيحة</option><option value="A">A</option><option value="B">B</option><option value="C">C</option><option value="D">D</option></select>
    </div>
    <div class="form-row">
      <input type="text" name="opt_a" placeholder="أ — الخيار الأول" style="flex:1">
      <input type="text" name="opt_b" placeholder="ب — الخيار الثاني" style="flex:1">
    </div>
    <div class="form-row">
      <input type="text" name="opt_c" placeholder="ج — الخيار الثالث" style="flex:1">
      <input type="text" name="opt_d" placeholder="د — الخيار الرابع" style="flex:1">
    </div>
    <button class="btn btn-g" style="margin-top:6px">إضافة الدرس</button>
  </form>
</div>
<table>
<tr><th>ID</th><th>المسار</th><th>العنوان</th><th>الترتيب</th><th>مدفوع</th><th>اختبار</th><th>إجراء</th></tr>
<?php foreach(db()->query("SELECT id,track,title,order_index,is_premium,quiz_question FROM lessons ORDER BY track,order_index") as $r): ?>
<tr>
  <td><?= $r['id'] ?></td>
  <td><span class="badge b-active"><?= $r['track'] ?></span></td>
  <td><?= htmlspecialchars($r['title']) ?></td>
  <td><?= $r['order_index'] ?></td>
  <td><?= $r['is_premium']?'💳':'🆓' ?></td>
  <td><?= $r['quiz_question']?'✅ نعم':'❌ لا' ?></td>
  <td><form method="POST" class="inline-form" onsubmit="return confirm('حذف الدرس؟')"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="delete_lesson"><input type="hidden" name="lesson_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="lessons"><button class="btn btn-r">🗑</button></form></td>
</tr>
<?php endforeach; ?>
</table>

<?php
// ══════════════════════════════════════════════════════
// الأحياء والمناطق
// ══════════════════════════════════════════════════════
elseif($tab==='neighborhoods'):
$hoods = db()->query("SELECT n.*, COUNT(u.id) AS residents FROM neighborhoods n LEFT JOIN users u ON u.neighborhood_id=n.id GROUP BY n.id ORDER BY n.state, n.city, n.name")->fetchAll();
?>
<div class="form-box">
  <h3>➕ إضافة حي جديد</h3>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="add_neighborhood"><input type="hidden" name="tab" value="neighborhoods">
    <div class="form-row">
      <input type="text" name="state" placeholder="الولاية *" style="flex:1">
      <input type="text" name="city" placeholder="المدينة *" style="flex:1">
      <input type="text" name="name" placeholder="اسم الحي *" style="flex:1">
      <button class="btn btn-g">إضافة</button>
    </div>
  </form>
</div>
<div class="sec-head"><h3>الأحياء والمناطق (<?= count($hoods) ?>)</h3></div>
<table>
<tr><th>ID</th><th>الحي</th><th>المدينة</th><th>الولاية</th><th>عدد السكان</th><th>تاريخ الإنشاء</th><th>إجراء</th></tr>
<?php foreach($hoods as $r): ?>
<tr>
  <td><?= $r['id'] ?></td>
  <td><strong><?= htmlspecialchars($r['name']) ?></strong></td>
  <td><?= htmlspecialchars($r['city']) ?></td>
  <td><?= htmlspecialchars($r['state']) ?></td>
  <td><?= $r['residents'] ?> مستخدم</td>
  <td style="font-size:.72rem"><?= substr($r['created_at'],0,10) ?></td>
  <td><?php if($r['residents']==0): ?><form method="POST" class="inline-form" onsubmit="return confirm('حذف الحي؟')"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="delete_neighborhood"><input type="hidden" name="nid" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="neighborhoods"><button class="btn btn-r">🗑</button></form><?php else: ?><span style="color:#999;font-size:.72rem">لا يمكن (به سكان)</span><?php endif; ?></td>
</tr>
<?php endforeach; ?>
</table>

<?php
// ══════════════════════════════════════════════════════
// الفواتير
// ══════════════════════════════════════════════════════
elseif($tab==='invoices'):
$inv_filter_raw = $_GET['invf'] ?? 'all';
$inv_filter = in_array($inv_filter_raw, ['all','pending','paid','cancelled','refunded']) ? $inv_filter_raw : 'all';
$inv_where = ''; $inv_params = [];
if($inv_filter !== 'all'){ $inv_where = 'WHERE i.status = ?'; $inv_params = [$inv_filter]; }
try {
$inv_st = db()->prepare("SELECT i.*, u.name AS client_name, u.email AS client_email FROM invoices i LEFT JOIN users u ON u.id=i.user_id $inv_where ORDER BY i.id DESC LIMIT 200");
$inv_st->execute($inv_params);
$invoices = $inv_st->fetchAll();
} catch(Throwable $e) { $invoices = []; echo '<div style="background:#fff3e0;padding:12px;border-radius:8px;margin-bottom:16px">⚠️ شغّل migrate.sql أولاً لإنشاء جدول الفواتير</div>'; }
?>
<div class="form-box">
  <h3>🧾 إنشاء فاتورة جديدة</h3>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="add_invoice"><input type="hidden" name="tab" value="invoices">
    <div class="form-row">
      <input type="number" name="inv_uid" placeholder="ID المستخدم (اختياري)" style="width:160px">
      <select name="inv_type"><option value="subscription">اشتراك</option><option value="partner_fee">رسوم شراكة</option><option value="donation">تبرع</option><option value="custom">أخرى</option></select>
      <select name="inv_curr"><option value="SDG">جنيه سوداني SDG</option><option value="USD">دولار USD</option><option value="SAR">ريال SAR</option><option value="EGP">جنيه مصري EGP</option></select>
      <input type="number" name="inv_amount" placeholder="المبلغ *" step="0.01" style="width:120px">
    </div>
    <div class="form-row">
      <input type="text" name="inv_desc" placeholder="وصف الفاتورة" style="flex:2">
      <select name="inv_method"><option value="cash">نقداً</option><option value="bank_transfer">تحويل بنكي</option><option value="mobile_money">محفظة موبايل</option><option value="online">أونلاين</option></select>
      <input type="date" name="inv_due" placeholder="تاريخ الاستحقاق">
      <button class="btn btn-g">إنشاء فاتورة</button>
    </div>
  </form>
</div>
<div class="sec-head">
  <h3>الفواتير (<?= count($invoices) ?>)</h3>
  <div style="display:flex;gap:6px;flex-wrap:wrap">
    <?php foreach(['all'=>'الكل','pending'=>'معلقة','paid'=>'مدفوعة','cancelled'=>'ملغية'] as $s=>$l): ?>
    <a href="?tab=invoices&invf=<?= $s ?>" class="btn <?= $inv_filter===$s?'btn-g':'btn-b' ?>"><?= $l ?></a>
    <?php endforeach; ?>
    <form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="export_invoices"><button class="btn btn-s">⬇ CSV</button></form>
  </div>
</div>
<?php if($invoices): ?>
<table>
<tr><th>رقم الفاتورة</th><th>العميل</th><th>النوع</th><th>الوصف</th><th>المبلغ</th><th>الحالة</th><th>طريقة الدفع</th><th>الاستحقاق</th><th>الدفع</th><th>إجراءات</th></tr>
<?php foreach($invoices as $r): ?>
<tr>
  <td><strong dir="ltr"><?= htmlspecialchars($r['invoice_no']) ?></strong></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($r['client_name']??'—') ?><br><span style="color:#999"><?= htmlspecialchars($r['client_email']??'') ?></span></td>
  <td><?= $r['type'] ?></td>
  <td style="max-width:150px;font-size:.72rem"><?= htmlspecialchars(mb_substr($r['description']??'',0,50)) ?></td>
  <td><strong><?= number_format($r['amount'],2) ?> <?= $r['currency'] ?></strong></td>
  <td><span class="badge b-<?= $r['status']==='paid'?'paid-inv':$r['status'] ?>"><?= $r['status'] ?></span></td>
  <td style="font-size:.72rem"><?= $r['payment_method'] ?></td>
  <td style="font-size:.72rem"><?= $r['due_date']??'—' ?></td>
  <td style="font-size:.72rem"><?= $r['paid_at']?substr($r['paid_at'],0,10):'—' ?></td>
  <td>
    <?php if($r['status']==='pending'): ?>
    <div class="actions">
      <form method="POST" class="inline-form">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="mark_invoice_paid">
        <input type="hidden" name="inv_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="invoices">
        <input type="text" name="pay_ref" placeholder="مرجع الدفع" style="width:100px;padding:3px 6px;border:1px solid #ddd;border-radius:5px;font-size:.72rem">
        <button class="btn btn-s">✅ دفع</button>
      </form>
      <form method="POST" class="inline-form" onsubmit="return confirm('إلغاء الفاتورة؟')">
        <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="cancel_invoice">
        <input type="hidden" name="inv_id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="invoices">
        <button class="btn btn-r">✕</button>
      </form>
    </div>
    <?php elseif($r['status']==='paid'): ?>
    <a href="?tab=invoices&print=<?= $r['id'] ?>" class="btn btn-b" target="_blank">🖨️ طباعة</a>
    <?php endif; ?>
  </td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

<?php
// ══════════════════════════════════════════════════════
// الموظفون
// ══════════════════════════════════════════════════════
elseif($tab==='staff'):
$staff_list = []; try { $staff_list = db()->query('SELECT * FROM staff_members ORDER BY id DESC')->fetchAll(); } catch(Throwable $e) { echo '<div style="background:#fff3e0;padding:12px;border-radius:8px;margin-bottom:16px">⚠️ شغّل migrate.sql أولاً لإنشاء جدول الموظفين</div>'; }
?>
<?php if(in_array($role,['super_admin'])): ?>
<div class="form-box">
  <h3>➕ إضافة موظف جديد</h3>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="add_staff"><input type="hidden" name="tab" value="staff">
    <div class="form-row">
      <input type="text" name="s_name" placeholder="الاسم الكامل *" style="flex:1">
      <input type="email" name="s_email" placeholder="البريد الإلكتروني *" style="flex:1">
      <input type="password" name="s_pass" placeholder="كلمة المرور (6+) *" style="flex:1">
    </div>
    <div class="form-row">
      <select name="s_role">
        <option value="support">دعم العملاء</option>
        <option value="content">محتوى</option>
        <option value="finance">مالية</option>
        <option value="supervisor">مشرف</option>
        <option value="admin">أدمن</option>
      </select>
      <input type="text" name="s_dept" placeholder="القسم / الإدارة" style="flex:1">
      <button class="btn btn-g">إضافة الموظف</button>
    </div>
  </form>
</div>
<?php endif; ?>
<?php if($staff_list): ?>
<div class="sec-head"><h3>فريق العمل (<?= count($staff_list) ?>)</h3></div>
<table>
<tr><th>ID</th><th>الاسم</th><th>البريد</th><th>الدور</th><th>القسم</th><th>الحالة</th><th>آخر دخول</th><th>إجراءات</th></tr>
<?php foreach($staff_list as $r): ?>
<tr>
  <td><?= $r['id'] ?></td>
  <td><strong><?= htmlspecialchars($r['name']) ?></strong></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($r['email']) ?></td>
  <td><span class="badge b-<?= $r['role'] ?>"><?= $r['role'] ?></span></td>
  <td><?= htmlspecialchars($r['department']??'—') ?></td>
  <td><?= $r['active']?'<span class="badge b-active">✅ نشط</span>':'<span class="badge b-removed">❌ موقوف</span>' ?></td>
  <td style="font-size:.72rem"><?= $r['last_login']?substr($r['last_login'],0,16):'لم يدخل بعد' ?></td>
  <td>
    <?php if(in_array($role,['super_admin']) && $r['id'] !== ($_SESSION['staff_id']??-1)): ?>
    <div class="actions">
      <form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="toggle_staff"><input type="hidden" name="sid" value="<?= $r['id'] ?>"><input type="hidden" name="active" value="<?= $r['active'] ?>"><input type="hidden" name="tab" value="staff"><button class="btn <?= $r['active']?'btn-r':'btn-g' ?>"><?= $r['active']?'⏸ إيقاف':'▶ تفعيل' ?></button></form>
      <form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="reset_staff_pw"><input type="hidden" name="sid" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="staff"><input type="text" name="np" placeholder="كلمة مرور جديدة" style="width:110px;padding:3px 8px;border:1px solid #ddd;border-radius:5px;font-size:.75rem"><button class="btn btn-o">🔑</button></form>
    </div>
    <?php endif; ?>
  </td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

<?php
// ══════════════════════════════════════════════════════
// التقارير
// ══════════════════════════════════════════════════════
elseif($tab==='reports'):
$rev_total = 0; $rev_paid = 0;
try {
  $rev = db()->query("SELECT SUM(amount) as t, SUM(CASE WHEN status='paid' THEN amount ELSE 0 END) as p FROM invoices WHERE currency='SDG'")->fetch();
  $rev_total = (float)($rev['t']??0); $rev_paid = (float)($rev['p']??0);
} catch(Throwable $ignored){}
$top_users = db()->query("SELECT name,email,points_learn+points_trade+points_community+points_family AS total_pts,subscription_tier FROM users ORDER BY total_pts DESC LIMIT 10")->fetchAll();
$by_state  = db()->query("SELECT state, COUNT(*) AS cnt FROM users WHERE state != '' GROUP BY state ORDER BY cnt DESC LIMIT 15")->fetchAll();
$by_track  = db()->query("SELECT learning_track, COUNT(*) AS cnt FROM users GROUP BY learning_track")->fetchAll();
$ai_usage  = []; try { $ai_usage = db()->query("SELECT service, COUNT(*) AS cnt, DATE(created_at) AS day FROM ai_logs WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) GROUP BY service, day ORDER BY day DESC, cnt DESC LIMIT 50")->fetchAll(); } catch(Throwable $ignored){}
?>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;margin-bottom:20px">
  <div style="background:#fff;border-radius:10px;padding:16px;border:1.5px solid #e8f5e9;text-align:center"><div style="font-size:1.4rem;font-weight:900;color:#073328"><?= number_format($rev_paid,0) ?> SDG</div><div style="font-size:.8rem;color:#666">إجمالي المدفوعات</div></div>
  <div style="background:#fff;border-radius:10px;padding:16px;border:1.5px solid #fff3e0;text-align:center"><div style="font-size:1.4rem;font-weight:900;color:#e65100"><?= number_format($rev_total-$rev_paid,0) ?> SDG</div><div style="font-size:.8rem;color:#666">فواتير معلقة</div></div>
  <div style="background:#fff;border-radius:10px;padding:16px;border:1.5px solid #e3f2fd;text-align:center"><div style="font-size:1.4rem;font-weight:900;color:#1565c0"><?= $stats['users'] ?></div><div style="font-size:.8rem;color:#666">إجمالي المستخدمين</div></div>
  <div style="background:#fff;border-radius:10px;padding:16px;border:1.5px solid #f3e5f5;text-align:center"><div style="font-size:1.4rem;font-weight:900;color:#6a1b9a"><?= $stats['paid'] ?></div><div style="font-size:.8rem;color:#666">مشتركون مدفوعون</div></div>
</div>
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;flex-wrap:wrap">
  <div><h4 style="margin-bottom:10px;color:#073328">🏅 أكثر المستخدمين نشاطاً</h4>
  <table><tr><th>الاسم</th><th>النقاط</th><th>الاشتراك</th></tr>
  <?php foreach($top_users as $r): ?><tr><td><?= htmlspecialchars($r['name']) ?></td><td><?= number_format($r['total_pts']) ?></td><td><span class="badge b-<?= $r['subscription_tier'] ?>"><?= $r['subscription_tier'] ?></span></td></tr><?php endforeach; ?>
  </table></div>
  <div><h4 style="margin-bottom:10px;color:#073328">🗺️ التوزيع الجغرافي</h4>
  <table><tr><th>الولاية</th><th>المستخدمون</th></tr>
  <?php foreach($by_state as $r): ?><tr><td><?= htmlspecialchars($r['state']) ?></td><td><?= $r['cnt'] ?></td></tr><?php endforeach; ?>
  </table></div>
  <div><h4 style="margin-bottom:10px;color:#073328">📚 المسارات التعليمية</h4>
  <table><tr><th>المسار</th><th>العدد</th></tr>
  <?php foreach($by_track as $r): ?><tr><td><?= $r['learning_track']??'—' ?></td><td><?= $r['cnt'] ?></td></tr><?php endforeach; ?>
  </table>
  <?php if($ai_usage): ?>
  <h4 style="margin:14px 0 10px;color:#073328">🤖 استخدام AI (7 أيام)</h4>
  <table><tr><th>الخدمة</th><th>اليوم</th><th>طلبات</th></tr>
  <?php foreach($ai_usage as $r): ?><tr><td><?= $r['service'] ?></td><td style="font-size:.72rem"><?= $r['day'] ?></td><td><?= $r['cnt'] ?></td></tr><?php endforeach; ?>
  </table><?php endif; ?>
  </div>
</div>

<?php
// ══════════════════════════════════════════════════════
// AI Logs
// ══════════════════════════════════════════════════════
elseif($tab==='ai_logs'):
$ai_logs = []; try { $ai_logs = db()->query("SELECT l.*, u.name AS uname FROM ai_logs l LEFT JOIN users u ON u.id=l.user_id ORDER BY l.id DESC LIMIT 200")->fetchAll(); } catch(Throwable $e) { echo '<div style="background:#fff3e0;padding:12px;border-radius:8px">⚠️ جدول ai_logs غير متاح</div>'; }
?>
<div class="sec-head"><h3>سجل استخدام الذكاء الاصطناعي (<?= count($ai_logs) ?>)</h3></div>
<?php if($ai_logs): ?>
<table><tr><th>ID</th><th>الخدمة</th><th>المستخدم</th><th>التاريخ</th></tr>
<?php foreach($ai_logs as $r): ?>
<tr><td><?= $r['id'] ?></td><td><span class="badge b-active"><?= $r['service'] ?></span></td><td><?= htmlspecialchars($r['uname']??'زائر') ?></td><td style="font-size:.72rem"><?= substr($r['created_at'],0,16) ?></td></tr>
<?php endforeach; ?>
</table><?php endif; ?>

<?php
// ══════════════════════════════════════════════════════
// المستثمرون + الرسائل + الشركاء
// ══════════════════════════════════════════════════════
elseif($tab==='invest'):
?>
<div class="sec-head"><h3>طلبات الاستثمار</h3><form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="export_investors"><button class="btn btn-g">⬇ CSV</button></form></div>
<table><tr><th>الاسم</th><th>البريد</th><th>الهاتف</th><th>الدولة</th><th>الفئة</th><th>الحالة</th><th>التاريخ</th></tr>
<?php foreach(db()->query('SELECT * FROM investment_applications ORDER BY id DESC LIMIT 200') as $r): ?>
<tr><td><?= htmlspecialchars($r['name']) ?></td><td><?= htmlspecialchars($r['email']) ?></td><td><?= htmlspecialchars($r['phone']??'—') ?></td><td><?= htmlspecialchars($r['country']??'—') ?></td><td><?= htmlspecialchars($r['tier']??'—') ?></td><td><span class="badge b-active"><?= $r['status'] ?></span></td><td><?= substr($r['created_at'],0,10) ?></td></tr>
<?php endforeach; ?>
</table>

<?php elseif($tab==='inquiries'):
$inq = db()->query("SELECT * FROM inquiries ORDER BY FIELD(status,'new','read','replied'), id DESC LIMIT 200")->fetchAll();
?>
<h3 style="margin-bottom:12px;color:#073328">الرسائل والاستفسارات (<?= count($inq) ?>)</h3>
<table><tr><th>الاسم</th><th>البريد</th><th>النوع</th><th>الرسالة</th><th>الحالة</th><th>التاريخ</th><th>إجراء</th></tr>
<?php foreach($inq as $r): ?>
<tr style="<?= $r['status']==='new'?'background:#fff8e1':'' ?>">
  <td><strong><?= htmlspecialchars($r['name']??'—') ?></strong></td>
  <td style="font-size:.72rem"><?= htmlspecialchars($r['email']??'—') ?></td>
  <td><span class="badge b-active"><?= $r['type'] ?></span></td>
  <td style="max-width:250px;font-size:.78rem"><?= htmlspecialchars(mb_substr($r['message']??'',0,100)) ?>...</td>
  <td><span class="badge b-<?= $r['status']==='new'?'pending':($r['status']==='replied'?'resolved':'active') ?>"><?= $r['status'] ?></span></td>
  <td style="font-size:.72rem"><?= substr($r['created_at'],0,10) ?></td>
  <td><?php if($r['status']!=='replied'): ?><form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="mark_inquiry"><input type="hidden" name="id" value="<?= $r['id'] ?>"><input type="hidden" name="tab" value="inquiries"><button class="btn btn-g">✅ قرأت</button></form><?php endif; ?></td>
</tr>
<?php endforeach; ?>
</table>

<?php
// ══════════════════════════════════════════════════════
// تبويب الإشعارات والبث
// ══════════════════════════════════════════════════════
elseif($tab==='broadcast'):
$total_users    = (int)db()->query('SELECT COUNT(*) FROM users')->fetchColumn();
$users_with_fcm = 0;
try { $users_with_fcm = (int)db()->query('SELECT COUNT(DISTINCT user_id) FROM user_devices WHERE last_seen > NOW() - INTERVAL 90 DAY')->fetchColumn(); } catch(Throwable $ignored){}
if (!$users_with_fcm) { try { $users_with_fcm = (int)db()->query('SELECT COUNT(*) FROM users WHERE fcm_token IS NOT NULL AND fcm_token != ""')->fetchColumn(); } catch(Throwable $ignored){} }
$paid_users  = (int)db()->query("SELECT COUNT(*) FROM users WHERE subscription_tier='paid'")->fetchColumn();
$states = db()->query("SELECT DISTINCT state, COUNT(*) AS cnt FROM users WHERE state != '' GROUP BY state ORDER BY cnt DESC LIMIT 20")->fetchAll();
$broadcast_logs = []; try { $broadcast_logs = db()->query("SELECT * FROM staff_activity_log WHERE action='broadcast_push' ORDER BY id DESC LIMIT 15")->fetchAll(); } catch(Throwable $ignored) {}
?>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px;margin-bottom:20px">
  <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;border:1.5px solid #e8f5e9"><div style="font-size:1.5rem;font-weight:900;color:#073328"><?= number_format($total_users) ?></div><div style="font-size:.76rem;color:#666">👤 إجمالي المستخدمين</div></div>
  <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;border:1.5px solid #e3f2fd"><div style="font-size:1.5rem;font-weight:900;color:#1565c0"><?= number_format($users_with_fcm) ?></div><div style="font-size:.76rem;color:#666">📱 FCM نشطون</div></div>
  <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;border:1.5px solid #fff3e0"><div style="font-size:1.5rem;font-weight:900;color:#e65100"><?= number_format($paid_users) ?></div><div style="font-size:.76rem;color:#666">💳 مدفوعون</div></div>
  <div style="background:#fff;border-radius:10px;padding:14px;text-align:center;border:1.5px solid #f3e5f5"><div style="font-size:1.5rem;font-weight:900;color:#6a1b9a"><?= number_format($total_users - $paid_users) ?></div><div style="font-size:.76rem;color:#666">🆓 مجانيون</div></div>
</div>

<div class="form-box" style="border:2px solid #073328">
  <h3 style="font-size:.95rem;margin-bottom:16px">📡 إرسال إشعار جماعي</h3>
  <form method="POST" onsubmit="return confirm('هل أنت متأكد من الإرسال؟')">
    <input type="hidden" name="csrf" value="<?= $csrf ?>">
    <input type="hidden" name="action" value="broadcast_push">
    <input type="hidden" name="tab" value="broadcast">
    <div class="form-row" style="margin-bottom:10px">
      <input type="text" name="b_title" placeholder="📌 عنوان الإشعار *" style="flex:2;min-width:200px;padding:8px 12px;border:1.5px solid #ddd;border-radius:8px;font-family:Arial" required>
    </div>
    <textarea name="b_body" rows="2" placeholder="محتوى الإشعار *" style="width:100%;padding:8px 12px;border:1.5px solid #ddd;border-radius:8px;font-family:Arial;resize:vertical;margin-bottom:10px" required></textarea>
    <div class="form-row" style="margin-bottom:12px;align-items:flex-end">
      <div>
        <label style="font-size:.76rem;color:#555;display:block;margin-bottom:4px">🎯 القطاع المستهدف</label>
        <select name="b_segment" id="b_seg" onchange="toggleBVal(this.value)" style="padding:8px 12px;border:1.5px solid #ddd;border-radius:8px;font-family:Arial;min-width:190px">
          <option value="all">🌍 الجميع (<?= $total_users ?>)</option>
          <option value="paid">💳 المدفوعون (<?= $paid_users ?>)</option>
          <option value="free">🆓 المجانيون (<?= $total_users-$paid_users ?>)</option>
          <option value="state">🗺️ ولاية محددة</option>
          <option value="city">🏙️ مدينة محددة</option>
          <option value="hood">🏘️ حي (ID)</option>
          <option value="track">📚 مسار تعليمي</option>
          <option value="user_type">👨‍⚕️ نوع مستخدم</option>
        </select>
      </div>
      <div id="bval_wrap" style="display:none;flex:1;min-width:150px">
        <label style="font-size:.76rem;color:#555;display:block;margin-bottom:4px">القيمة</label>
        <select name="b_value" id="bval_sel" style="width:100%;padding:8px 12px;border:1.5px solid #ddd;border-radius:8px;font-family:Arial">
          <option value="">-- اختر --</option>
          <?php foreach($states as $s): ?><option value="<?= htmlspecialchars($s['state']) ?>" data-seg="state"><?= htmlspecialchars($s['state']) ?> (<?= $s['cnt'] ?>)</option><?php endforeach; ?>
          <option value="foundation" data-seg="track">🌱 الأساس</option>
          <option value="growth" data-seg="track">🚀 النمو</option>
          <option value="leadership" data-seg="track">🏆 القيادة</option>
          <option value="user" data-seg="type">👤 عادي</option>
          <option value="teacher" data-seg="type">👨‍🏫 مدرس</option>
          <option value="doctor" data-seg="type">👨‍⚕️ طبيب</option>
          <option value="pharmacist" data-seg="type">💊 صيدلاني</option>
          <option value="service_provider" data-seg="type">🔧 مقدم خدمة</option>
          <option value="academic" data-seg="type">🎓 أكاديمي</option>
        </select>
        <input type="text" id="bval_txt" placeholder="اكتب هنا..." style="display:none;width:100%;padding:8px 12px;border:1.5px solid #ddd;border-radius:8px;font-family:Arial;margin-top:4px">
      </div>
    </div>
    <div style="display:flex;gap:10px;align-items:center">
      <button type="submit" class="btn btn-g" style="padding:10px 20px">📤 إرسال الإشعار</button>
      <span style="font-size:.76rem;color:#e53935">⚠️ يُرسل فوراً ولا يمكن التراجع</span>
    </div>
  </form>
</div>
<script>
function toggleBVal(seg){
  const wrap=document.getElementById('bval_wrap');
  const sel=document.getElementById('bval_sel');
  const txt=document.getElementById('bval_txt');
  if(['all','paid','free'].includes(seg)){wrap.style.display='none';return;}
  wrap.style.display='block';
  if(seg==='city'||seg==='hood'){
    sel.style.display='none'; sel.removeAttribute('name');
    txt.style.display='block'; txt.name='b_value';
    txt.placeholder=seg==='city'?'مثال: أم درمان':'رقم ID الحي';
  } else {
    sel.style.display='block'; sel.name='b_value';
    txt.style.display='none'; txt.removeAttribute('name');
    // Filter options
    const opts=sel.querySelectorAll('option');
    opts.forEach(o=>{
      const ds=o.dataset.seg||'';
      o.style.display=(ds===''||ds===seg)?'':'none';
    });
  }
}
</script>

<?php if($broadcast_logs): ?>
<div class="sec-head" style="margin-top:20px"><h3>📋 سجل الإرسالات الأخيرة</h3></div>
<table><tr><th>التاريخ</th><th>العنوان</th><th>القطاع</th><th>المُرسَل</th><th>IP</th></tr>
<?php foreach($broadcast_logs as $log):
  $det=json_decode($log['details']??'{}',true); ?>
<tr>
  <td style="font-size:.7rem"><?= substr($log['created_at']??'',0,16) ?></td>
  <td><?= htmlspecialchars(mb_substr($det['title']??'—',0,40)) ?></td>
  <td><span class="badge b-active"><?= htmlspecialchars($det['segment']??'all') ?><?= ($det['value']??'')?': '.htmlspecialchars($det['value']):'' ?></span></td>
  <td><strong><?= $det['sent']??'—' ?></strong></td>
  <td style="font-size:.7rem;color:#999"><?= htmlspecialchars($log['ip_address']??'') ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php else: ?>
<div style="text-align:center;padding:20px;color:#999;font-size:.82rem">لا توجد إرسالات سابقة</div>
<?php endif; ?>

<?php elseif($tab==='queue'):
// ── User Search ─────────────────────────────────────────────────
$user_search = trim($_GET['usq'] ?? '');
$user_search_results = [];
if ($user_search && strlen($user_search) >= 2) {
    try {
        $us = db()->prepare("SELECT id,name,email,subscription_tier,state,created_at FROM users WHERE name LIKE ? OR email LIKE ? LIMIT 30");
        $us->execute(["%$user_search%", "%$user_search%"]);
        $user_search_results = $us->fetchAll();
    } catch(Throwable $ignored){}
}

$queue_tasks = []; try { $queue_tasks = db()->query("SELECT * FROM tasks ORDER BY created_at DESC LIMIT 100")->fetchAll(); } catch(Throwable $e){ echo '<div style="background:#fff3e0;padding:12px">⚠️ جدول tasks غير موجود — شغّل migration_v22_complete.sql</div>'; }
?>
<div class="sec-head">
  <h3>⚙️ Queue Tasks (<?= count($queue_tasks) ?>)</h3>
  <div style="font-size:.75rem;color:#666">آخر 100 مهمة</div>
</div>
<table>
<tr><th>ID</th><th>النوع</th><th>الحالة</th><th>المحاولات</th><th>التنفيذ</th><th>آخر خطأ</th><th>أُنشئ</th></tr>
<?php foreach($queue_tasks as $t): ?>
<tr>
  <td><?= $t['id'] ?></td>
  <td><code style="font-size:.72rem"><?= htmlspecialchars($t['type']) ?></code></td>
  <td><span class="badge <?= $t['status']==='done'?'b-active':($t['status']==='failed'?'b-urgent':($t['status']==='processing'?'b-paid':'b-pending')) ?>"><?= $t['status'] ?></span></td>
  <td><?= $t['attempts'] ?></td>
  <td style="font-size:.7rem"><?= substr($t['run_at']??'',0,16) ?></td>
  <td style="font-size:.7rem;color:#e53935;max-width:200px;overflow:hidden"><?= htmlspecialchars(mb_substr($t['last_error']??'—',0,80)) ?></td>
  <td style="font-size:.7rem"><?= substr($t['created_at']??'',0,16) ?></td>
</tr>
<?php endforeach; ?>
</table>

<?php elseif($tab==='system_metrics'):
$metrics = []; try { $metrics = db()->query("SELECT metric, AVG(value) AS avg_val, MAX(value) AS max_val, COUNT(*) AS cnt, MAX(created_at) AS last_seen FROM ai_metrics GROUP BY metric ORDER BY last_seen DESC LIMIT 50")->fetchAll(); } catch(Throwable $e){ echo '<div style="background:#fff3e0;padding:12px">⚠️ جدول ai_metrics غير موجود — شغّل migration_v22_complete.sql</div>'; }
$decisions = []; try { $decisions = db()->query("SELECT event, score, created_at FROM ai_decisions ORDER BY created_at DESC LIMIT 50")->fetchAll(); } catch(Throwable $ignored){}
?>
<div class="sec-head"><h3>📈 System Metrics — AI Pipeline</h3></div>
<?php if($metrics): ?>
<table>
<tr><th>Metric</th><th>Count</th><th>Avg</th><th>Max</th><th>آخر ظهور</th></tr>
<?php foreach($metrics as $m): ?>
<tr>
  <td><code style="font-size:.72rem"><?= htmlspecialchars($m['metric']) ?></code></td>
  <td><?= $m['cnt'] ?></td>
  <td><?= round($m['avg_val'],2) ?></td>
  <td><?= round($m['max_val'],2) ?></td>
  <td style="font-size:.72rem"><?= substr($m['last_seen'],0,16) ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<div class="sec-head" style="margin-top:20px"><h3>🤖 AI Decisions (آخر 50)</h3></div>
<?php if($decisions): ?>
<table>
<tr><th>Event</th><th>Score</th><th>الوقت</th></tr>
<?php foreach($decisions as $d): ?>
<tr>
  <td><?= htmlspecialchars($d['event']) ?></td>
  <td><?= $d['score'] ?></td>
  <td style="font-size:.72rem"><?= substr($d['created_at'],0,16) ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

<?php elseif($tab==='partners'):
?>
<div class="form-box"><h3>➕ إضافة شريك</h3>
<form method="POST"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="add_partner"><input type="hidden" name="tab" value="partners">
<div class="form-row"><input type="text" name="name" placeholder="اسم الشريك *" style="flex:1"><select name="track"><option value="">كل المسارات</option><option value="foundation">الأساس</option><option value="growth">النمو</option><option value="leadership">القيادة</option></select><button class="btn btn-g">إضافة</button></div></form></div>
<table><tr><th>ID</th><th>الاسم</th><th>المسار</th><th>الحالة</th><th>إجراء</th></tr>
<?php foreach(db()->query('SELECT id,name,track,active FROM partners ORDER BY id DESC') as $r): ?>
<tr><td><?= $r['id'] ?></td><td><strong><?= htmlspecialchars($r['name']) ?></strong></td><td><?= $r['track']?:'الكل' ?></td><td><?= $r['active']?'<span class="badge b-active">✅</span>':'<span class="badge b-removed">❌</span>' ?></td>
<td><form method="POST" class="inline-form"><input type="hidden" name="csrf" value="<?= $csrf ?>"><input type="hidden" name="action" value="toggle_partner"><input type="hidden" name="pid" value="<?= $r['id'] ?>"><input type="hidden" name="active" value="<?= $r['active'] ?>"><input type="hidden" name="tab" value="partners"><button class="btn <?= $r['active']?'btn-r':'btn-g' ?>"><?= $r['active']?'⏸ إيقاف':'▶ تفعيل' ?></button></form></td></tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

</div>

<script>
// ── Admin Real-time Refresh ───────────────────────────────────
(function(){
  // Auto-refresh stats every 60 seconds
  if(window.location.search.includes('tab=dashboard') || !window.location.search.includes('tab=')){
    setInterval(function(){
      // Soft-reload stats section only
      const url = new URL(window.location.href);
      url.searchParams.set('_refresh', Date.now());
      // Visual indicator
      const dot = document.querySelector('.pulse');
      if(dot){ dot.style.animation='none'; setTimeout(()=>dot.style.animation='',100); }
    }, 60000);
  }

  // Search in tables
  window.filterTable = function(inputId, tableId){
    const q = document.getElementById(inputId)?.value?.toLowerCase()||'';
    const rows = document.querySelectorAll('#'+tableId+' tr:not(:first-child)');
    rows.forEach(row=>{
      row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
    });
  };

  // Export table to CSV
  window.exportCSV = function(tableId, filename){
    const rows = document.querySelectorAll('#'+tableId+' tr');
    const csv  = Array.from(rows).map(r=>
      Array.from(r.querySelectorAll('th,td')).map(c=>'"'+c.textContent.trim().replace(/"/g,'""')+'"').join(',')
    ).join('\n');
    const a = document.createElement('a');
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent('\uFEFF'+csv);
    a.download = (filename||'export')+'.csv';
    a.click();
  };
})();
</script>


<?php
// ── NEW: AI ENGINE TABS ──────────────────────────────────────────
$current_tab = $_GET['tab'] ?? '';

if ($current_tab === 'ai_engines'): ?>
<div style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">🧠 محركات AI — الوضع الحالي</h2>
  
  <!-- AssistantEngine Domains -->
  <div class="engine-card">
    <h3>🎯 AssistantEngine — 14 مساعد متخصص</h3>
    <?php
    $ae_domains = [
      ['hub','مساعد سودانا العام',['platform','general','government'],'#00d97e'],
      ['medical','المساعد الطبي',['medical','pharmacy','family','emergency'],'#ef4444'],
      ['legal','المساعد القانوني',['legal'],'#a78bfa'],
      ['finance','المساعد المالي',['finance','banking'],'#f59e0b'],
      ['education','المساعد التعليمي',['education','academic'],'#0ea5e9'],
      ['agriculture','المساعد الزراعي',['agriculture'],'#84cc16'],
      ['mental','مساعد الصحة النفسية',['mental'],'#f472b6'],
      ['career','المساعد المهني',['career'],'#fb923c'],
      ['community','مساعد الحي',['community'],'#34d399'],
      ['market','مساعد السوق',['market'],'#fbbf24'],
      ['sales','مساعد الأعمال',['business','bde'],'#60a5fa'],
      ['developer','مساعد المطورين',['developer','tech'],'#c084fc'],
      ['investment','مساعد الاستثمار',['finance'],'#2dd4bf'],
      ['enterprise','مساعد المؤسسات',['enterprise'],'#94a3b8'],
    ];
    foreach($ae_domains as [$key, $name, $sectors, $color]): ?>
    <div style="display:flex;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid #1e3a2a">
      <div style="width:32px;height:32px;background:<?= $color ?>18;border:1px solid <?= $color ?>40;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:.8rem;flex-shrink:0">
        <?= match($key){'medical'=>'⚕️','legal'=>'⚖️','mental'=>'🧘','education'=>'🎓','agriculture'=>'🌾','career'=>'💼','community'=>'🏘️','market'=>'🛒','sales'=>'📈','developer'=>'💻','finance'=>'💰','investment'=>'📊','enterprise'=>'🏢',default=>'🤖'} ?>
      </div>
      <div style="flex:1">
        <div style="font-weight:700;font-size:.8rem;color:#e2e8f0"><?= $name ?></div>
        <div style="font-size:.68rem;color:#64748b"><?= implode(', ', $sectors) ?></div>
      </div>
      <div style="font-size:.68rem;color:<?= $color ?>;background:<?= $color ?>12;padding:2px 8px;border-radius:10px"><?= $key ?></div>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- InferenceEngine Stats -->
  <div class="engine-card" style="margin-top:12px">
    <h3>⚡ InferenceEngine — 610 قاعدة | 19 قطاع</h3>
    <?php
    $ie_data = [
      ['academic',176,'#00d97e'],['medical',87,'#ef4444'],['platform',87,'#0ea5e9'],
      ['business',68,'#f59e0b'],['legal',33,'#a78bfa'],['finance',25,'#60a5fa'],
      ['community',23,'#34d399'],['tech',22,'#c084fc'],['mental',19,'#f472b6'],
      ['emergency',13,'#fb923c'],['agriculture',12,'#84cc16'],['career',11,'#fbbf24'],
      ['government',8,'#94a3b8'],['pharmacy',6,'#2dd4bf'],['bde',5,'#60a5fa'],
    ];
    $max_rules = 176;
    foreach($ie_data as [$sector, $count, $color]): ?>
    <div class="sector-bar">
      <span class="label"><?= $sector ?></span>
      <div style="flex:1;background:#1e3a2a;border-radius:3px;height:6px">
        <div class="bar" style="width:<?= round($count/$max_rules*100) ?>%;background:<?= $color ?>"></div>
      </div>
      <span class="num"><?= $count ?></span>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<?php elseif ($current_tab === 'policy_editor'): ?>
<div style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">📋 PolicyEngine — محرر السياسات الحي</h2>
  
  <?php
  try {
    $policies = db()->query("SELECT * FROM policy_versions ORDER BY created_at DESC LIMIT 30")->fetchAll();
    if ($policies): ?>
    <div style="background:#060d1a;border:1px solid #1e3a2a;border-radius:12px;overflow:hidden">
      <table style="width:100%;border-collapse:collapse;font-size:.78rem">
        <thead>
          <tr style="border-bottom:1px solid #1e3a2a">
            <th style="padding:10px 14px;text-align:right;color:#64748b;font-weight:600">السياسة</th>
            <th style="padding:10px 14px;text-align:right;color:#64748b;font-weight:600">الإجراء</th>
            <th style="padding:10px 14px;text-align:right;color:#64748b;font-weight:600">الشرط</th>
            <th style="padding:10px 14px;text-align:right;color:#64748b;font-weight:600">الحالة</th>
            <th style="padding:10px 14px;text-align:right;color:#64748b;font-weight:600">أُنشئت</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($policies as $p): ?>
          <tr style="border-bottom:1px solid #1e3a2a;transition:.15s" onmouseover="this.style.background='#0d2137'" onmouseout="this.style.background=''">
            <td style="padding:10px 14px;color:#e2e8f0;font-weight:600"><?= htmlspecialchars($p['policy_key'] ?? '') ?></td>
            <td style="padding:10px 14px">
              <span style="padding:2px 8px;border-radius:10px;font-size:.68rem;font-weight:700;
                background:<?= $p['action']==='BLOCK'?'#ef444415':($p['action']==='ALLOW'?'#00d97e15':'#f59e0b15') ?>;
                color:<?= $p['action']==='BLOCK'?'#ef4444':($p['action']==='ALLOW'?'#00d97e':'#f59e0b') ?>">
                <?= htmlspecialchars($p['action'] ?? '') ?>
              </span>
            </td>
            <td style="padding:10px 14px;color:#94a3b8;font-size:.72rem"><?= htmlspecialchars(substr($p['condition_dsl'] ?? '',0,60)) ?></td>
            <td style="padding:10px 14px">
              <span style="color:<?= ($p['is_active']??0)?'#00d97e':'#ef4444' ?>">
                <?= ($p['is_active']??0) ? '● نشط' : '○ معطّل' ?>
              </span>
            </td>
            <td style="padding:10px 14px;color:#64748b;font-size:.72rem"><?= substr($p['created_at']??'',0,10) ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php else: ?>
    <div class="engine-card">
      <p style="color:#64748b;font-size:.85rem">لا توجد سياسات مسجّلة في قاعدة البيانات بعد. يعمل النظام بالسياسات الداخلية في PolicyEngine.php</p>
      <div style="margin-top:12px;padding:12px;background:#0d2137;border-radius:8px;font-family:monospace;font-size:.75rem;color:#6ee7b7">
        // السياسات الحالية في PolicyEngine.php:<br>
        BLOCK: medical.ai_diagnosis<br>
        ALLOW: platform.navigation<br>
        REQUIRE_APPROVAL: finance.large_transfer<br>
        BLOCK: emergency.delay<br>
        ...و 17 سياسة أخرى
      </div>
    </div>
    <?php endif;
  } catch(Throwable $e) {
    echo '<div class="engine-card"><p style="color:#ef4444">خطأ: '.$e->getMessage().'</p></div>';
  }
  ?>
</div>

<?php elseif ($current_tab === 'ie_rules'): ?>
<div style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">⚡ InferenceEngine — قواعد الاستدلال المحلي</h2>
  <div class="engine-card">
    <p style="font-size:.82rem;color:#94a3b8;margin-bottom:14px">610 قاعدة PHP تعمل offline — إجابات فورية بدون AI cost</p>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:10px;margin-bottom:16px">
      <div style="background:#0d2137;border-radius:10px;padding:12px;text-align:center">
        <div style="font-size:1.5rem;font-weight:900;color:#00d97e">610</div>
        <div style="font-size:.68rem;color:#64748b;margin-top:3px">إجمالي القواعد</div>
      </div>
      <div style="background:#0d2137;border-radius:10px;padding:12px;text-align:center">
        <div style="font-size:1.5rem;font-weight:900;color:#0ea5e9">19</div>
        <div style="font-size:.68rem;color:#64748b;margin-top:3px">قطاعات</div>
      </div>
      <div style="background:#0d2137;border-radius:10px;padding:12px;text-align:center">
        <div style="font-size:1.5rem;font-weight:900;color:#f59e0b">80+</div>
        <div style="font-size:.68rem;color:#64748b;margin-top:3px">نمط لكل قاعدة</div>
      </div>
      <div style="background:#0d2137;border-radius:10px;padding:12px;text-align:center">
        <div style="font-size:1.5rem;font-weight:900;color:#a78bfa">0.6+</div>
        <div style="font-size:.68rem;color:#64748b;margin-top:3px">عتبة الثقة</div>
      </div>
    </div>
    <p style="font-size:.78rem;color:#64748b">بنية القاعدة: {id, sector, patterns[], response_ar, confidence, execution_mode, requires_provider, billing_class}</p>
  </div>
</div>


<?php elseif ($current_tab === 'wallet_summary'): ?>
<div style="max-width:900px" class="fade-in">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">👛 المحافظ والمعاملات المالية</h2>
  <?php
  try {
    // Wallet stats
    $w_stats = db()->query("SELECT COUNT(*) as wallets, COALESCE(SUM(balance),0) as total_balance FROM wallet WHERE is_active=1")->fetch();
    $tx_today = db()->query("SELECT COUNT(*) as cnt, COALESCE(SUM(amount_sdg),0) as vol FROM wallet_transactions WHERE DATE(created_at)=CURDATE()")->fetch();
    $reserves = db()->query("SELECT COUNT(*) as cnt, COALESCE(SUM(reserved_amount),0) as total FROM billing_reserves WHERE status='active'")->fetch();
    $receipts = db()->query("SELECT COUNT(*) as cnt FROM payment_receipts WHERE DATE(created_at)=CURDATE()")->fetch();
  ?>
  <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin-bottom:18px">
    <div class="stat" style="text-align:center">
      <div style="font-size:1.6rem;font-weight:900;color:#00d97e"><?php echo number_format($w_stats['wallets']); ?></div>
      <div style="font-size:.7rem;color:#64748b;margin-top:4px">محافظ نشطة</div>
    </div>
    <div class="stat" style="text-align:center">
      <div style="font-size:1.6rem;font-weight:900;color:#f59e0b"><?php echo number_format($w_stats['total_balance']); ?></div>
      <div style="font-size:.7rem;color:#64748b;margin-top:4px">إجمالي الأرصدة (SDG)</div>
    </div>
    <div class="stat" style="text-align:center">
      <div style="font-size:1.6rem;font-weight:900;color:#0ea5e9"><?php echo number_format($tx_today['cnt']); ?></div>
      <div style="font-size:.7rem;color:#64748b;margin-top:4px">معاملات اليوم</div>
    </div>
    <div class="stat" style="text-align:center">
      <div style="font-size:1.6rem;font-weight:900;color:#a78bfa"><?php echo number_format($reserves['cnt']); ?></div>
      <div style="font-size:.7rem;color:#64748b;margin-top:4px">احتياطيات نشطة</div>
    </div>
  </div>
  <div class="engine-card">
    <h3>آخر 30 معاملة</h3>
    <?php $txs = db()->query("SELECT wt.*, u.full_name FROM wallet_transactions wt LEFT JOIN users u ON wt.user_id=u.id ORDER BY wt.created_at DESC LIMIT 30")->fetchAll(); ?>
    <div style="overflow-x:auto">
    <table style="width:100%;border-collapse:collapse;font-size:.76rem" class="admin-table">
      <thead><tr>
        <th style="padding:8px;text-align:right;border-bottom:1px solid #1e3a2a;color:#64748b">المستخدم</th>
        <th style="padding:8px;text-align:right;border-bottom:1px solid #1e3a2a;color:#64748b">النوع</th>
        <th style="padding:8px;text-align:right;border-bottom:1px solid #1e3a2a;color:#64748b">المبلغ</th>
        <th style="padding:8px;text-align:right;border-bottom:1px solid #1e3a2a;color:#64748b">الرصيد بعد</th>
        <th style="padding:8px;text-align:right;border-bottom:1px solid #1e3a2a;color:#64748b">التاريخ</th>
      </tr></thead>
      <tbody>
      <?php foreach($txs as $tx): ?>
        <tr style="border-bottom:1px solid #1e3a2a">
          <td style="padding:8px"><?php echo htmlspecialchars($tx['full_name'] ?? 'نظام'); ?></td>
          <td style="padding:8px"><span class="badge-<?php echo in_array($tx['type'],['credit','release'])?'ok':($tx['type']==='hold'?'warn':'err'); ?>"><?php echo $tx['type']; ?></span></td>
          <td style="padding:8px;font-weight:700;color:<?php echo in_array($tx['type'],['credit','release'])?'#00d97e':'#f87171'; ?>"><?php echo number_format($tx['amount_sdg'],2); ?></td>
          <td style="padding:8px;color:#94a3b8"><?php echo number_format($tx['balance_after'],2); ?></td>
          <td style="padding:8px;color:#64748b;font-size:.7rem"><?php echo substr($tx['created_at'],0,16); ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
    </div>
  </div>
  <?php } catch(Throwable $e) { echo '<div class="badge-err">خطأ: '.htmlspecialchars($e->getMessage()).'</div>'; } ?>
</div>

<?php elseif ($current_tab === 'execution_log'): ?>
<div style="max-width:900px" class="fade-in">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">🔍 سجل التنفيذ — Request Traces</h2>
  <?php
  try {
    $logs = db()->query("SELECT * FROM execution_log ORDER BY created_at DESC LIMIT 50")->fetchAll();
  ?>
  <div style="display:flex;gap:8px;margin-bottom:14px;flex-wrap:wrap">
    <span style="font-size:.78rem;color:#64748b">آخر 50 طلب — تحديث تلقائي كل 30 ثانية</span>
    <a href="?tab=execution_log" class="badge-ok" style="text-decoration:none;cursor:pointer">🔄 تحديث</a>
  </div>
  <div class="engine-card" style="padding:0;overflow:hidden">
    <table style="width:100%;border-collapse:collapse;font-size:.74rem" class="admin-table">
      <thead><tr style="background:#060d1a">
        <th style="padding:10px;text-align:right;color:#64748b">الوقت</th>
        <th style="padding:10px;text-align:right;color:#64748b">القطاع</th>
        <th style="padding:10px;text-align:right;color:#64748b">النية</th>
        <th style="padding:10px;text-align:right;color:#64748b">Domain</th>
        <th style="padding:10px;text-align:right;color:#64748b">الحالة</th>
        <th style="padding:10px;text-align:right;color:#64748b">المدة</th>
      </tr></thead>
      <tbody>
      <?php foreach($logs as $log): ?>
      <?php $state = json_decode($log['state_data'] ?? '{}', true); ?>
      <tr style="border-bottom:1px solid #1e3a2a">
        <td style="padding:8px;color:#64748b;font-size:.68rem"><?php echo substr($log['created_at']??'',11,8); ?></td>
        <td style="padding:8px"><span class="badge-ok"><?php echo htmlspecialchars($state['sector']??$log['sector']??'-'); ?></span></td>
        <td style="padding:8px;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#e2e8f0"><?php echo htmlspecialchars(substr($state['intent']??$log['intent']??'-',0,40)); ?></td>
        <td style="padding:8px;color:#a78bfa"><?php echo htmlspecialchars($state['domain']??'-'); ?></td>
        <td style="padding:8px"><span class="badge-<?php echo ($log['status']??'ok')==='ok'?'ok':(($log['status']==='error')?'err':'warn'); ?>"><?php echo $log['status']??'ok'; ?></span></td>
        <td style="padding:8px;color:#64748b"><?php echo $log['duration_ms']??'-'; ?>ms</td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php } catch(Throwable $e) { echo '<div class="badge-warn">'.htmlspecialchars($e->getMessage()).'</div>'; } ?>
</div>

<?php elseif ($current_tab === 'support'): ?>
<div style="max-width:900px" class="fade-in">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">🎫 تذاكر الدعم الفني</h2>
  <?php
  try {
    $tickets = db()->query("SELECT st.*, u.full_name FROM support_tickets st LEFT JOIN users u ON st.user_id=u.id ORDER BY st.created_at DESC LIMIT 30")->fetchAll();
    $open_count = db()->query("SELECT COUNT(*) FROM support_tickets WHERE status='open'")->fetchColumn();
  ?>
  <div style="display:flex;align-items:center;gap:12px;margin-bottom:14px">
    <span class="badge-warn"><?php echo $open_count; ?> مفتوح</span>
    <span style="font-size:.78rem;color:#64748b">آخر 30 تذكرة</span>
  </div>
  <div class="engine-card" style="padding:0;overflow:hidden">
    <table style="width:100%;border-collapse:collapse;font-size:.76rem" class="admin-table">
      <thead><tr style="background:#060d1a">
        <th style="padding:10px;text-align:right;color:#64748b">المستخدم</th>
        <th style="padding:10px;text-align:right;color:#64748b">الموضوع</th>
        <th style="padding:10px;text-align:right;color:#64748b">الحالة</th>
        <th style="padding:10px;text-align:right;color:#64748b">التاريخ</th>
        <th style="padding:10px;text-align:right;color:#64748b">إجراء</th>
      </tr></thead>
      <tbody>
      <?php foreach($tickets as $t): ?>
      <tr style="border-bottom:1px solid #1e3a2a">
        <td style="padding:8px"><?php echo htmlspecialchars($t['full_name']??''); ?></td>
        <td style="padding:8px;color:#e2e8f0"><?php echo htmlspecialchars(substr($t['subject']??'',0,50)); ?></td>
        <td style="padding:8px"><span class="badge-<?php echo $t['status']==='open'?'warn':($t['status']==='resolved'?'ok':'err'); ?>"><?php echo $t['status']??'open'; ?></span></td>
        <td style="padding:8px;color:#64748b;font-size:.7rem"><?php echo substr($t['created_at']??'',0,10); ?></td>
        <td style="padding:8px">
          <form method="POST" style="display:inline">
            <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
            <input type="hidden" name="action" value="close_ticket">
            <input type="hidden" name="ticket_id" value="<?php echo $t['id']; ?>">
            <button type="submit" class="badge-ok" style="border:none;cursor:pointer">إغلاق</button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php } catch(Throwable $e) { echo '<div class="badge-warn">'.htmlspecialchars($e->getMessage()).'</div>'; } ?>
</div>


<?php elseif ($current_tab === 'pricing_exchange'): ?>
<div class="fade-in" style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">💱 التحكم في سعر الصرف</h2>
  <?php
  $rate_result = null;
  if (!empty($_POST['action']) && $_POST['action']==='update_rate' && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $newRate = (float)($_POST['new_rate']??0);
    $note    = mb_substr(trim($_POST['note']??''),0,200);
    require_once __DIR__.'/engine/PricingEngine.php';
    $rate_result = PricingEngine::updateRate($newRate, (int)($_SESSION['admin']['id']??0), $note);
  }
  require_once __DIR__.'/engine/PricingEngine.php';
  $currentRate = PricingEngine::getRate();
  $rateHistory = PricingEngine::getHistory(20);
  ?>
  <?php if ($rate_result): ?>
  <div class="<?php echo $rate_result['ok']?'badge-ok':'badge-err'; ?>" style="padding:10px 14px;border-radius:8px;margin-bottom:16px;display:inline-block">
    <?php echo $rate_result['ok'] ? '✅ تم تحديث سعر الصرف' : '❌ '.$rate_result['error']; ?>
    <?php if ($rate_result['ok'] && $rate_result['alert']): ?>
    <span style="margin-right:8px;color:#f59e0b"> ⚠️ تغيير كبير: <?php echo abs($rate_result['change_pct']); ?>%</span>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <div class="engine-card" style="margin-bottom:16px">
    <h3>📊 السعر الفعّال الآن</h3>
    <div style="font-size:2rem;font-weight:900;color:#00d97e;margin:12px 0">
      1 USD = <?php echo number_format($currentRate,0); ?> SDG
    </div>
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin-top:12px">
      <?php
      $preview = [
        ['Plus','5.00',$currentRate*5],
        ['Pro','12.20',$currentRate*12.20],
        ['Starter ($99)','99',$currentRate*99],
        ['Business ($249)','249',$currentRate*249],
      ];
      foreach($preview as [$name,$usd,$sdg]):
      ?>
      <div class="stat" style="text-align:center">
        <div style="font-size:.75rem;color:#64748b;margin-bottom:4px"><?php echo $name; ?></div>
        <div style="font-size:1.1rem;font-weight:800;color:#e2e8f0"><?php echo number_format((int)$sdg); ?></div>
        <div style="font-size:.65rem;color:#475569">SDG</div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <div class="engine-card" style="margin-bottom:16px">
    <h3>✏️ تحديث السعر</h3>
    <form method="POST">
      <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
      <input type="hidden" name="action" value="update_rate">
      <div style="display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap;margin-top:12px">
        <div>
          <label style="font-size:.75rem;color:#64748b;display:block;margin-bottom:4px">1 USD = كم جنيه؟</label>
          <input type="number" name="new_rate" value="<?php echo $currentRate; ?>"
            min="100" max="100000" step="1" required
            style="background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:8px;padding:10px 14px;font-family:inherit;font-size:1rem;width:160px">
        </div>
        <div style="flex:1">
          <label style="font-size:.75rem;color:#64748b;display:block;margin-bottom:4px">ملاحظة (اختياري)</label>
          <input type="text" name="note" placeholder="مثال: تحديث بناءً على بنك السودان"
            style="background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:8px;padding:10px 14px;font-family:inherit;font-size:.85rem;width:100%">
        </div>
        <button type="submit" style="background:#00d97e;color:#000;border:none;border-radius:8px;padding:10px 20px;font-family:inherit;font-weight:800;cursor:pointer;white-space:nowrap">
          ⚡ حفظ وتطبيق فوراً
        </button>
      </div>
    </form>
  </div>

  <?php if ($rateHistory): ?>
  <div class="engine-card">
    <h3>📋 سجل التعديلات</h3>
    <table style="width:100%;border-collapse:collapse;font-size:.76rem;margin-top:12px" class="admin-table">
      <thead><tr style="background:#060d1a">
        <th style="padding:8px;color:#64748b;text-align:right">التاريخ</th>
        <th style="padding:8px;color:#64748b;text-align:right">السعر</th>
        <th style="padding:8px;color:#64748b;text-align:right">التغيير%</th>
        <th style="padding:8px;color:#64748b;text-align:right">بواسطة</th>
        <th style="padding:8px;color:#64748b;text-align:right">ملاحظة</th>
      </tr></thead>
      <tbody>
      <?php foreach($rateHistory as $r): ?>
      <tr style="border-bottom:1px solid #1e3a2a">
        <td style="padding:8px;color:#64748b;font-size:.7rem"><?php echo substr($r['created_at'],0,16); ?></td>
        <td style="padding:8px;font-weight:700;color:#00d97e"><?php echo number_format($r['rate_usd_sdg'],0); ?> SDG</td>
        <td style="padding:8px">
          <?php if($r['change_pct']!==null): ?>
          <span style="color:<?php echo $r['change_pct']>0?'#ef4444':'#00d97e'; ?>">
            <?php echo $r['change_pct']>0?'▲':'▼'; ?> <?php echo abs($r['change_pct']); ?>%
          </span>
          <?php else: echo '—'; endif; ?>
        </td>
        <td style="padding:8px;color:#94a3b8"><?php echo htmlspecialchars($r['set_by_name']??'نظام'); ?></td>
        <td style="padding:8px;color:#64748b;font-size:.7rem"><?php echo htmlspecialchars($r['note']??''); ?></td>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>

<?php elseif ($current_tab === 'pricing_plans'): ?>
<div class="fade-in" style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:4px">💳 أسعار الاشتراكات</h2>
  <p style="font-size:.78rem;color:#64748b;margin-bottom:16px">سعر الصرف الحالي: <?php require_once __DIR__.'/engine/PricingEngine.php'; echo number_format(PricingEngine::getRate(),0); ?> SDG/USD</p>
  <?php
  if (!empty($_POST['action']) && $_POST['action']==='update_plans' && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $updates = [
      ['sub_plus_price_sdg',  (int)($_POST['plus_sdg']??20000)],
      ['sub_pro_price_sdg',   (int)($_POST['pro_sdg']??50000)],
      ['credit_plus_sdg',     (int)($_POST['credit_plus']??15000)],
      ['credit_pro_sdg',      (int)($_POST['credit_pro']??50000)],
    ];
    foreach($updates as [$key,$val]) {
      PricingEngine::updateSetting($key, (string)$val, (int)($_SESSION['admin']['id']??0));
    }
    echo '<div class="badge-ok" style="padding:10px;border-radius:8px;margin-bottom:16px;display:inline-block">✅ تم حفظ أسعار الاشتراكات</div>';
  }
  $ps = PricingEngine::getAll();
  ?>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
    <input type="hidden" name="action" value="update_plans">
    <div class="engine-card" style="margin-bottom:16px">
      <table style="width:100%;border-collapse:collapse;font-size:.82rem">
        <thead><tr style="border-bottom:1px solid #1e3a2a">
          <th style="padding:10px;text-align:right;color:#64748b">الخطة</th>
          <th style="padding:10px;text-align:right;color:#64748b">السعر (SDG/شهر)</th>
          <th style="padding:10px;text-align:right;color:#64748b">بالدولار (~)</th>
          <th style="padding:10px;text-align:right;color:#64748b">رصيد وثائق/شهر</th>
          <th style="padding:10px;text-align:right;color:#64748b">AI/يوم</th>
          <th style="padding:10px;text-align:right;color:#64748b">حجوزات/يوم</th>
        </tr></thead>
        <tbody>
          <tr style="border-bottom:1px solid #1e3a2a">
            <td style="padding:10px;font-weight:700">🆓 مجاني</td>
            <td style="padding:10px;color:#00d97e;font-weight:800">0 SDG</td>
            <td style="padding:10px;color:#64748b">$0</td>
            <td style="padding:10px;color:#64748b">0</td>
            <td style="padding:10px;color:#64748b">20</td>
            <td style="padding:10px;color:#64748b">2</td>
          </tr>
          <tr style="border-bottom:1px solid #1e3a2a">
            <td style="padding:10px;font-weight:700">⭐ Plus</td>
            <td style="padding:10px">
              <input type="number" name="plus_sdg" value="<?php echo $ps['plans']['plus']['sdg']; ?>"
                min="0" step="1000" style="background:#0d2137;color:#00d97e;border:1px solid #1e3a2a;border-radius:6px;padding:6px 10px;font-weight:800;width:110px">
              SDG
            </td>
            <td style="padding:10px;color:#64748b">≈$<?php echo round($ps['plans']['plus']['sdg']/PricingEngine::getRate(),2); ?></td>
            <td style="padding:10px">
              <input type="number" name="credit_plus" value="<?php echo $ps['plans']['plus']['doc_credit_sdg']; ?>"
                min="0" step="1000" style="background:#0d2137;color:#f59e0b;border:1px solid #1e3a2a;border-radius:6px;padding:6px 8px;width:100px">
              SDG
            </td>
            <td style="padding:10px;color:#64748b">60</td>
            <td style="padding:10px;color:#64748b">5</td>
          </tr>
          <tr>
            <td style="padding:10px;font-weight:700">🔥 Pro</td>
            <td style="padding:10px">
              <input type="number" name="pro_sdg" value="<?php echo $ps['plans']['pro']['sdg']; ?>"
                min="0" step="1000" style="background:#0d2137;color:#f59e0b;border:1px solid #1e3a2a;border-radius:6px;padding:6px 10px;font-weight:800;width:110px">
              SDG
            </td>
            <td style="padding:10px;color:#64748b">≈$<?php echo round($ps['plans']['pro']['sdg']/PricingEngine::getRate(),2); ?></td>
            <td style="padding:10px">
              <input type="number" name="credit_pro" value="<?php echo $ps['plans']['pro']['doc_credit_sdg']; ?>"
                min="0" step="1000" style="background:#0d2137;color:#f59e0b;border:1px solid #1e3a2a;border-radius:6px;padding:6px 8px;width:100px">
              SDG
            </td>
            <td style="padding:10px;color:#64748b">200</td>
            <td style="padding:10px;color:#64748b">20</td>
          </tr>
        </tbody>
      </table>
    </div>
    <button type="submit" style="background:#00d97e;color:#000;border:none;border-radius:8px;padding:10px 24px;font-family:inherit;font-weight:800;cursor:pointer">✅ حفظ أسعار الاشتراكات</button>
  </form>
</div>

<?php elseif ($current_tab === 'pricing_documents'): ?>
<div class="fade-in" style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:4px">📄 أسعار إصدار الوثائق</h2>
  <p style="font-size:.78rem;color:#64748b;margin-bottom:16px">بالجنيه السوداني مباشرة — مستقلة عن سعر الصرف</p>
  <?php
  require_once __DIR__.'/engine/PricingEngine.php';
  if (!empty($_POST['action']) && $_POST['action']==='update_doc' && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $dt   = preg_replace('/[^a-z_]/','',$_POST['doc_type']??'');
    $free = max(0,(int)($_POST['price_free']??0));
    $plus = max(0,(int)($_POST['price_plus']??0));
    $pro  = max(0,(int)($_POST['price_pro']??0));
    try {
      db()->prepare("UPDATE document_prices SET price_free_sdg=?,price_plus_sdg=?,price_pro_sdg=? WHERE doc_type=?")
         ->execute([$free,$plus,$pro,$dt]);
      PricingEngine::flushCache();
      echo '<div class="badge-ok" style="padding:8px 14px;border-radius:8px;margin-bottom:14px;display:inline-block">✅ تم تحديث السعر</div>';
    } catch(Throwable $e) {}
  }
  try {
    $docPrices = db()->query("SELECT * FROM document_prices WHERE is_active=1 ORDER BY id")->fetchAll();
  } catch(Throwable $e) { $docPrices = []; }
  ?>
  <div class="engine-card">
    <table style="width:100%;border-collapse:collapse;font-size:.8rem" class="admin-table">
      <thead><tr style="background:#060d1a">
        <th style="padding:10px;text-align:right;color:#64748b">الوثيقة</th>
        <th style="padding:10px;text-align:right;color:#64748b">مجاني SDG</th>
        <th style="padding:10px;text-align:right;color:#64748b">Plus SDG</th>
        <th style="padding:10px;text-align:right;color:#64748b">Pro SDG</th>
        <th style="padding:10px;color:#64748b">حفظ</th>
      </tr></thead>
      <tbody>
      <?php foreach($docPrices as $dp): ?>
      <tr style="border-bottom:1px solid #1e3a2a">
        <td style="padding:10px;font-weight:600"><?php echo htmlspecialchars($dp['label_ar']); ?></td>
        <form method="POST" style="display:contents">
        <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
        <input type="hidden" name="action" value="update_doc">
        <input type="hidden" name="doc_type" value="<?php echo $dp['doc_type']; ?>">
        <td style="padding:6px"><input type="number" name="price_free" value="<?php echo $dp['price_free_sdg']; ?>" min="0" step="500" style="background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:5px 8px;width:90px"></td>
        <td style="padding:6px"><input type="number" name="price_plus" value="<?php echo $dp['price_plus_sdg']; ?>" min="0" step="500" style="background:#0d2137;color:#00d97e;border:1px solid #1e3a2a;border-radius:6px;padding:5px 8px;width:90px"></td>
        <td style="padding:6px"><input type="number" name="price_pro"  value="<?php echo $dp['price_pro_sdg'];  ?>" min="0" step="500" style="background:#0d2137;color:#f59e0b;border:1px solid #1e3a2a;border-radius:6px;padding:5px 8px;width:90px"></td>
        <td style="padding:6px"><button type="submit" class="badge-ok" style="border:none;cursor:pointer;padding:5px 12px;border-radius:6px">💾</button></td>
        </form>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php elseif ($current_tab === 'pricing_corporate'): ?>
<div class="fade-in" style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:4px">🏢 أسعار حلول الشركات</h2>
  <?php require_once __DIR__.'/engine/PricingEngine.php'; $ps=PricingEngine::getAll(); $rate=PricingEngine::getRate(); ?>
  <p style="font-size:.78rem;color:#64748b;margin-bottom:16px">مسعَّرة بالدولار — تُعرَض للشركات بالجنيه تلقائياً (سعر الصرف: <?php echo number_format($rate,0); ?> SDG/USD)</p>
  <?php
  if (!empty($_POST['action']) && $_POST['action']==='update_corp' && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $updates=[
      ['corp_starter_base_usd',(string)(float)($_POST['starter_usd']??99)],
      ['corp_business_base_usd',(string)(float)($_POST['business_usd']??249)],
      ['corp_scale_base_usd',(string)(float)($_POST['scale_usd']??599)],
    ];
    foreach($updates as[$k,$v]) PricingEngine::updateSetting($k,$v,(int)($_SESSION['admin']['id']??0));
    $ps=PricingEngine::getAll();
    echo '<div class="badge-ok" style="padding:8px 14px;border-radius:8px;margin-bottom:14px;display:inline-block">✅ تم تحديث أسعار الشركات</div>';
  }
  ?>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
    <input type="hidden" name="action" value="update_corp">
    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px;margin-bottom:16px">
      <?php foreach([
        ['Starter','starter',$ps['corporate']['starter']],
        ['Business','business',$ps['corporate']['business']],
        ['Scale','scale',$ps['corporate']['scale']],
      ] as [$name,$key,$pkg]): ?>
      <div class="engine-card" style="text-align:center">
        <div style="font-size:.85rem;font-weight:800;color:#e2e8f0;margin-bottom:10px"><?php echo $name; ?></div>
        <input type="number" name="<?php echo $key; ?>_usd" value="<?php echo $pkg['usd']; ?>"
          min="1" step="1" style="background:#060d1a;color:#f59e0b;border:1px solid #1e3a2a;border-radius:8px;padding:8px 12px;font-size:1.2rem;font-weight:900;width:120px;text-align:center">
        <div style="font-size:.72rem;color:#475569;margin-top:4px">USD/شهر</div>
        <div style="font-size:.85rem;color:#00d97e;margin-top:8px;font-weight:700"><?php echo number_format($pkg['sdg']); ?> SDG</div>
        <div style="font-size:.68rem;color:#475569">= <?php echo $pkg['usd']; ?> × <?php echo number_format($rate,0); ?></div>
        <div style="font-size:.72rem;color:#64748b;margin-top:6px"><?php echo $pkg['users']; ?> مستخدم</div>
      </div>
      <?php endforeach; ?>
    </div>
    <button type="submit" style="background:#00d97e;color:#000;border:none;border-radius:8px;padding:10px 24px;font-family:inherit;font-weight:800;cursor:pointer">✅ حفظ أسعار الشركات</button>
  </form>
  <p style="font-size:.75rem;color:#475569;margin-top:10px">⚡ تغيير سعر الصرف → الأسعار بالجنيه تتحدث تلقائياً في كل الصفحات</p>
</div>

<?php elseif ($current_tab === 'pricing_policies'): ?>
<div class="fade-in" style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">⚖️ السياسات المالية</h2>
  <?php
  require_once __DIR__.'/engine/PricingEngine.php';
  if (!empty($_POST['action']) && $_POST['action']==='update_policies' && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $fields = ['commission_rate','vat_rate','annual_discount_pct','refund_window_days',
               'pay_limit_free_daily_sdg','pay_limit_plus_daily_sdg','pay_limit_pro_daily_sdg','pay_limit_monthly_sdg'];
    foreach($fields as $f) {
      if(isset($_POST[$f])) PricingEngine::updateSetting($f,(string)$_POST[$f],(int)($_SESSION['admin']['id']??0));
    }
    echo '<div class="badge-ok" style="padding:8px 14px;border-radius:8px;margin-bottom:14px;display:inline-block">✅ تم حفظ السياسات</div>';
  }
  try {
    $policySettings = db()->query("SELECT setting_key,value,label_ar,unit FROM platform_settings WHERE category IN ('commission','limits') ORDER BY id")->fetchAll(PDO::FETCH_UNIQUE);
  } catch(Throwable $e){ $policySettings=[]; }
  function ps($key,$def=0,$s=[]) { return $s[$key]['value']??$def; }
  ?>
  <form method="POST">
    <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
    <input type="hidden" name="action" value="update_policies">
    <div class="engine-card" style="margin-bottom:14px">
      <h3>💸 العمولة والضرائب</h3>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:12px">
        <?php foreach([
          ['commission_rate','عمولة المنصة','%','0.10'],
          ['vat_rate','ضريبة القيمة المضافة','%','0'],
          ['annual_discount_pct','خصم العقد السنوي','%','20'],
          ['refund_window_days','فترة الاسترداد','يوم','7'],
        ] as [$key,$label,$unit,$def]): $val=$policySettings[$key]['value']??$def; ?>
        <div>
          <label style="font-size:.75rem;color:#64748b;display:block;margin-bottom:4px"><?php echo $label; ?></label>
          <div style="display:flex;align-items:center;gap:6px">
            <input type="number" name="<?php echo $key; ?>" value="<?php echo $val; ?>" step="0.01" min="0"
              style="background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:7px 10px;width:100px">
            <span style="color:#64748b;font-size:.82rem"><?php echo $unit; ?></span>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <div class="engine-card" style="margin-bottom:14px">
      <h3>🔒 حدود الدفع اليومية</h3>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:12px">
        <?php foreach([
          ['pay_limit_free_daily_sdg','مجاني (يومي)','20000'],
          ['pay_limit_plus_daily_sdg','Plus (يومي)','200000'],
          ['pay_limit_pro_daily_sdg','Pro (يومي)','500000'],
          ['pay_limit_monthly_sdg','الحد الشهري الكلي','1000000'],
        ] as [$key,$label,$def]): $val=$policySettings[$key]['value']??$def; ?>
        <div>
          <label style="font-size:.75rem;color:#64748b;display:block;margin-bottom:4px"><?php echo $label; ?></label>
          <div style="display:flex;align-items:center;gap:6px">
            <input type="number" name="<?php echo $key; ?>" value="<?php echo $val; ?>" step="1000" min="0"
              style="background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:7px 10px;width:130px">
            <span style="color:#64748b;font-size:.82rem">SDG</span>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <button type="submit" style="background:#00d97e;color:#000;border:none;border-radius:8px;padding:10px 24px;font-family:inherit;font-weight:800;cursor:pointer">✅ حفظ السياسات</button>
  </form>
</div>

<?php elseif ($current_tab === 'pricing_images'): ?>
<div class="fade-in" style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:4px">🖼️ أسعار توليد الصور</h2>
  <p style="font-size:.78rem;color:#64748b;margin-bottom:16px">3 أحجام × 3 باقات (مجاني/Plus/Pro) — يحفظ في image_prices</p>
  <?php
  require_once __DIR__.'/engine/PricingEngine.php';
  if (!empty($_POST['action']) && $_POST['action']==='update_image' && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $sk   = preg_replace('/[^a-z0-9x]/','',$_POST['size_key']??'');
    $free = max(0,(int)($_POST['price_free']??0));
    $plus = max(0,(int)($_POST['price_plus']??0));
    $pro  = max(0,(int)($_POST['price_pro']??0));
    try {
      $oldR = db()->prepare("SELECT price_plus_sdg FROM image_prices WHERE size_key=?");
      $oldR->execute([$sk]); $oldVal = $oldR->fetchColumn();
      db()->prepare("UPDATE image_prices SET price_free_sdg=?,price_plus_sdg=?,price_pro_sdg=? WHERE size_key=?")
         ->execute([$free,$plus,$pro,$sk]);
      PricingEngine::auditPriceChange('image', $sk, (string)$oldVal, (string)$plus, (int)($_SESSION['admin']['id']??0), 'admin update');
      echo '<div class="badge-ok" style="padding:8px 14px;border-radius:8px;margin-bottom:14px;display:inline-block">✅ تم تحديث السعر</div>';
    } catch(Throwable $e) { echo '<div class="badge-err" style="padding:8px 14px;border-radius:8px;margin-bottom:14px;display:inline-block">❌ '.htmlspecialchars($e->getMessage()).'</div>'; }
  }
  try { $imgs = db()->query("SELECT * FROM image_prices WHERE is_active=1 ORDER BY id")->fetchAll(); }
  catch(Throwable $e) { $imgs = []; echo '<div class="badge-warn" style="padding:8px;border-radius:8px;margin-bottom:14px">⚠️ شغّل migration_v23_pricing.sql أولاً</div>'; }
  ?>
  <div class="engine-card">
    <table style="width:100%;border-collapse:collapse;font-size:.8rem" class="admin-table">
      <thead><tr style="background:#060d1a">
        <th style="padding:10px;text-align:right;color:#64748b">الحجم</th>
        <th style="padding:10px;text-align:right;color:#64748b">التكلفة الحقيقية</th>
        <th style="padding:10px;text-align:right;color:#64748b">مجاني SDG</th>
        <th style="padding:10px;text-align:right;color:#64748b">Plus SDG</th>
        <th style="padding:10px;text-align:right;color:#64748b">Pro SDG</th>
        <th style="padding:10px;color:#64748b">حفظ</th>
      </tr></thead><tbody>
      <?php foreach($imgs as $im): $rate=4100; $costSdg=round(($im['base_cost_usd']??0)*$rate); ?>
      <tr style="border-bottom:1px solid #1e3a2a">
        <td style="padding:10px;font-weight:600"><?php echo htmlspecialchars($im['label_ar']); ?><br><span style="color:#64748b;font-size:.7rem"><?php echo htmlspecialchars($im['size_key']); ?></span></td>
        <td style="padding:10px;color:#94a3b8;font-size:.78rem">$<?php echo $im['base_cost_usd']; ?> ≈ <?php echo number_format($costSdg); ?> SDG</td>
        <form method="POST" style="display:contents">
        <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
        <input type="hidden" name="action" value="update_image">
        <input type="hidden" name="size_key" value="<?php echo $im['size_key']; ?>">
        <td style="padding:6px"><input type="number" name="price_free" value="<?php echo $im['price_free_sdg']; ?>" min="0" step="100" style="background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:5px 8px;width:90px"></td>
        <td style="padding:6px"><input type="number" name="price_plus" value="<?php echo $im['price_plus_sdg']; ?>" min="0" step="100" style="background:#0d2137;color:#00d97e;border:1px solid #1e3a2a;border-radius:6px;padding:5px 8px;width:90px"></td>
        <td style="padding:6px"><input type="number" name="price_pro"  value="<?php echo $im['price_pro_sdg'];  ?>" min="0" step="100" style="background:#0d2137;color:#f59e0b;border:1px solid #1e3a2a;border-radius:6px;padding:5px 8px;width:90px"></td>
        <td style="padding:6px"><button type="submit" class="badge-ok" style="border:none;cursor:pointer;padding:5px 12px;border-radius:6px">💾</button></td>
        </form>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php elseif ($current_tab === 'pricing_videos'): ?>
<div class="fade-in" style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:4px">🎬 أسعار توليد الفيديو</h2>
  <p style="font-size:.78rem;color:#64748b;margin-bottom:16px">4 مدد × 3 باقات — يحفظ في video_prices</p>
  <?php
  require_once __DIR__.'/engine/PricingEngine.php';
  if (!empty($_POST['action']) && $_POST['action']==='update_video' && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $dk   = preg_replace('/[^a-z0-9]/','',$_POST['duration_key']??'');
    $free = max(0,(int)($_POST['price_free']??0));
    $plus = max(0,(int)($_POST['price_plus']??0));
    $pro  = max(0,(int)($_POST['price_pro']??0));
    try {
      $oldR = db()->prepare("SELECT price_plus_sdg FROM video_prices WHERE duration_key=?");
      $oldR->execute([$dk]); $oldVal = $oldR->fetchColumn();
      db()->prepare("UPDATE video_prices SET price_free_sdg=?,price_plus_sdg=?,price_pro_sdg=? WHERE duration_key=?")
         ->execute([$free,$plus,$pro,$dk]);
      PricingEngine::auditPriceChange('video', $dk, (string)$oldVal, (string)$plus, (int)($_SESSION['admin']['id']??0), 'admin update');
      echo '<div class="badge-ok" style="padding:8px 14px;border-radius:8px;margin-bottom:14px;display:inline-block">✅ تم تحديث السعر</div>';
    } catch(Throwable $e) { echo '<div class="badge-err" style="padding:8px 14px;border-radius:8px;margin-bottom:14px;display:inline-block">❌ '.htmlspecialchars($e->getMessage()).'</div>'; }
  }
  try { $vids = db()->query("SELECT * FROM video_prices WHERE is_active=1 ORDER BY id")->fetchAll(); }
  catch(Throwable $e) { $vids = []; echo '<div class="badge-warn" style="padding:8px;border-radius:8px;margin-bottom:14px">⚠️ شغّل migration_v23_pricing.sql أولاً</div>'; }
  ?>
  <div class="engine-card">
    <table style="width:100%;border-collapse:collapse;font-size:.8rem" class="admin-table">
      <thead><tr style="background:#060d1a">
        <th style="padding:10px;text-align:right;color:#64748b">المدة</th>
        <th style="padding:10px;text-align:right;color:#64748b">التكلفة الحقيقية</th>
        <th style="padding:10px;text-align:right;color:#64748b">مجاني SDG</th>
        <th style="padding:10px;text-align:right;color:#64748b">Plus SDG</th>
        <th style="padding:10px;text-align:right;color:#64748b">Pro SDG</th>
        <th style="padding:10px;color:#64748b">حفظ</th>
      </tr></thead><tbody>
      <?php foreach($vids as $v): $rate=4100; $costSdg=round(($v['base_cost_usd']??0)*$rate); ?>
      <tr style="border-bottom:1px solid #1e3a2a">
        <td style="padding:10px;font-weight:600"><?php echo htmlspecialchars($v['label_ar']); ?><br><span style="color:#64748b;font-size:.7rem"><?php echo htmlspecialchars($v['duration_key']); ?></span></td>
        <td style="padding:10px;color:#94a3b8;font-size:.78rem">$<?php echo $v['base_cost_usd']; ?> ≈ <?php echo number_format($costSdg); ?> SDG</td>
        <form method="POST" style="display:contents">
        <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
        <input type="hidden" name="action" value="update_video">
        <input type="hidden" name="duration_key" value="<?php echo $v['duration_key']; ?>">
        <td style="padding:6px"><input type="number" name="price_free" value="<?php echo $v['price_free_sdg']; ?>" min="0" step="500" style="background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:5px 8px;width:100px"></td>
        <td style="padding:6px"><input type="number" name="price_plus" value="<?php echo $v['price_plus_sdg']; ?>" min="0" step="500" style="background:#0d2137;color:#00d97e;border:1px solid #1e3a2a;border-radius:6px;padding:5px 8px;width:100px"></td>
        <td style="padding:6px"><input type="number" name="price_pro"  value="<?php echo $v['price_pro_sdg'];  ?>" min="0" step="500" style="background:#0d2137;color:#f59e0b;border:1px solid #1e3a2a;border-radius:6px;padding:5px 8px;width:100px"></td>
        <td style="padding:6px"><button type="submit" class="badge-ok" style="border:none;cursor:pointer;padding:5px 12px;border-radius:6px">💾</button></td>
        </form>
      </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php elseif ($current_tab === 'ai_usage_dashboard'): ?>
<div class="fade-in" style="max-width:1100px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:4px">📊 لوحة استخدام AI</h2>
  <p style="font-size:.78rem;color:#64748b;margin-bottom:16px">tokens + التكلفة الحقيقية + الهامش — آخر 30 يوم</p>
  <?php
  $usage30 = ['total_calls'=>0,'total_tokens'=>0,'total_cost_usd'=>0,'total_cost_sdg'=>0,'total_charged_sdg'=>0];
  try {
    $r = db()->query("SELECT COUNT(*) as c, COALESCE(SUM(tokens_used),0) as t, COALESCE(SUM(cost_usd),0) as cu, COALESCE(SUM(cost_sdg),0) as cs FROM ai_usage WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)")->fetch();
    $usage30['total_calls'] = (int)$r['c'];
    $usage30['total_tokens'] = (int)$r['t'];
    $usage30['total_cost_usd'] = (float)$r['cu'];
    $usage30['total_cost_sdg'] = (int)$r['cs'];
  } catch(Throwable $e){}
  try {
    $byProvider = db()->query("SELECT provider, COUNT(*) as c, SUM(tokens_used) as t, SUM(cost_usd) as cu FROM ai_usage WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND provider IS NOT NULL GROUP BY provider")->fetchAll();
  } catch(Throwable $e){ $byProvider=[]; }
  try {
    $bySector = db()->query("SELECT service, COUNT(*) as c FROM ai_usage WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY service ORDER BY c DESC LIMIT 10")->fetchAll();
  } catch(Throwable $e){ $bySector=[]; }
  try {
    $topUsers = db()->query("SELECT u.name, u.email, COUNT(au.id) as calls, SUM(au.tokens_used) as t, SUM(au.cost_sdg) as s FROM ai_usage au JOIN users u ON u.id=au.user_id WHERE au.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY au.user_id ORDER BY calls DESC LIMIT 10")->fetchAll();
  } catch(Throwable $e){ $topUsers=[]; }
  ?>
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:16px">
    <div class="engine-card" style="text-align:center">
      <div style="font-size:1.6rem;font-weight:900;color:#00d97e"><?php echo number_format($usage30['total_calls']); ?></div>
      <div style="color:#64748b;font-size:.78rem">إجمالي الاستدعاءات</div>
    </div>
    <div class="engine-card" style="text-align:center">
      <div style="font-size:1.6rem;font-weight:900;color:#fbbf24"><?php echo number_format($usage30['total_tokens']); ?></div>
      <div style="color:#64748b;font-size:.78rem">إجمالي tokens</div>
    </div>
    <div class="engine-card" style="text-align:center">
      <div style="font-size:1.6rem;font-weight:900;color:#f87171">$<?php echo number_format($usage30['total_cost_usd'],2); ?></div>
      <div style="color:#64748b;font-size:.78rem">التكلفة بالدولار</div>
    </div>
    <div class="engine-card" style="text-align:center">
      <div style="font-size:1.6rem;font-weight:900;color:#a78bfa"><?php echo number_format($usage30['total_cost_sdg']); ?></div>
      <div style="color:#64748b;font-size:.78rem">التكلفة بالجنيه</div>
    </div>
  </div>

  <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:14px">
    <div class="engine-card">
      <h3>🔌 حسب المزود</h3>
      <table style="width:100%;font-size:.78rem;margin-top:8px"><thead><tr style="color:#64748b"><th style="text-align:right;padding:6px">المزود</th><th style="text-align:right;padding:6px">استدعاءات</th><th style="text-align:right;padding:6px">tokens</th><th style="text-align:right;padding:6px">USD</th></tr></thead><tbody>
      <?php foreach($byProvider as $p): ?>
      <tr style="border-bottom:1px solid #1e3a2a"><td style="padding:6px;font-weight:600"><?php echo htmlspecialchars($p['provider']??'-'); ?></td><td style="padding:6px"><?php echo number_format($p['c']); ?></td><td style="padding:6px"><?php echo number_format($p['t']); ?></td><td style="padding:6px;color:#f87171">$<?php echo number_format($p['cu'],2); ?></td></tr>
      <?php endforeach; if(!$byProvider): ?><tr><td colspan="4" style="padding:14px;text-align:center;color:#64748b">لا بيانات بعد</td></tr><?php endif; ?>
      </tbody></table>
    </div>
    <div class="engine-card">
      <h3>📂 حسب الخدمة</h3>
      <table style="width:100%;font-size:.78rem;margin-top:8px"><thead><tr style="color:#64748b"><th style="text-align:right;padding:6px">الخدمة</th><th style="text-align:right;padding:6px">استدعاءات</th></tr></thead><tbody>
      <?php foreach($bySector as $s): ?>
      <tr style="border-bottom:1px solid #1e3a2a"><td style="padding:6px"><?php echo htmlspecialchars($s['service']??'-'); ?></td><td style="padding:6px"><?php echo number_format($s['c']); ?></td></tr>
      <?php endforeach; if(!$bySector): ?><tr><td colspan="2" style="padding:14px;text-align:center;color:#64748b">لا بيانات</td></tr><?php endif; ?>
      </tbody></table>
    </div>
  </div>

  <div class="engine-card">
    <h3>👤 أكثر المستخدمين استهلاكاً</h3>
    <table style="width:100%;font-size:.78rem;margin-top:8px"><thead><tr style="color:#64748b"><th style="text-align:right;padding:6px">الاسم</th><th style="text-align:right;padding:6px">البريد</th><th style="text-align:right;padding:6px">استدعاءات</th><th style="text-align:right;padding:6px">tokens</th><th style="text-align:right;padding:6px">SDG مدفوع</th></tr></thead><tbody>
    <?php foreach($topUsers as $u): ?>
    <tr style="border-bottom:1px solid #1e3a2a"><td style="padding:6px;font-weight:600"><?php echo htmlspecialchars($u['name']); ?></td><td style="padding:6px;color:#94a3b8;font-size:.7rem"><?php echo htmlspecialchars($u['email']); ?></td><td style="padding:6px"><?php echo number_format($u['calls']); ?></td><td style="padding:6px"><?php echo number_format($u['t']); ?></td><td style="padding:6px;color:#00d97e"><?php echo number_format($u['s']); ?></td></tr>
    <?php endforeach; if(!$topUsers): ?><tr><td colspan="5" style="padding:14px;text-align:center;color:#64748b">لا بيانات</td></tr><?php endif; ?>
    </tbody></table>
  </div>
</div>

<?php elseif ($current_tab === 'corporate'): ?>
<div class="fade-in" style="max-width:1000px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">🏢 طلبات حلول الشركات</h2>
  <?php
  // Handle admin actions
  if (!empty($_POST['corp_action']) && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $inquiryId = (int)($_POST['inquiry_id']??0);
    $act = $_POST['corp_action'];
    if ($inquiryId > 0) {
      if ($act === 'accept') {
        db()->prepare("UPDATE corporate_inquiries SET status='negotiating',admin_notes=? WHERE id=?")->execute([trim($_POST['note']??''),$inquiryId]);
      } elseif ($act === 'reject') {
        db()->prepare("UPDATE corporate_inquiries SET status='lost',admin_notes=? WHERE id=?")->execute([trim($_POST['note']??''),$inquiryId]);
      } elseif ($act === 'contact') {
        db()->prepare("UPDATE corporate_inquiries SET status='contact_attempted',admin_notes=? WHERE id=?")->execute([trim($_POST['note']??''),$inquiryId]);
        // Insert CRM timeline
        db()->prepare("INSERT INTO crm_timeline (user_id,event_type,summary) SELECT contact_email,?,? FROM corporate_inquiries WHERE id=?")->execute(['corporate_contact',trim($_POST['note']??''),$inquiryId]);
      }
    }
  }
  try {
    $inquiries = db()->query("SELECT * FROM corporate_inquiries ORDER BY created_at DESC LIMIT 50")->fetchAll();
    $stats_new = db()->query("SELECT COUNT(*) FROM corporate_inquiries WHERE status='submitted'")->fetchColumn();
    $stats_neg = db()->query("SELECT COUNT(*) FROM corporate_inquiries WHERE status='negotiating'")->fetchColumn();
    $stats_won = db()->query("SELECT COUNT(*) FROM corporate_inquiries WHERE status='won'")->fetchColumn();
  } catch(Throwable $e){ $inquiries=[]; $stats_new=$stats_neg=$stats_won=0; }
  ?>
  <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:18px">
    <div class="stat" style="text-align:center"><div style="font-size:1.6rem;font-weight:900;color:#f59e0b"><?php echo $stats_new; ?></div><div style="font-size:.7rem;color:#64748b">جديد</div></div>
    <div class="stat" style="text-align:center"><div style="font-size:1.6rem;font-weight:900;color:#a78bfa"><?php echo $stats_neg; ?></div><div style="font-size:.7rem;color:#64748b">قيد التفاوض</div></div>
    <div class="stat" style="text-align:center"><div style="font-size:1.6rem;font-weight:900;color:#00d97e"><?php echo $stats_won; ?></div><div style="font-size:.7rem;color:#64748b">مُنجَز</div></div>
  </div>
  <?php if(empty($inquiries)): ?>
  <div class="engine-card" style="text-align:center;padding:40px">
    <div style="font-size:2rem;margin-bottom:12px">🏢</div>
    <p style="color:#64748b">لا يوجد طلبات بعد. ستظهر هنا عندما تُقدِّم الشركات طلباتها.</p>
  </div>
  <?php else: foreach($inquiries as $inq): ?>
  <div class="engine-card fade-in" style="margin-bottom:14px">
    <div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:8px">
      <div>
        <div style="font-weight:800;font-size:.95rem;color:#e2e8f0"><?php echo htmlspecialchars($inq['org_name']); ?></div>
        <div style="font-size:.75rem;color:#64748b;margin-top:3px">
          <?php echo htmlspecialchars($inq['org_sector']??''); ?> |
          <?php echo htmlspecialchars($inq['employees_count']??''); ?> موظف |
          <?php echo $inq['ref_no']??$inq['id']; ?>
        </div>
      </div>
      <span class="badge-<?php echo match($inq['status']){
        'submitted','draft'=>'warn','negotiating','won'=>'ok',default=>'err'}; ?>">
        <?php echo match($inq['status']??''){
          'draft'=>'مسودة','submitted'=>'جديد','analyzing'=>'تحليل',
          'proposal_ready'=>'عرض جاهز','contact_attempted'=>'تم التواصل',
          'negotiating'=>'قيد التفاوض','won'=>'مُنجَز','lost'=>'مرفوض',
          default=>$inq['status']
        }; ?>
      </span>
    </div>
    <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin:10px 0;font-size:.75rem;color:#94a3b8">
      <div>📧 <?php echo htmlspecialchars($inq['contact_email']??''); ?></div>
      <div>📞 <?php echo htmlspecialchars($inq['contact_phone']??''); ?></div>
      <div>💰 <?php echo $inq['estimated_cost_sdg']?number_format($inq['estimated_cost_sdg']).' SDG':'—'; ?></div>
    </div>
    <?php if($inq['admin_notes']): ?>
    <div style="font-size:.75rem;color:#64748b;margin-bottom:8px">ملاحظة: <?php echo htmlspecialchars($inq['admin_notes']); ?></div>
    <?php endif; ?>
    <form method="POST" style="display:flex;gap:8px;flex-wrap:wrap;margin-top:10px">
      <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
      <input type="hidden" name="inquiry_id" value="<?php echo $inq['id']; ?>">
      <input type="text" name="note" placeholder="ملاحظة..."
        style="flex:1;min-width:200px;background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:6px 10px;font-family:inherit;font-size:.78rem">
      <button type="submit" name="corp_action" value="contact" class="badge-ok" style="border:none;cursor:pointer;padding:6px 14px;border-radius:6px;font-family:inherit">📞 تواصل</button>
      <button type="submit" name="corp_action" value="accept"  class="badge-ok" style="border:none;cursor:pointer;padding:6px 14px;border-radius:6px;font-family:inherit">✅ قبول</button>
      <button type="submit" name="corp_action" value="reject"  class="badge-err" style="border:none;cursor:pointer;padding:6px 14px;border-radius:6px;font-family:inherit">❌ رفض</button>
    </form>
  </div>
  <?php endforeach; endif; ?>
</div>


<?php elseif ($current_tab === 'suggestions'): ?>
<div class="fade-in" style="max-width:1000px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">💡 مقترحات المستخدمين</h2>
  <?php
  // Handle admin action
  if (!empty($_POST['sug_action']) && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $sugId  = (int)($_POST['sug_id']??0);
    $act    = $_POST['sug_action'];
    $reply  = mb_substr(trim($_POST['admin_reply']??''),0,500);
    $note   = mb_substr(trim($_POST['admin_notes']??''),0,500);
    if ($sugId > 0) {
      $status = match($act) {
        'accept'=>'accepted','reject'=>'rejected',
        'implement'=>'implemented','backlog'=>'under_review',
        'duplicate'=>'duplicate', default=>null
      };
      if ($status) {
        db()->prepare("UPDATE user_suggestions SET status=?,admin_notes=?,admin_reply=? WHERE id=?")
           ->execute([$status,$note,$reply,$sugId]);
        // Award points on implementation
        if ($status==='implemented') {
          $uid = db()->query("SELECT user_id FROM user_suggestions WHERE id=$sugId")->fetchColumn();
          if ($uid) {
            require_once __DIR__.'/engine/SuggestionsAgent.php';
            SuggestionsAgent::awardPoints((int)$uid,'suggestion_implemented');
            db()->prepare("INSERT INTO notifications (user_id,type,title,body) VALUES (?,?,?,?)")
               ->execute([$uid,'suggestion_implemented','🚀 تم تنفيذ اقتراحك!','شكراً على مشاركتك في تطوير سودانا — تم تنفيذ اقتراحك!']);
          }
        }
      }
    }
  }

  // Stats
  try {
    $stats_pending  = db()->query("SELECT COUNT(*) FROM user_suggestions WHERE status='pending'")->fetchColumn();
    $stats_urgent   = db()->query("SELECT COUNT(*) FROM user_suggestions WHERE priority_label='urgent'")->fetchColumn();
    $stats_accepted = db()->query("SELECT COUNT(*) FROM user_suggestions WHERE status='accepted'")->fetchColumn();
    $stats_done     = db()->query("SELECT COUNT(*) FROM user_suggestions WHERE status='implemented'")->fetchColumn();
    $suggestions    = db()->query(
      "SELECT us.*, u.full_name FROM user_suggestions us
       LEFT JOIN users u ON us.user_id=u.id
       ORDER BY CASE us.priority_label WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 ELSE 3 END,
                us.votes_count DESC LIMIT 50"
    )->fetchAll();
  } catch(Throwable $e){ $suggestions=[]; $stats_pending=$stats_urgent=$stats_accepted=$stats_done=0; }
  ?>
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin-bottom:18px">
    <div class="stat" style="text-align:center"><div style="font-size:1.5rem;font-weight:900;color:#f59e0b"><?php echo $stats_pending; ?></div><div style="font-size:.7rem;color:#64748b">بانتظار المراجعة</div></div>
    <div class="stat" style="text-align:center"><div style="font-size:1.5rem;font-weight:900;color:#ef4444"><?php echo $stats_urgent; ?></div><div style="font-size:.7rem;color:#64748b">عاجل</div></div>
    <div class="stat" style="text-align:center"><div style="font-size:1.5rem;font-weight:900;color:#00d97e"><?php echo $stats_accepted; ?></div><div style="font-size:.7rem;color:#64748b">مقبول</div></div>
    <div class="stat" style="text-align:center"><div style="font-size:1.5rem;font-weight:900;color:#a78bfa"><?php echo $stats_done; ?></div><div style="font-size:.7rem;color:#64748b">منفَّذ</div></div>
  </div>

  <?php if(empty($suggestions)): ?>
  <div class="engine-card" style="text-align:center;padding:32px"><div style="font-size:2rem">💡</div><p style="color:#64748b;margin-top:8px">لا مقترحات بعد</p></div>
  <?php else: foreach($suggestions as $sug):
    $typeIcon = ['improvement'=>'💡','bug'=>'🐛','solution'=>'🔧','new_service'=>'🌟','positive'=>'👍'][$sug['type']]??'💡';
    $priColor = ['urgent'=>'#ef4444','high'=>'#f59e0b','medium'=>'#00d97e','low'=>'#64748b'][$sug['priority_label']]??'#64748b';
    $staColor = ['pending'=>'warn','under_review'=>'warn','accepted'=>'ok','implemented'=>'ok','rejected'=>'err','duplicate'=>'err'][$sug['status']]??'warn';
  ?>
  <div class="engine-card fade-in" style="margin-bottom:12px">
    <div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:6px;margin-bottom:8px">
      <div>
        <span style="font-size:.72rem;color:#64748b"><?php echo $typeIcon; ?> <?php echo htmlspecialchars($sug['service']??''); ?> | <?php echo $sug['ref_no']??$sug['id']; ?></span>
        <div style="font-weight:800;font-size:.92rem;color:#e2e8f0;margin-top:3px"><?php echo htmlspecialchars($sug['title']); ?></div>
      </div>
      <div style="display:flex;gap:6px;align-items:flex-start">
        <?php if($sug['priority_label']): ?>
        <span style="color:<?php echo $priColor; ?>;font-size:.75rem;font-weight:700"><?php echo strtoupper($sug['priority_label']??''); ?></span>
        <?php endif; ?>
        <span class="badge-<?php echo $staColor; ?>"><?php echo match($sug['status']??''){
          'pending'=>'انتظار','under_review'=>'قيد المراجعة','accepted'=>'مقبول',
          'implemented'=>'منفَّذ','rejected'=>'مرفوض','duplicate'=>'مكرر',default=>$sug['status']
        }; ?></span>
      </div>
    </div>
    <p style="font-size:.78rem;color:#94a3b8;margin-bottom:8px;line-height:1.5"><?php echo htmlspecialchars(mb_substr($sug['description']??'',0,200)); ?>...</p>
    <?php if($sug['ai_summary']): ?>
    <div style="background:#0d2137;border-radius:8px;padding:8px 12px;margin-bottom:8px;font-size:.75rem;color:#6ee7b7">
      🤖 <?php echo htmlspecialchars($sug['ai_summary']); ?>
    </div>
    <?php endif; ?>
    <div style="display:flex;gap:12px;font-size:.7rem;color:#64748b;margin-bottom:10px">
      <span>🔼 <?php echo $sug['votes_count']; ?> صوت</span>
      <?php if($sug['affected_estimate']): ?><span>👥 ~<?php echo number_format($sug['affected_estimate']); ?> مستخدم</span><?php endif; ?>
      <?php if($sug['effort_level']): ?><span>⚡ <?php echo $sug['effort_level']; ?> effort</span><?php endif; ?>
      <?php if($sug['team_responsible']): ?><span>👷 <?php echo $sug['team_responsible']; ?></span><?php endif; ?>
      <span>📅 <?php echo substr($sug['created_at'],0,10); ?></span>
    </div>
    <form method="POST" style="display:flex;gap:6px;flex-wrap:wrap;align-items:center">
      <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
      <input type="hidden" name="sug_id" value="<?php echo $sug['id']; ?>">
      <input type="text" name="admin_reply" placeholder="رد للمستخدم..."
        style="flex:1;min-width:160px;background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:6px 10px;font-family:inherit;font-size:.75rem">
      <input type="text" name="admin_notes" placeholder="ملاحظة داخلية..."
        style="flex:1;min-width:120px;background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:6px 10px;font-family:inherit;font-size:.75rem">
      <button type="submit" name="sug_action" value="accept"    class="badge-ok"  style="border:none;cursor:pointer;padding:5px 10px;border-radius:6px;font-family:inherit">✅ قبول</button>
      <button type="submit" name="sug_action" value="implement" class="badge-ok"  style="border:none;cursor:pointer;padding:5px 10px;border-radius:6px;font-family:inherit;background:#a78bfa;color:#fff">🚀 منفَّذ</button>
      <button type="submit" name="sug_action" value="backlog"   class="badge-warn" style="border:none;cursor:pointer;padding:5px 10px;border-radius:6px;font-family:inherit">📋 Backlog</button>
      <button type="submit" name="sug_action" value="reject"    class="badge-err" style="border:none;cursor:pointer;padding:5px 10px;border-radius:6px;font-family:inherit">❌ رفض</button>
    </form>
  </div>
  <?php endforeach; endif; ?>
</div>

<?php elseif ($current_tab === 'fraud'): ?>
<div class="fade-in" style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">🛡️ مكافحة الاحتيال</h2>
  <?php try {
    $flags = db()->query("SELECT ff.*, u.full_name FROM fraud_flags ff LEFT JOIN users u ON ff.user_id=u.id ORDER BY ff.created_at DESC LIMIT 50")->fetchAll();
    $unreviewed = db()->query("SELECT COUNT(*) FROM fraud_flags WHERE reviewed=0")->fetchColumn();
  } catch(Throwable $e){ $flags=[]; $unreviewed=0; } ?>
  <div style="margin-bottom:14px"><span class="badge-warn"><?php echo $unreviewed; ?> غير مراجَع</span></div>
  <?php if(empty($flags)): ?>
  <div class="engine-card" style="text-align:center;padding:24px;color:#64748b">✅ لا بلاغات احتيال حتى الآن</div>
  <?php else: foreach($flags as $f): ?>
  <div class="engine-card" style="margin-bottom:10px">
    <div style="display:flex;justify-content:space-between">
      <div>
        <span class="badge-<?php echo $f['severity']==='critical'||$f['severity']==='high'?'err':'warn'; ?>"><?php echo $f['severity']; ?></span>
        <span style="font-size:.78rem;color:#e2e8f0;margin-right:8px"><?php echo htmlspecialchars($f['flag_type']); ?></span>
      </div>
      <span style="font-size:.7rem;color:#64748b"><?php echo substr($f['created_at'],0,16); ?></span>
    </div>
    <div style="font-size:.75rem;color:#94a3b8;margin-top:6px">
      المستخدم: <?php echo htmlspecialchars($f['full_name']??'مجهول'); ?> | IP: <?php echo substr($f['ip_hash']??'',0,12); ?>...
    </div>
  </div>
  <?php endforeach; endif; ?>
</div>

<?php elseif ($current_tab === 'settlement'): ?>
<?php // Original settlement content is already handled in admin.php via $tab variable ?>
<?php elseif ($current_tab === 'suggestions'): ?>
<div class="fade-in" style="max-width:1000px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">💡 مقترحات المستخدمين</h2>
  <?php
  if (!empty($_POST['sug_action']) && !empty($_POST['csrf']) && $_POST['csrf']===$csrf) {
    $sugId  = (int)($_POST['sug_id']??0);
    $act    = $_POST['sug_action'];
    $note   = mb_substr(trim($_POST['admin_note']??''),0,500);
    $reply  = mb_substr(trim($_POST['admin_reply']??''),0,1000);
    if ($sugId > 0) {
      $smap = ['accept'=>'accepted','reject'=>'rejected','implement'=>'implemented','review'=>'under_review'];
      if (isset($smap[$act])) {
        db()->prepare("UPDATE user_suggestions SET status=?,admin_notes=?,admin_reply=? WHERE id=?")->execute([$smap[$act],$note,$reply,$sugId]);
        if ($act==='implement') {
          db()->prepare("INSERT INTO notifications (user_id,type,title,body) SELECT user_id,'suggestion_implemented','✅ تم تنفيذ اقتراحك!','شكراً لمساهمتك' FROM user_suggestions WHERE id=? AND user_id IS NOT NULL")->execute([$sugId]);
          db()->prepare("UPDATE users SET achievement_points=achievement_points+200 WHERE id=(SELECT user_id FROM user_suggestions WHERE id=? AND user_id IS NOT NULL)")->execute([$sugId]);
        }
      }
    }
  }
  try {
    $sp = ['pending'=>db()->query("SELECT COUNT(*) FROM user_suggestions WHERE status='pending'")->fetchColumn(),'urgent'=>db()->query("SELECT COUNT(*) FROM user_suggestions WHERE priority_label='urgent'")->fetchColumn(),'impl'=>db()->query("SELECT COUNT(*) FROM user_suggestions WHERE status='implemented'")->fetchColumn(),'total'=>db()->query("SELECT COUNT(*) FROM user_suggestions")->fetchColumn()];
    $sugs = db()->query("SELECT us.*,u.full_name as uname FROM user_suggestions us LEFT JOIN users u ON us.user_id=u.id ORDER BY us.priority_score DESC,us.votes_count DESC LIMIT 50")->fetchAll();
  } catch(Throwable $e){$sp=['pending'=>0,'urgent'=>0,'impl'=>0,'total'=>0];$sugs=[];}
  ?>
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:18px">
    <div class="stat" style="text-align:center"><div style="font-size:1.5rem;font-weight:900;color:#f59e0b"><?php echo $sp['pending']; ?></div><div style="font-size:.68rem;color:#64748b">معلَّق</div></div>
    <div class="stat" style="text-align:center"><div style="font-size:1.5rem;font-weight:900;color:#ef4444"><?php echo $sp['urgent']; ?></div><div style="font-size:.68rem;color:#64748b">عاجل</div></div>
    <div class="stat" style="text-align:center"><div style="font-size:1.5rem;font-weight:900;color:#00d97e"><?php echo $sp['impl']; ?></div><div style="font-size:.68rem;color:#64748b">مُنفَّذ</div></div>
    <div class="stat" style="text-align:center"><div style="font-size:1.5rem;font-weight:900;color:#94a3b8"><?php echo $sp['total']; ?></div><div style="font-size:.68rem;color:#64748b">إجمالي</div></div>
  </div>
  <?php if(empty($sugs)): ?>
  <div class="engine-card" style="text-align:center;padding:30px"><p style="color:#64748b">لا مقترحات بعد — شجِّع المستخدمين على <a href="/app/suggestions.php" style="color:#00d97e">صفحة المقترحات</a></p></div>
  <?php else: foreach($sugs as $s): ?>
  <div class="engine-card" style="margin-bottom:10px;border-right:3px solid <?php echo match($s['priority_label']??''){  'urgent'=>'#ef4444','high'=>'#f59e0b','medium'=>'#00d97e',default=>'#475569'}; ?>">
    <div style="font-weight:700;color:#e2e8f0;font-size:.88rem;margin-bottom:4px"><?php echo ['improvement'=>'💡','bug'=>'🐛','solution'=>'🔧','new_service'=>'🌟','positive'=>'❤️'][$s['type']??'']??'📝'; ?> <?php echo htmlspecialchars(mb_substr($s['title']??'',0,80)); ?></div>
    <div style="font-size:.7rem;color:#64748b;margin-bottom:6px"><?php echo htmlspecialchars($s['service']??''); ?> | 🔼<?php echo $s['votes_count']??0; ?> | Score:<?php echo number_format($s['priority_score']??0,2); ?> | <?php echo htmlspecialchars($s['uname']??'مجهول'); ?></div>
    <?php if($s['ai_summary']??''): ?><div style="font-size:.72rem;color:#94a3b8;font-style:italic;margin-bottom:6px">🤖 <?php echo htmlspecialchars(mb_substr($s['ai_summary'],0,120)); ?></div><?php endif; ?>
    <form method="POST" style="display:flex;gap:5px;flex-wrap:wrap;margin-top:8px">
      <input type="hidden" name="csrf" value="<?php echo $csrf; ?>">
      <input type="hidden" name="sug_id" value="<?php echo $s['id']; ?>">
      <input name="admin_note"  placeholder="ملاحظة..." style="flex:1;min-width:120px;background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:4px 8px;font-family:inherit;font-size:.72rem">
      <input name="admin_reply" placeholder="رد للمستخدم..." style="flex:1;min-width:120px;background:#0d2137;color:#e2e8f0;border:1px solid #1e3a2a;border-radius:6px;padding:4px 8px;font-family:inherit;font-size:.72rem">
      <button name="sug_action" value="review"    class="badge-warn" style="border:none;cursor:pointer;padding:4px 10px;border-radius:6px;font-family:inherit">🔍</button>
      <button name="sug_action" value="accept"    class="badge-ok"   style="border:none;cursor:pointer;padding:4px 10px;border-radius:6px;font-family:inherit">✅</button>
      <button name="sug_action" value="implement" style="background:#064e3b;color:#34d399;border:none;cursor:pointer;padding:4px 10px;border-radius:6px;font-family:inherit">🚀</button>
      <button name="sug_action" value="reject"    class="badge-err"  style="border:none;cursor:pointer;padding:4px 10px;border-radius:6px;font-family:inherit">❌</button>
    </form>
  </div>
  <?php endforeach; endif; ?>
</div>

<?php elseif ($current_tab === 'fraud'): ?>
<div class="fade-in" style="max-width:900px">
  <h2 style="font-size:1.1rem;font-weight:900;color:#00d97e;margin-bottom:16px">🚨 مكافحة الاحتيال</h2>
  <?php try { $fflags=db()->query("SELECT ff.*,u.full_name FROM fraud_flags ff LEFT JOIN users u ON ff.user_id=u.id ORDER BY ff.created_at DESC LIMIT 30")->fetchAll(); $fc=db()->query("SELECT COUNT(*) FROM fraud_flags WHERE status='active'")->fetchColumn(); } catch(Throwable $e){$fflags=[];$fc=0;} ?>
  <div style="margin-bottom:14px"><span class="badge-err"><?php echo $fc; ?> نشط</span></div>
  <?php if(empty($fflags)): ?><div class="engine-card" style="text-align:center;padding:30px"><div style="font-size:2rem">✅</div><p style="color:#64748b;margin-top:8px">النظام سليم — لا بلاغات</p></div>
  <?php else: ?><div class="engine-card" style="padding:0;overflow:hidden"><table style="width:100%;border-collapse:collapse;font-size:.76rem"><thead><tr style="background:#060d1a"><th style="padding:10px;color:#64748b;text-align:right">المستخدم</th><th style="padding:10px;color:#64748b;text-align:right">النوع</th><th style="padding:10px;color:#64748b;text-align:right">الخطورة</th><th style="padding:10px;color:#64748b;text-align:right">التاريخ</th></tr></thead><tbody>
  <?php foreach($fflags as $f): ?><tr style="border-bottom:1px solid #1e3a2a"><td style="padding:8px"><?php echo htmlspecialchars($f['full_name']??'مجهول'); ?></td><td style="padding:8px;color:#f59e0b"><?php echo htmlspecialchars($f['flag_type']??''); ?></td><td style="padding:8px"><span class="badge-<?php echo in_array($f['severity']??'',['high','critical'])?'err':'warn'; ?>"><?php echo $f['severity']??''; ?></span></td><td style="padding:8px;color:#64748b;font-size:.7rem"><?php echo substr($f['created_at']??'',0,10); ?></td></tr>
  <?php endforeach; ?></tbody></table></div>
  <?php endif; ?>
</div>

<?php endif; ?>

<script>
// Highlight active sidebar link
// Highlight active sidebar link
const tab = new URLSearchParams(location.search).get('tab') || 'home';
document.querySelectorAll('.sb-link').forEach(a => {
  const t = new URLSearchParams(a.search).get('tab');
  if (t === tab) a.classList.add('active');
});
// Responsive sidebar toggle
function toggleSidebar(){
  const sb = document.getElementById('admin-sidebar');
  sb.style.display = sb.style.display === 'none' ? '' : 'none';
}
</script>
</div></div><!-- end admin-main + admin-layout -->

        <!-- ══════════════════════════════════════════════════
             SUDANNA PAY ADMIN PANEL
             ══════════════════════════════════════════════════ -->
        <div id="sdpay-panel" style="display:none">
          <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;margin-bottom:20px">
            <div class="stat-card" id="sp-total-vol">
              <div style="font-size:.75rem;color:var(--muted)">حجم اليوم</div>
              <div style="font-size:1.4rem;font-weight:900">جاري...</div>
            </div>
            <div class="stat-card" id="sp-txn-count">
              <div style="font-size:.75rem;color:var(--muted)">معاملات اليوم</div>
              <div style="font-size:1.4rem;font-weight:900">—</div>
            </div>
            <div class="stat-card" id="sp-revenue">
              <div style="font-size:.75rem;color:var(--muted)">إيرادات اليوم</div>
              <div style="font-size:1.4rem;font-weight:900">—</div>
            </div>
            <div class="stat-card" id="sp-wallets">
              <div style="font-size:.75rem;color:var(--muted)">إجمالي المحافظ</div>
              <div style="font-size:1.4rem;font-weight:900">—</div>
            </div>
            <div class="stat-card" id="sp-disputes">
              <div style="font-size:.75rem;color:var(--muted);color:#dc2626">نزاعات مفتوحة</div>
              <div style="font-size:1.4rem;font-weight:900;color:#dc2626">—</div>
            </div>
            <div class="stat-card" id="sp-pending">
              <div style="font-size:.75rem;color:var(--muted)">معاملات معلقة</div>
              <div style="font-size:1.4rem;font-weight:900">—</div>
            </div>
          </div>

          <h3 style="margin:16px 0 8px;font-size:.95rem">&#128196; آخر المعاملات</h3>
          <div id="sp-txn-list" style="background:#0d1117;border-radius:10px;padding:12px;font-family:monospace;font-size:.78rem;max-height:300px;overflow-y:auto">جاري التحميل...</div>

          <h3 style="margin:16px 0 8px;font-size:.95rem;color:#dc2626">&#9888; النزاعات المفتوحة</h3>
          <div id="sp-disputes-list" style="background:#1a0a0a;border-radius:10px;padding:12px;font-size:.82rem;max-height:250px;overflow-y:auto">جاري التحميل...</div>

          <h3 style="margin:16px 0 8px;font-size:.95rem;color:#d97706">&#128736; تقارير AML</h3>
          <div id="sp-aml-list" style="background:#1a1500;border-radius:10px;padding:12px;font-size:.82rem;max-height:200px;overflow-y:auto">جاري التحميل...</div>
        </div>

        <script>
        async function loadPayPanel() {
          try {
            const [dash, txns, disputes, aml] = await Promise.all([
              fetch('/api/accounting/dashboard.php').then(r=>r.json()),
              fetch('/api/pay/history.php?limit=20&all=1').then(r=>r.json()),
              fetch('/api/pay/dispute.php?action=list').then(r=>r.json()),
              fetch('/api/admin/aml.php').then(r=>r.json()).catch(()=>({data:[]})),
            ]);
            const d = dash.data || {};
            document.getElementById('sp-total-vol').querySelector('div:last-child').textContent = 
              Number(d.txn_volume_sdg||0).toLocaleString('ar-SA') + ' SDG';
            document.getElementById('sp-txn-count').querySelector('div:last-child').textContent = d.txn_count||0;
            document.getElementById('sp-revenue').querySelector('div:last-child').textContent = 
              Number(d.revenue_sdg||0).toLocaleString('ar-SA') + ' SDG';
            document.getElementById('sp-wallets').querySelector('div:last-child').textContent = 
              Number(d.total_wallets_sdg||0).toLocaleString('ar-SA') + ' SDG';
            document.getElementById('sp-disputes').querySelector('div:last-child').textContent = d.open_disputes||0;
            document.getElementById('sp-pending').querySelector('div:last-child').textContent = d.pending_reconcile||0;

            const tl = txns.data || txns.transactions || [];
            document.getElementById('sp-txn-list').innerHTML = tl.length ? 
              tl.map(t => `<div style="border-bottom:1px solid #222;padding:4px 0">
                <span style="color:#${t.status==='completed'?'3fb950':t.status==='failed'?'f87171':'fbbf24'}">${t.status}</span>
                &nbsp;${t.txn_ref} &nbsp;|&nbsp; ${Number(t.amount_sdg||0).toLocaleString()} SDG
                &nbsp;|&nbsp; ${t.type} &nbsp;|&nbsp; ${(t.created_at||'').substring(0,16)}
              </div>`).join('') : '<p style="color:#666">لا معاملات</p>';

            const dl = disputes.disputes || disputes.data || [];
            document.getElementById('sp-disputes-list').innerHTML = dl.length ?
              dl.map(d => `<div style="border-bottom:1px solid #333;padding:6px 0">
                <span style="color:#f87171;font-weight:700">#${d.id}</span> ${d.subject||''} 
                &nbsp;|&nbsp; <span style="color:#fbbf24">${d.priority||'normal'}</span>
                &nbsp;|&nbsp; ${(d.created_at||'').substring(0,10)}
              </div>`).join('') : '<p style="color:#666">لا نزاعات مفتوحة ✅</p>';
          } catch(e) {
            console.error('Pay panel error:', e);
          }
        }
        document.addEventListener('DOMContentLoaded', () => {
          const btn = document.querySelector('[data-tab="sdpay"]') || document.querySelector('button[onclick*="sdpay"]');
          if (btn) btn.addEventListener('click', loadPayPanel);
          // Auto-load if pay panel visible
          setTimeout(() => { if(document.getElementById('sdpay-panel')?.offsetParent) loadPayPanel(); }, 500);
        });
        </script>

</body>
</html>
