<?php
/**
 * الملف الشخصي للطبيب
 */
$accountInfo = null;
try {
    $stmt = $db->prepare('SELECT da.*, d.full_name, d.specialty, d.phone AS doctor_phone, d.clinic_name, t.name AS tenant_name FROM doctor_accounts da JOIN doctors d ON d.id = da.doctor_id AND d.tenant_id = da.tenant_id JOIN tenants t ON t.id = da.tenant_id WHERE da.id = ?');
    $stmt->execute([$doctorAuth->accountId()]);
    $accountInfo = $stmt->fetch();
} catch (Throwable $e) {}

$myStats = ['patients' => 0, 'orders' => 0, 'notes' => 0, 'appointments' => 0, 'reminders' => 0, 'critical_results' => 0];
$activityLog = [];
$weeklyStats = ['orders' => [], 'patients' => [], 'appointments' => []];
$monthlyStats = ['orders' => 0, 'patients' => 0, 'notes' => 0];

try {
    $stmt = $db->prepare("SELECT COUNT(DISTINCT patient_id) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ?");
    $stmt->execute([$doctorId, $tenantId]);
    $myStats['patients'] = (int)$stmt->fetchColumn();
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ?");
    $stmt->execute([$doctorId, $tenantId]);
    $myStats['orders'] = (int)$stmt->fetchColumn();
    $stmt = $db->prepare("SELECT COUNT(*) FROM patient_medical_notes WHERE doctor_account_id = ?");
    $stmt->execute([$doctorAuth->accountId()]);
    $myStats['notes'] = (int)$stmt->fetchColumn();
    
    // إحصائيات المواعيد
    try {
        $db->query('SELECT id FROM doctor_appointments LIMIT 1');
        $stmt = $db->prepare("SELECT COUNT(*) FROM doctor_appointments WHERE doctor_account_id = ?");
        $stmt->execute([$doctorAuth->accountId()]);
        $myStats['appointments'] = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {}
    
    // إحصائيات التذكيرات
    try {
        $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1');
        $stmt = $db->prepare("SELECT COUNT(*) FROM doctor_follow_up_reminders WHERE doctor_account_id = ? AND is_done = 0");
        $stmt->execute([$doctorAuth->accountId()]);
        $myStats['reminders'] = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {}
    
    // النتائج الحرجة
    try {
        $stmt = $db->prepare("SELECT COUNT(*) FROM results r 
            JOIN order_items oi ON oi.id = r.order_item_id 
            JOIN lab_orders o ON o.id = oi.order_id 
            WHERE o.doctor_id = ? AND o.tenant_id = ? AND r.flag = 'C' 
            AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
        $stmt->execute([$doctorId, $tenantId]);
        $myStats['critical_results'] = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {}
    
    // إحصائيات الأسبوع (آخر 7 أيام) - طلبات التحاليل + المواعيد
    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ? AND DATE(order_date) = ?");
        $stmt->execute([$doctorId, $tenantId, $date]);
        $weeklyStats['orders'][] = ['date' => $date, 'count' => (int)$stmt->fetchColumn()];
        
        $stmt = $db->prepare("SELECT COUNT(DISTINCT patient_id) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ? AND DATE(order_date) = ?");
        $stmt->execute([$doctorId, $tenantId, $date]);
        $weeklyStats['patients'][] = ['date' => $date, 'count' => (int)$stmt->fetchColumn()];

        $aptCount = 0;
        try {
            $db->query('SELECT id FROM doctor_appointments LIMIT 1');
            $stmt = $db->prepare("SELECT COUNT(*) FROM doctor_appointments WHERE doctor_account_id = ? AND DATE(appointment_date) = ?");
            $stmt->execute([$doctorAuth->accountId(), $date]);
            $aptCount = (int)$stmt->fetchColumn();
        } catch (Throwable $e) {
            try {
                $db->query('SELECT id FROM patient_doctor_bookings LIMIT 1');
                $stmt = $db->prepare("SELECT COUNT(*) FROM patient_doctor_bookings WHERE doctor_account_id = ? AND DATE(appointment_date) = ?");
                $stmt->execute([$doctorAuth->accountId(), $date]);
                $aptCount = (int)$stmt->fetchColumn();
            } catch (Throwable $e2) {}
        }
        $weeklyStats['appointments'][] = ['date' => $date, 'count' => $aptCount];
    }
    
    // إحصائيات الشهر الحالي
    $monthStart = date('Y-m-01');
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ? AND order_date >= ?");
    $stmt->execute([$doctorId, $tenantId, $monthStart]);
    $monthlyStats['orders'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare("SELECT COUNT(DISTINCT patient_id) FROM lab_orders WHERE doctor_id = ? AND tenant_id = ? AND order_date >= ?");
    $stmt->execute([$doctorId, $tenantId, $monthStart]);
    $monthlyStats['patients'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare("SELECT COUNT(*) FROM patient_medical_notes WHERE doctor_account_id = ? AND created_at >= ?");
    $stmt->execute([$doctorAuth->accountId(), $monthStart]);
    $monthlyStats['notes'] = (int)$stmt->fetchColumn();
} catch (Throwable $e) {}
try {
    $db->query('SELECT id FROM doctor_activity_log LIMIT 1');
    $stmt = $db->prepare('SELECT action, entity_type, entity_id, created_at FROM doctor_activity_log WHERE doctor_account_id = ? ORDER BY created_at DESC LIMIT 30');
    $stmt->execute([$doctorAuth->accountId()]);
    $activityLog = $stmt->fetchAll();
} catch (Throwable $e) {}
$actionLabels = ['view_results' => 'عرض نتائج', 'view_patient' => 'عرض مريض', 'search' => 'بحث', 'login' => 'تسجيل دخول', 'export' => 'تصدير'];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/svg+xml" href="favicon.svg">
    <title>الملف الشخصي - Smart Doctor</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="doctor.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content doctor-profile-page">
    <div class="page-header" style="margin-bottom:24px;">
        <div>
            <h1 style="margin:0 0 8px;">👤 الملف الشخصي</h1>
            <p style="color:var(--text-muted);margin:0;">إدارة حسابك وإعداداتك الشخصية</p>
        </div>
    </div>

    <?php if ($accountInfo): ?>
    <?php if (isset($_SESSION['doctor_profile_msg'])): ?><div class="alert alert-success" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['doctor_profile_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_profile_msg']); ?></div><?php endif; ?>
    <?php if (isset($_SESSION['doctor_profile_error'])): ?><div class="alert alert-danger" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['doctor_profile_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_profile_error']); ?></div><?php endif; ?>
    <!-- بطاقة المعلومات الشخصية -->
    <div class="card" style="margin-bottom:24px;background:linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%);color:white;border:none;">
        <div style="display:flex;gap:24px;align-items:center;flex-wrap:wrap;">
            <div style="position:relative;flex-shrink:0;">
                <div style="width:100px;height:100px;border-radius:50%;background:rgba(255,255,255,0.2);display:flex;align-items:center;justify-content:center;font-size:3rem;overflow:hidden;">
                    <?php if (!empty($accountInfo['photo']) && file_exists(__DIR__ . '/../../' . $accountInfo['photo'])): ?>
                    <img src="<?php echo htmlspecialchars($accountInfo['photo'], ENT_QUOTES, 'UTF-8'); ?>" alt="صورة الطبيب" style="width:100%;height:100%;object-fit:cover;">
                    <?php else: ?>
                    👨‍⚕️
                    <?php endif; ?>
                </div>
                <form method="post" action="doctor.php?page=profile&action=upload_photo" enctype="multipart/form-data" style="margin-top:8px;">
                    <label style="display:inline-block;cursor:pointer;font-size:0.8rem;color:rgba(255,255,255,0.9);background:rgba(255,255,255,0.15);padding:6px 12px;border-radius:8px;">
                        📷 <?php echo !empty($accountInfo['photo']) ? 'تغيير الصورة' : 'تحميل صورة'; ?>
                        <input type="file" name="photo" accept="image/jpeg,image/png,image/gif,image/webp" style="display:none;" onchange="this.form.submit()">
                    </label>
                </form>
            </div>
            <div style="flex:1;min-width:200px;">
                <h2 style="margin:0 0 8px;color:white;font-size:1.5rem;">د. <?php echo htmlspecialchars($accountInfo['full_name'], ENT_QUOTES, 'UTF-8'); ?></h2>
                <p style="margin:0 0 12px;color:rgba(255,255,255,0.8);font-size:1rem;">
                    <?php echo htmlspecialchars($accountInfo['specialty'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?>
                    <?php if (!empty($accountInfo['clinic_name'])): ?>
                    <span style="color:rgba(255,255,255,0.6);"> · </span>
                    <span style="color:rgba(255,255,255,0.7);"><?php echo htmlspecialchars($accountInfo['clinic_name'], ENT_QUOTES, 'UTF-8'); ?></span>
                    <?php endif; ?>
                </p>
                <div style="display:flex;gap:16px;flex-wrap:wrap;font-size:0.9rem;color:rgba(255,255,255,0.8);">
                    <div style="display:flex;align-items:center;gap:6px;">
                        <span>🏥</span>
                        <span><?php echo htmlspecialchars($accountInfo['tenant_name'], ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>
                    <?php $dispPhone = $accountInfo['phone'] ?? $accountInfo['doctor_phone'] ?? ''; if (!empty($dispPhone)): ?>
                    <div style="display:flex;align-items:center;gap:6px;">
                        <span>📞</span>
                        <span><?php echo htmlspecialchars($dispPhone, ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>
                    <?php endif; ?>
                    <div style="display:flex;align-items:center;gap:6px;">
                        <span>👤</span>
                        <span><?php echo htmlspecialchars($accountInfo['username'], ENT_QUOTES, 'UTF-8'); ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- الإحصائيات الرئيسية -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
        <div class="card doctor-profile-stat-card" style="border-right:4px solid #0d9488;background:linear-gradient(135deg, #f0fdfa 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#0d9488;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    👥
                </div>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#0d9488;line-height:1;"><?php echo number_format($myStats['patients']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">المرضى</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                هذا الشهر: <?php echo number_format($monthlyStats['patients']); ?>
            </div>
        </div>

        <div class="card doctor-profile-stat-card" style="border-right:4px solid #3b82f6;background:linear-gradient(135deg, #eff6ff 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#3b82f6;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    📋
                </div>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#3b82f6;line-height:1;"><?php echo number_format($myStats['orders']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">الطلبات</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                هذا الشهر: <?php echo number_format($monthlyStats['orders']); ?>
            </div>
        </div>

        <div class="card doctor-profile-stat-card" style="border-right:4px solid #22c55e;background:linear-gradient(135deg, #f0fdf4 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#22c55e;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    📝
                </div>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#22c55e;line-height:1;"><?php echo number_format($myStats['notes']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">الملاحظات</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                هذا الشهر: <?php echo number_format($monthlyStats['notes']); ?>
            </div>
        </div>

        <div class="card doctor-profile-stat-card" style="border-right:4px solid #f59e0b;background:linear-gradient(135deg, #fffbeb 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#f59e0b;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    📅
                </div>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#f59e0b;line-height:1;"><?php echo number_format($myStats['appointments']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">المواعيد</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                تذكيرات نشطة: <?php echo number_format($myStats['reminders']); ?>
            </div>
        </div>

        <?php if ($myStats['critical_results'] > 0): ?>
        <div class="card doctor-profile-stat-card" style="border-right:4px solid #dc2626;background:linear-gradient(135deg, #fef2f2 0%, #ffffff 100%);">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
                <div style="width:48px;height:48px;border-radius:12px;background:#dc2626;display:flex;align-items:center;justify-content:center;font-size:1.5rem;">
                    ⚠️
                </div>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#dc2626;line-height:1;"><?php echo number_format($myStats['critical_results']); ?></div>
                    <div style="color:var(--text-muted);font-size:0.85rem;margin-top:4px;">نتائج حرجة</div>
                </div>
            </div>
            <div style="padding-top:12px;border-top:1px solid var(--border);font-size:0.8rem;color:var(--text-muted);">
                آخر 30 يوم
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- معلومات إضافية -->
    <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(300px, 1fr));gap:20px;margin-bottom:24px;">
        <div class="card">
            <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
                <span>ℹ️</span> معلومات الحساب
            </h3>
            <div style="display:flex;flex-direction:column;gap:14px;">
                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;background:var(--bg-secondary);border-radius:8px;">
                    <span style="color:var(--text-muted);font-size:0.9rem;">اسم المستخدم:</span>
                    <code style="background:white;padding:4px 8px;border-radius:4px;font-weight:600;"><?php echo htmlspecialchars($accountInfo['username'], ENT_QUOTES, 'UTF-8'); ?></code>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;background:var(--bg-secondary);border-radius:8px;">
                    <span style="color:var(--text-muted);font-size:0.9rem;">المختبر:</span>
                    <strong><?php echo htmlspecialchars($accountInfo['tenant_name'], ENT_QUOTES, 'UTF-8'); ?></strong>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;background:var(--bg-secondary);border-radius:8px;">
                    <span style="color:var(--text-muted);font-size:0.9rem;">آخر دخول:</span>
                    <span><?php echo $accountInfo['last_login_at'] ? date('Y-m-d H:i', strtotime($accountInfo['last_login_at'])) : 'لم يسجل'; ?></span>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;padding:10px;background:var(--bg-secondary);border-radius:8px;">
                    <span style="color:var(--text-muted);font-size:0.9rem;">حالة الحساب:</span>
                    <span style="padding:4px 10px;background:#22c55e;color:white;border-radius:12px;font-size:0.8rem;font-weight:600;"><?php echo $accountInfo['is_active'] ? 'نشط' : 'غير نشط'; ?></span>
                </div>
            </div>
        </div>

        <div class="card">
            <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
                <span>📊</span> نشاط الأسبوع
            </h3>
            <canvas id="weeklyActivityChart" style="max-height:200px;"></canvas>
        </div>
    </div>
    <!-- تغيير كلمة المرور -->
    <div class="card" style="margin-bottom:24px;">
        <h3 style="margin-top:0;display:flex;align-items:center;gap:8px;">
            <span>🔐</span> تغيير كلمة المرور
        </h3>
        <form method="post" action="doctor.php?page=profile&action=change_password" style="max-width:400px;">
            <div class="form-group">
                <label>كلمة المرور الحالية</label>
                <input type="password" name="current_password" required>
            </div>
            <div class="form-group">
                <label>كلمة المرور الجديدة</label>
                <input type="password" name="new_password" required minlength="6">
            </div>
            <div class="form-group">
                <label>تأكيد كلمة المرور الجديدة</label>
                <input type="password" name="confirm_password" required minlength="6">
            </div>
            <button type="submit" class="btn-primary">تغيير كلمة المرور</button>
        </form>
        <div style="margin-top:16px;padding:12px;background:#ecfdf5;border-radius:8px;border-right:4px solid #0d9488;">
            <p style="margin:0;color:#047857;font-size:0.9rem;">
                <strong>💡 ملاحظة:</strong> لتحديث بياناتك الشخصية (الاسم، التخصص، العيادة)، تواصل مع مدير المختبر.
            </p>
        </div>
    </div>

    <?php
    $twoFactorEnabled = !empty($accountInfo['two_factor_enabled']);
    $twoFactorSetup = isset($_SESSION['doctor_2fa_secret_setup']) || (isset($_GET['setup_2fa']) && $_GET['setup_2fa'] && !$twoFactorEnabled);
    try { $db->query('SELECT two_factor_enabled FROM doctor_accounts LIMIT 1'); } catch (Throwable $e) { $twoFactorEnabled = false; $twoFactorSetup = false; }
    ?>
    <!-- التحقق الثنائي 2FA -->
    <div class="card" style="margin-bottom:24px;">
        <h3 style="margin-top:0;"><span>🔐</span> التحقق الثنائي (2FA)</h3>
        <?php if ($twoFactorSetup && isset($_SESSION['doctor_2fa_secret_setup'])): 
            $secretSetup = $_SESSION['doctor_2fa_secret_setup'];
            $otpauth = \App\Core\TOTP::getProvisioningUri($secretSetup, $accountInfo['username'], 'Smart Doctor');
        ?>
        <p style="color:var(--text-muted);">امسح رمز QR بتطبيق المصادقة (Google Authenticator، Microsoft Authenticator) أو أدخل الرمز يدوياً:</p>
        <div style="margin:16px 0;">
            <code style="padding:12px;background:var(--bg-secondary);border-radius:8px;display:block;word-break:break-all;font-size:1rem;"><?php echo htmlspecialchars($secretSetup, ENT_QUOTES, 'UTF-8'); ?></code>
        </div>
        <form method="post" action="doctor.php?page=profile&action=verify_2fa" style="max-width:300px;">
            <div class="form-group">
                <label>رمز التحقق من التطبيق</label>
                <input type="text" name="totp_code" required placeholder="000000" pattern="[0-9]{6}" maxlength="6" inputmode="numeric" style="text-align:center;letter-spacing:4px;font-size:1.2rem;">
            </div>
            <button type="submit" class="btn-primary">تفعيل 2FA</button>
        </form>
        <?php elseif ($twoFactorEnabled): ?>
        <p style="color:#22c55e;"><strong>✅ مفعّل</strong> - يتم طلب رمز التحقق عند كل دخول.</p>
        <form method="post" action="doctor.php?page=profile&action=disable_2fa" onsubmit="return confirm('هل تريد إلغاء التحقق الثنائي؟');">
            <div class="form-group" style="max-width:300px;">
                <label>كلمة المرور لإلغاء 2FA</label>
                <input type="password" name="password" required>
            </div>
            <button type="submit" class="btn-secondary" style="background:#dc2626;color:white;border:none;">إلغاء 2FA</button>
        </form>
        <?php else: ?>
        <p style="color:var(--text-muted);">قم بتفعيل التحقق الثنائي لتأمين حسابك.</p>
        <form method="post" action="doctor.php?page=profile&action=enable_2fa">
            <button type="submit" class="btn-primary">تفعيل 2FA</button>
        </form>
        <?php endif; ?>
    </div>

    <!-- إشعارات واتساب للنتائج الحرجة -->
    <div class="card" style="margin-bottom:24px;">
        <h3 style="margin-top:0;"><span>📱</span> إعدادات واتساب</h3>
        <p style="color:var(--text-muted);font-size:0.9rem;margin-bottom:16px;">ربط واتساب خاص بك (UltraMsg) يرسل الإشعارات من رقمك. إذا تركت فارغاً، يستخدم إعدادات المختبر.</p>
        <form method="post" action="doctor.php?page=profile&action=update_notifications">
            <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:16px;">
                <div class="form-group">
                    <label>رقم الهاتف (للاستقبال)</label>
                    <input type="tel" name="phone" placeholder="07XXXXXXXX" value="<?php echo htmlspecialchars($accountInfo['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>Instance ID <span style="color:var(--text-muted);font-size:0.8em;">(واتساب مالتة)</span></label>
                    <input type="text" name="whatsapp_instance_id" placeholder="instance12345" value="<?php echo htmlspecialchars($accountInfo['whatsapp_instance_id'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>Token</label>
                    <input type="text" name="whatsapp_access_token" placeholder="من UltraMsg" value="<?php echo htmlspecialchars($accountInfo['whatsapp_access_token'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
            </div>
            <div class="form-group">
                <label><input type="checkbox" name="whatsapp_notify_critical" value="1" <?php echo !empty($accountInfo['whatsapp_notify_critical']) ? 'checked' : ''; ?>> إرسال إشعار واتساب عند صدور نتيجة حرجة لأحد مرضاي</label>
            </div>
            <div class="form-group">
                <label><input type="checkbox" name="whatsapp_notify_appointments" value="1" <?php echo (!isset($accountInfo['whatsapp_notify_appointments']) || !empty($accountInfo['whatsapp_notify_appointments'])) ? 'checked' : ''; ?>> إرسال إشعار واتساب عند حجز مريض موعد معك</label>
            </div>
            <div class="form-group">
                <label><input type="checkbox" name="patient_whatsapp_remind" value="1" <?php echo (!isset($accountInfo['patient_whatsapp_remind']) || !empty($accountInfo['patient_whatsapp_remind'])) ? 'checked' : ''; ?>> إرسال تذكير واتساب للمريض قبل موعده بساعتين تلقائياً</label>
            </div>
            <button type="submit" class="btn-primary">حفظ الإعدادات</button>
        </form>
    </div>
    <!-- سجل النشاط -->
    <?php if (!empty($activityLog)): ?>
    <div class="card">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
            <h3 style="margin:0;display:flex;align-items:center;gap:8px;">
                <span>📋</span> سجل النشاط الأخير
            </h3>
            <span style="font-size:0.85rem;color:var(--text-muted);">آخر 30 عملية</span>
        </div>
        <div class="table-wrapper" style="max-height:400px;overflow-y:auto;border-radius:8px;">
            <table class="table" style="margin:0;">
                <thead style="position:sticky;top:0;background:var(--bg-card);z-index:10;">
                    <tr>
                        <th style="padding:12px;">الإجراء</th>
                        <th style="padding:12px;">النوع</th>
                        <th style="padding:12px;">التاريخ والوقت</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($activityLog as $log): 
                    $actionIcon = [
                        'view_results' => '📄',
                        'view_patient' => '👤',
                        'search' => '🔍',
                        'login' => '🔐',
                        'export' => '📥',
                        'add_note' => '📝',
                        'add_appointment' => '📅'
                    ];
                    $icon = $actionIcon[$log['action']] ?? '⚙️';
                ?>
                <tr style="transition:background 0.2s;">
                    <td style="padding:12px;">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <span style="font-size:1.2rem;"><?php echo $icon; ?></span>
                            <span><?php echo htmlspecialchars($actionLabels[$log['action']] ?? $log['action'], ENT_QUOTES, 'UTF-8'); ?></span>
                        </div>
                    </td>
                    <td style="padding:12px;">
                        <span style="padding:4px 10px;background:var(--bg-secondary);border-radius:12px;font-size:0.85rem;">
                            <?php echo htmlspecialchars($log['entity_type'] ?? '-', ENT_QUOTES, 'UTF-8'); ?>
                            <?php if ($log['entity_id']): ?>
                            <span style="color:var(--primary);font-weight:600;">#<?php echo (int)$log['entity_id']; ?></span>
                            <?php endif; ?>
                        </span>
                    </td>
                    <td style="padding:12px;color:var(--text-muted);font-size:0.9rem;">
                        <?php echo date('Y-m-d', strtotime($log['created_at'])); ?>
                        <span style="color:var(--text-muted);opacity:0.7;"><?php echo date('H:i', strtotime($log['created_at'])); ?></span>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
    <?php else: ?>
    <div class="card">
        <p style="color:var(--text-muted);">تعذر تحميل البيانات.</p>
    </div>
    <?php endif; ?>
</main>

<script>
// رسم بياني لنشاط الأسبوع
(function(){
    var ctx = document.getElementById('weeklyActivityChart');
    if (!ctx) return;
    
    var weeklyData = <?php echo json_encode($weeklyStats['orders']); ?>;
    var labels = weeklyData.map(function(d) {
        var date = new Date(d.date + 'T12:00:00');
        var days = ['أحد', 'اثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'];
        return days[date.getDay()] + ' ' + date.getDate();
    });
    var ordersData = weeklyData.map(function(d) { return d.count; });
    var patientsData = <?php echo json_encode($weeklyStats['patients']); ?>.map(function(d) { return d.count; });
    var appointmentsData = <?php echo json_encode($weeklyStats['appointments'] ?? []); ?>.map(function(d) { return d.count; });
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'الطلبات',
                data: ordersData,
                borderColor: '#3b82f6',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                tension: 0.4,
                fill: true
            }, {
                label: 'المواعيد',
                data: appointmentsData,
                borderColor: '#f59e0b',
                backgroundColor: 'rgba(245, 158, 11, 0.1)',
                tension: 0.4,
                fill: true
            }, {
                label: 'المرضى',
                data: patientsData,
                borderColor: '#0d9488',
                backgroundColor: 'rgba(13, 148, 136, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'top',
                    rtl: true
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            }
        }
    });
})();
</script>
</body>
</html>
