<?php
/**
 * لوحة تحكم الطبيب - الرئيسية
 */
$tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
$doctorCond = ' AND o.doctor_id = ' . (int)$doctorId;

$stats = [
    'total_patients' => 0,
    'total_orders' => 0,
    'today_orders' => 0,
    'pending_results' => 0,
    'abnormal_count' => 0,
    'critical_count' => 0,
    'orders_by_month' => array_fill(1, 12, 0),
    'top_tests_abnormal' => [],
];

try {
    $stmt = $db->prepare("SELECT COUNT(DISTINCT o.patient_id) FROM lab_orders o WHERE 1=1 $tenantCond $doctorCond");
    $stmt->execute();
    $stats['total_patients'] = (int)$stmt->fetchColumn();

    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders o WHERE 1=1 $tenantCond $doctorCond");
    $stmt->execute();
    $stats['total_orders'] = (int)$stmt->fetchColumn();

    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders o WHERE DATE(o.order_date) = CURDATE() $tenantCond $doctorCond");
    $stmt->execute();
    $stats['today_orders'] = (int)$stmt->fetchColumn();

    $stmt = $db->prepare("SELECT COUNT(*) FROM order_items oi JOIN lab_orders o ON o.id = oi.order_id WHERE oi.status IN ('pending','in_progress') $tenantCond $doctorCond");
    $stmt->execute();
    $stats['pending_results'] = (int)$stmt->fetchColumn();

    $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 r.flag IN ('L','H','C') AND r.flag IS NOT NULL $tenantCond $doctorCond");
    $stmt->execute();
    $stats['abnormal_count'] = (int)$stmt->fetchColumn();

    $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 r.flag = 'C' $tenantCond $doctorCond");
    $stmt->execute();
    $stats['critical_count'] = (int)$stmt->fetchColumn();

    $stmt = $db->prepare("SELECT MONTH(o.order_date) AS m, COUNT(*) AS c FROM lab_orders o WHERE YEAR(o.order_date) = YEAR(CURDATE()) $tenantCond $doctorCond GROUP BY MONTH(o.order_date)");
    $stmt->execute();
    foreach ($stmt->fetchAll() as $row) {
        $m = (int)$row['m'];
        if ($m >= 1 && $m <= 12) $stats['orders_by_month'][$m] = (int)$row['c'];
    }

    $stmt = $db->prepare("SELECT t.name AS test_name, COUNT(*) AS cnt FROM results r JOIN order_items oi ON oi.id = r.order_item_id JOIN lab_orders o ON o.id = oi.order_id JOIN tests t ON t.id = oi.test_id WHERE r.flag IN ('L','H','C') $tenantCond $doctorCond GROUP BY oi.test_id ORDER BY cnt DESC LIMIT 5");
    $stmt->execute();
    $stats['top_tests_abnormal'] = $stmt->fetchAll();
} catch (Throwable $e) {}

$recentOrders = [];
$upcomingReminders = [];
$overdueReminders = [];
$recentAlerts = [];
$unreadAlertsCount = 0;
try {
    $stmt = $db->prepare("SELECT o.id, o.order_number, o.order_date, o.status, o.patient_id, p.full_name AS patient_name, p.patient_code FROM lab_orders o JOIN patients p ON p.id = o.patient_id WHERE 1=1 $tenantCond $doctorCond ORDER BY o.order_date DESC LIMIT 15");
    $stmt->execute();
    $recentOrders = $stmt->fetchAll();
} catch (Throwable $e) {}
try {
    $db->query('SELECT id FROM doctor_alerts LIMIT 1');
    $stmt = $db->prepare('SELECT COUNT(*) FROM doctor_alerts WHERE doctor_account_id = ? AND is_read = 0');
    $stmt->execute([$doctorAuth->accountId()]);
    $unreadAlertsCount = (int)$stmt->fetchColumn();
    $stmt = $db->prepare('SELECT * FROM doctor_alerts WHERE doctor_account_id = ? ORDER BY created_at DESC LIMIT 5');
    $stmt->execute([$doctorAuth->accountId()]);
    $recentAlerts = $stmt->fetchAll();
} catch (Throwable $e) {}
try {
    $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1');
    $stmt = $db->prepare('SELECT r.id, r.reminder_date, r.note, p.full_name AS patient_name, p.id AS patient_id FROM doctor_follow_up_reminders r JOIN patients p ON p.id = r.patient_id WHERE r.doctor_account_id = ? AND r.reminder_date >= CURDATE() AND r.is_done = 0 ORDER BY r.reminder_date ASC LIMIT 5');
    $stmt->execute([$doctorAuth->accountId()]);
    $upcomingReminders = $stmt->fetchAll();
    $stmt = $db->prepare('SELECT r.id, r.reminder_date, r.note, p.full_name AS patient_name, p.id AS patient_id FROM doctor_follow_up_reminders r JOIN patients p ON p.id = r.patient_id WHERE r.doctor_account_id = ? AND r.reminder_date < CURDATE() AND r.is_done = 0 ORDER BY r.reminder_date ASC LIMIT 5');
    $stmt->execute([$doctorAuth->accountId()]);
    $overdueReminders = $stmt->fetchAll();
} catch (Throwable $e) {}


$monthReport = ['this_month' => 0, 'last_month' => 0, 'new_patients_this' => 0];
try {
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders o WHERE YEAR(o.order_date) = YEAR(CURDATE()) AND MONTH(o.order_date) = MONTH(CURDATE()) $tenantCond $doctorCond");
    $stmt->execute();
    $monthReport['this_month'] = (int)$stmt->fetchColumn();
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders o WHERE YEAR(o.order_date) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND MONTH(o.order_date) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) $tenantCond $doctorCond");
    $stmt->execute();
    $monthReport['last_month'] = (int)$stmt->fetchColumn();
    $stmt = $db->prepare("SELECT COUNT(DISTINCT o.patient_id) FROM lab_orders o WHERE YEAR(o.order_date) = YEAR(CURDATE()) AND MONTH(o.order_date) = MONTH(CURDATE()) $tenantCond $doctorCond AND o.patient_id NOT IN (SELECT o2.patient_id FROM lab_orders o2 WHERE o2.order_date < DATE_FORMAT(CURDATE(), '%Y-%m-01') AND o2.tenant_id = ? AND o2.doctor_id = ?)");
    $stmt->execute([$tenantId, $doctorId]);
    $monthReport['new_patients_this'] = (int)$stmt->fetchColumn();
} catch (Throwable $e) {}

$monthNames = ['', 'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'];
$todayDate = date('Y-m-d');

$todayCompleted = 0;
$reviewProgress = 0;
$todayAppointments = 0;
$avgResponseTime = 0;
$patientRetention = 0;
$topDiagnoses = [];
$genderDistribution = ['M' => 0, 'F' => 0];
$ageGroups = ['0-18' => 0, '19-40' => 0, '41-60' => 0, '60+' => 0];
$weekOrders = 0;
$lastWeekOrders = 0;
$recentOrdersCount = 0;

try {
    // طلبات اليوم المكتملة
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders o WHERE DATE(o.order_date) = CURDATE() AND o.status = 'completed' $tenantCond $doctorCond");
    $stmt->execute();
    $todayCompleted = (int)$stmt->fetchColumn();
    $totalToday = $stats['today_orders'];
    $reviewProgress = $totalToday > 0 ? min(100, round($todayCompleted / $totalToday * 100)) : 0;
    
    // طلبات الأسبوع الحالي
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders o WHERE o.order_date >= DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) $tenantCond $doctorCond");
    $stmt->execute();
    $weekOrders = (int)$stmt->fetchColumn();
    
    // طلبات الأسبوع الماضي
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders o WHERE o.order_date >= DATE_SUB(DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY), INTERVAL 7 DAY) AND o.order_date < DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) $tenantCond $doctorCond");
    $stmt->execute();
    $lastWeekOrders = (int)$stmt->fetchColumn();
    
    // طلبات آخر 7 أيام
    $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders o WHERE o.order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) $tenantCond $doctorCond");
    $stmt->execute();
    $recentOrdersCount = (int)$stmt->fetchColumn();
    
    // المواعيد اليوم (نحسب من doctor_appointments أولاً لأنه يحتوي على جميع المواعيد)
    // إذا لم يكن موجوداً، نستخدم patient_doctor_bookings كـ fallback
    $todayAppointments = 0;
    try {
        $db->query('SELECT id FROM doctor_appointments LIMIT 1');
        // نحسب من doctor_appointments فقط لأنه يحتوي على نسخة من كل موعد (من الحجوزات + من الطبيب مباشرة)
        $stmt = $db->prepare('SELECT COUNT(*) FROM doctor_appointments WHERE doctor_account_id = ? AND DATE(appointment_date) = ?');
        $stmt->execute([$doctorAuth->accountId(), $todayDate]);
        $todayAppointments = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {
        // إذا جدول doctor_appointments غير موجود، نحسب من patient_doctor_bookings
        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(), $todayDate]);
            $todayAppointments = (int)$stmt->fetchColumn();
        } catch (Throwable $e2) {
            // كلا الجدولين غير موجودين
            $todayAppointments = 0;
        }
    }
    
    // توزيع الجنس
    $stmt = $db->prepare("SELECT p.gender, COUNT(DISTINCT p.id) AS cnt FROM patients p JOIN lab_orders o ON o.patient_id = p.id WHERE 1=1 $tenantCond $doctorCond AND p.gender IN ('M','F') GROUP BY p.gender");
    $stmt->execute();
    foreach ($stmt->fetchAll() as $row) {
        $genderDistribution[$row['gender']] = (int)$row['cnt'];
    }
    
    // توزيع الفئات العمرية
    $stmt = $db->prepare("SELECT 
        CASE 
            WHEN TIMESTAMPDIFF(YEAR, p.date_of_birth, CURDATE()) BETWEEN 0 AND 18 THEN '0-18'
            WHEN TIMESTAMPDIFF(YEAR, p.date_of_birth, CURDATE()) BETWEEN 19 AND 40 THEN '19-40'
            WHEN TIMESTAMPDIFF(YEAR, p.date_of_birth, CURDATE()) BETWEEN 41 AND 60 THEN '41-60'
            WHEN TIMESTAMPDIFF(YEAR, p.date_of_birth, CURDATE()) > 60 THEN '60+'
            ELSE 'غير محدد'
        END AS age_group,
        COUNT(DISTINCT p.id) AS cnt
        FROM patients p 
        JOIN lab_orders o ON o.patient_id = p.id 
        WHERE 1=1 $tenantCond $doctorCond AND p.date_of_birth IS NOT NULL
        GROUP BY age_group");
    $stmt->execute();
    foreach ($stmt->fetchAll() as $row) {
        if (isset($ageGroups[$row['age_group']])) {
            $ageGroups[$row['age_group']] = (int)$row['cnt'];
        }
    }
    
    // معدل الاحتفاظ بالمرضى (مرضى عادوا خلال آخر 3 أشهر)
    $stmt = $db->prepare("SELECT COUNT(DISTINCT o1.patient_id) FROM lab_orders o1 
        WHERE o1.order_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) 
        AND o1.patient_id IN (
            SELECT DISTINCT o2.patient_id FROM lab_orders o2 
            WHERE o2.order_date < DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
            $tenantCond $doctorCond
        ) $tenantCond $doctorCond");
    $stmt->execute();
    $returningPatients = (int)$stmt->fetchColumn();
    $totalOldPatients = $stats['total_patients'] - $monthReport['new_patients_this'];
    $patientRetention = $totalOldPatients > 0 ? round(($returningPatients / $totalOldPatients) * 100, 1) : 0;
    
    // أكثر التشخيصات/الملاحظات الطبية
    try {
        $db->query('SELECT note_type FROM patient_medical_notes LIMIT 1');
        $stmt = $db->prepare("SELECT note_type, COUNT(*) AS cnt FROM patient_medical_notes 
            WHERE doctor_account_id = ? AND note_type IN ('diagnosis', 'lab_review', 'follow_up')
            GROUP BY note_type ORDER BY cnt DESC LIMIT 5");
        $stmt->execute([$doctorAuth->accountId()]);
        $topDiagnoses = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
} catch (Throwable $e) {}

if (isset($_GET['export_monthly']) && $_GET['export_monthly'] === '1') {
    $isExcel = isset($_GET['format']) && $_GET['format'] === 'xls';
    header('Content-Type: ' . ($isExcel ? 'application/vnd.ms-excel' : 'text/csv') . '; charset=UTF-8');
    header('Content-Disposition: attachment; filename="monthly_report_' . date('Y-m') . '.' . ($isExcel ? 'xls' : 'csv') . '"');
    echo "\xEF\xBB\xBF";
    echo "التقرير الشهري,القيمة\n";
    echo "الشهر," . $monthNames[(int)date('n')] . "\n";
    echo "طلبات هذا الشهر," . $monthReport['this_month'] . "\n";
    echo "طلبات الشهر الماضي," . $monthReport['last_month'] . "\n";
    echo "الفرق," . ($monthReport['this_month'] - $monthReport['last_month']) . "\n";
    echo "مرضى جدد," . $monthReport['new_patients_this'] . "\n";
    echo "إجمالي المرضى," . $stats['total_patients'] . "\n";
    echo "إجمالي الطلبات," . $stats['total_orders'] . "\n";
    echo "نتائج غير طبيعية," . $stats['abnormal_count'] . "\n";
    echo "نتائج حرجة," . $stats['critical_count'] . "\n";
    exit;
}
?>
<!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">
    <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">
    <div class="page-header doctor-dashboard-header">
        <?php $greeting = ((int)date('G')) < 12 ? 'صباح الخير' : 'مساء الخير'; ?>
        <div class="doctor-greeting">
            <h1><?php echo $greeting; ?> د. <?php echo htmlspecialchars($_SESSION['doctor_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></h1>
            <p class="doctor-subtitle"><?php echo htmlspecialchars($_SESSION['doctor_tenant_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?> · <?php echo $monthNames[(int)date('n')] . ' ' . date('d') . ' ' . date('Y'); ?></p>
        </div>
        <div class="doctor-quick-actions">
            <a href="doctor.php?page=search" class="btn-primary">🔍 بحث سريع</a>
            <a href="doctor.php?page=appointments" class="btn-secondary">📅 المواعيد</a>
            <a href="doctor.php?page=results" class="btn-secondary">📋 النتائج</a>
            <a href="doctor.php?page=reminders" class="btn-secondary">⏰ التذكيرات</a>
            <button type="button" onclick="DoctorFocusMode()" class="btn-secondary" title="وضع التركيز (إخفاء الشريط الجانبي)">🎯 تركيز</button>
            <button type="button" onclick="DoctorNotifications.requestPermission()" class="btn-secondary" title="تفعيل الإشعارات">🔔 إشعارات</button>
        </div>
    </div>

    <?php if ($stats['today_orders'] > 0): ?>
    <div class="doctor-activity-indicator">
        <div class="doctor-activity-label">
            <span>مؤشر نشاط اليوم</span>
            <span><?php echo $todayCompleted; ?> / <?php echo $stats['today_orders']; ?> تمت مراجعته</span>
        </div>
        <div class="doctor-activity-bar"><div class="doctor-activity-fill" style="width:<?php echo $reviewProgress; ?>%;"></div></div>
    </div>
    <?php endif; ?>

    <div class="doctor-today-tasks card">
        <h3 class="doctor-card-title">📌 ما يحتاج مراجعة اليوم</h3>
        <div class="doctor-today-tasks-grid">
            <?php if ($stats['critical_count'] > 0): ?>
            <a href="doctor.php?page=results&critical=1" class="doctor-task-item doctor-task-urgent">
                <span class="doctor-task-icon">⚠️</span>
                <span class="doctor-task-text"><?php echo $stats['critical_count']; ?> نتيجة حرجة</span>
                <span class="doctor-task-action">مراجعة ←</span>
            </a>
            <?php endif; ?>
            <?php if (count($overdueReminders) > 0): ?>
            <a href="doctor.php?page=reminders" class="doctor-task-item doctor-task-overdue">
                <span class="doctor-task-icon">⏰</span>
                <span class="doctor-task-text"><?php echo count($overdueReminders); ?> تذكير متأخر</span>
                <span class="doctor-task-action">عرض ←</span>
            </a>
            <?php endif; ?>
            <?php if ($stats['today_orders'] > 0 && $stats['pending_results'] > 0): ?>
            <a href="doctor.php?page=results&from=<?php echo date('Y-m-d'); ?>&to=<?php echo date('Y-m-d'); ?>&status=in_progress" class="doctor-task-item doctor-task-pending">
                <span class="doctor-task-icon">⏳</span>
                <span class="doctor-task-text"><?php echo $stats['pending_results']; ?> نتيجة قيد الانتظار</span>
                <span class="doctor-task-action">عرض ←</span>
            </a>
            <?php endif; ?>
            <?php if ($stats['critical_count'] == 0 && empty($overdueReminders) && ($stats['today_orders'] == 0 || $stats['pending_results'] == 0)): ?>
            <div class="doctor-task-item doctor-task-done">
                <span class="doctor-task-icon">✓</span>
                <span class="doctor-task-text">لا يوجد ما يحتاج مراجعة عاجلة</span>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($stats['critical_count'] > 0): ?>
    <div class="doctor-alert doctor-alert-critical">
        <span class="doctor-alert-icon">⚠️</span>
        <div class="doctor-alert-content">
            <strong>تنبيه:</strong> يوجد <?php echo $stats['critical_count']; ?> نتيجة حرجة تحتاج مراجعة فورية.
        </div>
        <a href="doctor.php?page=results&critical=1" class="doctor-alert-action">عرض الطلبات الحرجة ←</a>
    </div>
    <?php endif; ?>

    <?php if (!empty($overdueReminders)): ?>
    <div class="card doctor-reminder-card doctor-reminder-overdue">
        <h3 class="doctor-card-title">⚠️ تذكيرات متأخرة</h3>
        <ul style="list-style:none;padding:0;margin:0;">
            <?php foreach ($overdueReminders as $r): ?>
            <li style="padding:8px 0;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
                <span><a href="doctor.php?page=results&patient_id=<?php echo (int)$r['patient_id']; ?>"><?php echo htmlspecialchars($r['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a> - <?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?></span>
                <span style="color:var(--text-muted);font-size:0.9rem;"><?php echo htmlspecialchars($r['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span>
                <a href="doctor.php?page=reminders&action=done&id=<?php echo (int)$r['id']; ?>">تم</a>
            </li>
            <?php endforeach; ?>
        </ul>
        <a href="doctor.php?page=reminders" style="margin-top:8px;display:inline-block;">عرض الكل ←</a>
    </div>
    <?php endif; ?>

    <?php if (!empty($upcomingReminders)): ?>
    <div class="card doctor-reminder-card doctor-reminder-upcoming">
        <h3 class="doctor-card-title">⏰ تذكيرات قادمة</h3>
        <ul style="list-style:none;padding:0;margin:0;">
            <?php foreach ($upcomingReminders as $r): ?>
            <li style="padding:8px 0;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
                <span><a href="doctor.php?page=results&patient_id=<?php echo (int)$r['patient_id']; ?>"><?php echo htmlspecialchars($r['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a> - <?php echo date('Y-m-d', strtotime($r['reminder_date'])); ?></span>
                <span style="color:var(--text-muted);font-size:0.9rem;"><?php echo htmlspecialchars($r['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span>
                <a href="doctor.php?page=reminders&action=done&id=<?php echo (int)$r['id']; ?>">تم</a>
            </li>
            <?php endforeach; ?>
        </ul>
        <a href="doctor.php?page=reminders" style="margin-top:8px;display:inline-block;">عرض الكل ←</a>
    </div>
    <?php endif; ?>

    <?php if (!empty($recentAlerts) || $unreadAlertsCount > 0): ?>
    <div class="card" style="margin-bottom:24px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
            <h3 class="doctor-card-title">🔔 الإشعارات والتنبيهات</h3>
            <a href="doctor.php?page=alerts" class="btn-secondary btn-sm">عرض الكل ←</a>
        </div>
        <?php if ($unreadAlertsCount > 0): ?>
        <div style="background:#fef3c7;border:1px solid #fbbf24;border-radius:8px;padding:12px;margin-bottom:16px;">
            <strong style="color:#92400e;">لديك <?php echo $unreadAlertsCount; ?> إشعار غير مقروء</strong>
            <a href="doctor.php?page=alerts&filter=unread" style="margin-right:8px;color:#0d9488;font-weight:600;">عرض ←</a>
        </div>
        <?php endif; ?>
        <?php if (!empty($recentAlerts)): ?>
        <div style="display:flex;flex-direction:column;gap:0;">
            <?php foreach (array_slice($recentAlerts, 0, 5) as $alert): 
                $alertIcons = ['critical' => '⚠️', 'reminder' => '⏰', 'appointment' => '📅', 'booking' => '🔗', 'system' => '⚙️', 'info' => 'ℹ️'];
                $alertColors = ['critical' => '#ef4444', 'reminder' => '#f59e0b', 'appointment' => '#3b82f6', 'booking' => '#0d9488', 'system' => '#6b7280', 'info' => '#0d9488'];
                $icon = $alertIcons[$alert['alert_type']] ?? 'ℹ️';
                $color = $alertColors[$alert['alert_type']] ?? '#0d9488';
            ?>
            <div style="padding:12px;border-bottom:1px solid var(--border);display:flex;gap:12px;align-items:flex-start;transition:background 0.2s;<?php echo $alert['is_read'] == 0 ? 'background:rgba(13,148,136,0.05);' : ''; ?>">
                <div style="flex-shrink:0;width:32px;height:32px;border-radius:50%;background:<?php echo $color; ?>20;display:flex;align-items:center;justify-content:center;font-size:1.2rem;">
                    <?php echo $icon; ?>
                </div>
                <div style="flex:1;min-width:0;">
                    <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;margin-bottom:4px;">
                        <h4 style="margin:0;font-size:0.95rem;<?php echo $alert['is_read'] == 0 ? 'font-weight:600;' : ''; ?>">
                            <?php echo htmlspecialchars($alert['title'], ENT_QUOTES, 'UTF-8'); ?>
                        </h4>
                        <?php if ($alert['is_read'] == 0): ?>
                        <span style="width:8px;height:8px;background:#0d9488;border-radius:50%;flex-shrink:0;margin-top:6px;"></span>
                        <?php endif; ?>
                    </div>
                    <?php if ($alert['message']): ?>
                    <p style="margin:0 0 6px;color:var(--text-secondary);font-size:0.85rem;line-height:1.4;">
                        <?php echo nl2br(htmlspecialchars(mb_substr($alert['message'], 0, 100), ENT_QUOTES, 'UTF-8')); ?><?php echo mb_strlen($alert['message']) > 100 ? '...' : ''; ?>
                    </p>
                    <?php endif; ?>
                    <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;font-size:0.75rem;color:var(--text-muted);">
                        <span>🕐 <?php echo date('Y-m-d H:i', strtotime($alert['created_at'])); ?></span>
                        <?php if ($alert['action_url']): ?>
                        <a href="<?php echo htmlspecialchars($alert['action_url'], ENT_QUOTES, 'UTF-8'); ?>" style="color:#0d9488;font-weight:500;">عرض ←</a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <p style="color:var(--text-muted);text-align:center;padding:20px;">لا توجد إشعارات</p>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="doctor-stats-grid">
        <div class="doctor-stat-card">
            <div class="doctor-stat-icon">👥</div>
            <div class="doctor-stat-value"><?php echo $stats['total_patients']; ?></div>
            <div class="doctor-stat-label">إجمالي المرضى</div>
        </div>
        <div class="doctor-stat-card">
            <div class="doctor-stat-icon">📋</div>
            <div class="doctor-stat-value"><?php echo $stats['total_orders']; ?></div>
            <div class="doctor-stat-label">إجمالي الطلبات</div>
        </div>
        <a href="doctor.php?page=results&from=<?php echo date('Y-m-d'); ?>&to=<?php echo date('Y-m-d'); ?>" class="doctor-stat-card doctor-stat-card-link">
            <div class="doctor-stat-icon">📅</div>
            <div class="doctor-stat-value"><?php echo $stats['today_orders']; ?></div>
            <div class="doctor-stat-label">طلبات اليوم</div>
        </a>
        <a href="doctor.php?page=results&status=in_progress" class="doctor-stat-card doctor-stat-card-link">
            <div class="doctor-stat-icon">⏳</div>
            <div class="doctor-stat-value"><?php echo $stats['pending_results']; ?></div>
            <div class="doctor-stat-label">قيد الانتظار</div>
        </a>
        <a href="doctor.php?page=appointments&date=<?php echo date('Y-m-d'); ?>" class="doctor-stat-card doctor-stat-card-link">
            <div class="doctor-stat-icon">📅</div>
            <div class="doctor-stat-value"><?php echo $todayAppointments; ?></div>
            <div class="doctor-stat-label">مواعيد اليوم</div>
        </a>
        <a href="doctor.php?page=results&from=<?php echo date('Y-m-d', strtotime('monday this week')); ?>&to=<?php echo date('Y-m-d'); ?>" class="doctor-stat-card doctor-stat-card-link">
            <div class="doctor-stat-icon">📊</div>
            <div class="doctor-stat-value"><?php echo $weekOrders; ?></div>
            <div class="doctor-stat-label">طلبات الأسبوع</div>
            <?php $wd = $weekOrders - $lastWeekOrders; ?>
            <div class="doctor-stat-trend <?php echo $wd >= 0 ? 'positive' : 'negative'; ?>"><?php echo $wd >= 0 ? '↑' : '↓'; ?> <?php echo abs($wd); ?> عن الأسبوع الماضي</div>
        </a>
        <a href="doctor.php?page=results&critical=1" class="doctor-stat-card doctor-stat-card-link doctor-stat-card-warning">
            <div class="doctor-stat-icon">⚠️</div>
            <div class="doctor-stat-value"><?php echo $stats['abnormal_count']; ?></div>
            <div class="doctor-stat-label">غير طبيعية</div>
        </a>
        <?php if ($patientRetention > 0): ?>
        <div class="doctor-stat-card">
            <div class="doctor-stat-icon">🔄</div>
            <div class="doctor-stat-value"><?php echo $patientRetention; ?>%</div>
            <div class="doctor-stat-label">معدل الاحتفاظ</div>
        </div>
        <?php endif; ?>
    </div>

    <!-- ملخص يومي محسّن -->
    <div class="card" style="margin-bottom:24px;background:linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%);color:white;border:none;">
        <div style="padding:24px;">
            <h3 style="margin:0 0 20px;font-size:1.3rem;display:flex;align-items:center;gap:10px;">
                <span>📊</span> <?php echo $stats['today_orders'] > 0 ? 'ملخص اليوم' : 'ملخص الأسبوع'; ?>
            </h3>
            <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(180px, 1fr));gap:20px;">
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#14b8a6;margin-bottom:4px;">
                        <?php echo $stats['today_orders'] > 0 ? $stats['today_orders'] : $weekOrders; ?>
                    </div>
                    <div style="color:rgba(255,255,255,0.8);font-size:0.9rem;">
                        <?php echo $stats['today_orders'] > 0 ? 'طلبات اليوم' : 'طلبات الأسبوع'; ?>
                    </div>
                    <?php if ($stats['today_orders'] == 0 && $weekOrders > 0): ?>
                    <div style="color:rgba(255,255,255,0.6);font-size:0.75rem;margin-top:4px;">
                        <?php echo $lastWeekOrders > 0 ? '↑ ' . ($weekOrders - $lastWeekOrders) . ' عن الأسبوع الماضي' : ''; ?>
                    </div>
                    <?php endif; ?>
                </div>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#22c55e;margin-bottom:4px;">
                        <?php 
                        if ($stats['today_orders'] > 0) {
                            echo $todayCompleted;
                        } else {
                            // طلبات مكتملة آخر 7 أيام
                            try {
                                $stmt = $db->prepare("SELECT COUNT(*) FROM lab_orders o WHERE o.order_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND o.status = 'completed' $tenantCond $doctorCond");
                                $stmt->execute();
                                echo (int)$stmt->fetchColumn();
                            } catch (Throwable $e) {
                                echo '0';
                            }
                        }
                        ?>
                    </div>
                    <div style="color:rgba(255,255,255,0.8);font-size:0.9rem;">
                        <?php echo $stats['today_orders'] > 0 ? 'مكتملة اليوم' : 'مكتملة (7 أيام)'; ?>
                    </div>
                </div>
                <?php if ($stats['critical_count'] > 0): ?>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#ef4444;margin-bottom:4px;"><?php echo $stats['critical_count']; ?></div>
                    <div style="color:rgba(255,255,255,0.8);font-size:0.9rem;">نتائج حرجة</div>
                </div>
                <?php endif; ?>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#f59e0b;margin-bottom:4px;"><?php echo $todayAppointments; ?></div>
                    <div style="color:rgba(255,255,255,0.8);font-size:0.9rem;">مواعيد اليوم</div>
                </div>
                <?php if ($stats['today_orders'] > 0): ?>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#8b5cf6;margin-bottom:4px;"><?php echo $reviewProgress; ?>%</div>
                    <div style="color:rgba(255,255,255,0.8);font-size:0.9rem;">معدل الإنجاز</div>
                </div>
                <?php else: ?>
                <div>
                    <div style="font-size:2rem;font-weight:bold;color:#3b82f6;margin-bottom:4px;"><?php echo $recentOrdersCount; ?></div>
                    <div style="color:rgba(255,255,255,0.8);font-size:0.9rem;">طلبات آخر 7 أيام</div>
                </div>
                <?php endif; ?>
                <?php if ($stats['today_orders'] == 0 && $recentOrdersCount == 0): ?>
                <div style="grid-column:1/-1;text-align:center;padding:20px;background:rgba(255,255,255,0.05);border-radius:8px;">
                    <div style="font-size:1.1rem;margin-bottom:8px;">لا توجد طلبات حديثة</div>
                    <div style="color:rgba(255,255,255,0.6);font-size:0.9rem;">ابدأ بإضافة مريض جديد أو انتظر الطلبات الجديدة</div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- أدوات سريعة -->
    <div class="card" style="margin-bottom:24px;">
        <h3 class="doctor-card-title">⚡ أدوات سريعة</h3>
        <div style="display:flex;flex-wrap:wrap;gap:12px;">
            <a href="doctor.php?page=patients&action=create" class="btn-primary" style="display:inline-flex;align-items:center;gap:6px;">
                ➕ إضافة مريض جديد
            </a>
            <a href="doctor.php?page=appointments&action=add" class="btn-secondary" style="display:inline-flex;align-items:center;gap:6px;">
                📅 حجز موعد
            </a>
            <a href="doctor.php?page=reminders&action=add" class="btn-secondary" style="display:inline-flex;align-items:center;gap:6px;">
                ⏰ إضافة تذكير
            </a>
            <a href="doctor.php?page=statistics" class="btn-secondary" style="display:inline-flex;align-items:center;gap:6px;">
                📊 إحصائيات مفصلة
            </a>
            <button onclick="window.print()" class="btn-secondary" style="display:inline-flex;align-items:center;gap:6px;">
                🖨️ طباعة الصفحة
            </button>
            <a href="doctor.php?page=dashboard&export_monthly=1&format=xls" class="btn-secondary" style="display:inline-flex;align-items:center;gap:6px;">
                📥 تصدير Excel
            </a>
        </div>
    </div>

    <div class="card doctor-monthly-report">
        <h3 class="doctor-card-title">📊 تقرير شهري</h3>
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px;">
            <a href="doctor.php?page=dashboard&export_monthly=1" class="btn-secondary">📥 تصدير CSV</a>
            <a href="doctor.php?page=dashboard&export_monthly=1&format=xls" class="btn-secondary">📥 تصدير Excel</a>
        </div>
        <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;">
            <div style="padding:16px;background:var(--bg-secondary);border-radius:8px;border-right:4px solid #0d9488;">
                <div style="font-size:1.5rem;font-weight:bold;color:#0d9488;"><?php echo $monthReport['this_month']; ?></div>
                <div style="color:var(--text-muted);margin-top:4px;">طلبات <?php echo $monthNames[(int)date('n')]; ?></div>
                <?php $diff = $monthReport['this_month'] - $monthReport['last_month']; ?>
                <div style="font-size:0.85rem;margin-top:8px;color:<?php echo $diff >= 0 ? '#22c55e' : '#ef4444'; ?>;font-weight:500;">
                    <?php echo $diff >= 0 ? '↑' : '↓'; ?> <?php echo abs($diff); ?> عن الشهر الماضي
                </div>
            </div>
            <div style="padding:16px;background:var(--bg-secondary);border-radius:8px;border-right:4px solid #3b82f6;">
                <div style="font-size:1.5rem;font-weight:bold;color:#3b82f6;"><?php echo $monthReport['last_month']; ?></div>
                <div style="color:var(--text-muted);margin-top:4px;">طلبات <?php echo $monthNames[(int)date('n')] === 'ديسمبر' ? 'نوفمبر' : $monthNames[(int)date('n') - 1] ?? 'الشهر الماضي'; ?></div>
            </div>
            <div style="padding:16px;background:var(--bg-secondary);border-radius:8px;border-right:4px solid #22c55e;">
                <div style="font-size:1.5rem;font-weight:bold;color:#22c55e;"><?php echo $monthReport['new_patients_this']; ?></div>
                <div style="color:var(--text-muted);margin-top:4px;">مرضى جدد هذا الشهر</div>
            </div>
            <?php if ($patientRetention > 0): ?>
            <div style="padding:16px;background:var(--bg-secondary);border-radius:8px;border-right:4px solid #8b5cf6;">
                <div style="font-size:1.5rem;font-weight:bold;color:#8b5cf6;"><?php echo $patientRetention; ?>%</div>
                <div style="color:var(--text-muted);margin-top:4px;">معدل الاحتفاظ بالمرضى</div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="doctor-charts-grid">
        <div class="card doctor-chart-card">
            <h3 class="doctor-card-title">الطلبات حسب الشهر</h3>
            <div style="height:240px;">
                <canvas id="chartOrders"></canvas>
            </div>
        </div>
        <div class="card doctor-chart-card">
            <h3 class="doctor-card-title">توزيع الجنس</h3>
            <div style="height:240px;">
                <canvas id="chartGender"></canvas>
            </div>
        </div>
    </div>
    
    <div class="doctor-charts-grid" style="margin-top:20px;">
        <div class="card doctor-chart-card">
            <h3 class="doctor-card-title">توزيع الفئات العمرية</h3>
            <div style="height:240px;">
                <canvas id="chartAge"></canvas>
            </div>
        </div>
        <div class="card doctor-chart-card">
            <h3 class="doctor-card-title">أكثر الفحوصات غير الطبيعية</h3>
            <?php if (empty($stats['top_tests_abnormal'])): ?>
            <p style="color:var(--text-muted);padding:20px;">لا توجد بيانات</p>
            <?php else: ?>
            <ul style="list-style:none;padding:0;margin:0;">
                <?php foreach ($stats['top_tests_abnormal'] as $t): ?>
                <li style="padding:12px 0;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center;">
                    <span style="flex:1;"><?php echo htmlspecialchars($t['test_name'], ENT_QUOTES, 'UTF-8'); ?></span>
                    <strong style="color:#ef4444;font-size:1.1rem;"><?php echo (int)$t['cnt']; ?></strong>
                </li>
                <?php endforeach; ?>
            </ul>
            <?php endif; ?>
        </div>
    </div>

    <div class="card doctor-recent-orders" id="doctorRecentOrders">
        <div class="doctor-card-header">
            <h3 class="doctor-card-title">آخر الطلبات</h3>
            <span class="doctor-shortcut-hint" title="Ctrl+K بحث سريع">⌨️ اختصارات</span>
        </div>
        <?php if (empty($recentOrders)): ?>
        <p style="color:var(--text-muted);margin:20px;">لا توجد طلبات حديثة</p>
        <?php else: ?>
        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>رقم الطلب</th>
                        <th>المريض</th>
                        <th>التاريخ</th>
                        <th>الحالة</th>
                        <th>إجراء</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($recentOrders as $o): ?>
                <tr>
                    <td><?php echo htmlspecialchars($o['order_number'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><a href="doctor.php?page=results&patient_id=<?php echo (int)$o['patient_id']; ?>" data-patient-id="<?php echo (int)$o['patient_id']; ?>"><?php echo htmlspecialchars($o['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a></td>
                    <td><?php echo date('Y-m-d H:i', strtotime($o['order_date'])); ?></td>
                    <td>
                        <?php
                        $sl = ['new'=>'جديد','in_progress'=>'قيد التنفيذ','completed'=>'مكتمل','cancelled'=>'ملغي'];
                        $sc = ['new'=>'#3b82f6','in_progress'=>'#f59e0b','completed'=>'#22c55e','cancelled'=>'#ef4444'];
                        $s = $o['status'] ?? 'new';
                        ?>
                        <span style="padding:4px 8px;background:<?php echo $sc[$s] ?? '#999'; ?>;color:white;border-radius:4px;font-size:12px;"><?php echo $sl[$s] ?? $s; ?></span>
                    </td>
                    <td><a href="doctor.php?page=results&order_id=<?php echo (int)$o['id']; ?>">عرض النتائج</a></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
(function(){
    // مخطط الطلبات الشهرية
    var ctxOrders = document.getElementById('chartOrders');
    if (ctxOrders) {
        new Chart(ctxOrders, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode(array_map(function($m) use ($monthNames) { return $monthNames[$m]; }, range(1, 12))); ?>,
                datasets: [{
                    label: 'الطلبات',
                    data: <?php echo json_encode(array_values($stats['orders_by_month'])); ?>,
                    backgroundColor: 'rgba(13, 148, 136, 0.7)',
                    borderColor: '#0d9488',
                    borderWidth: 2,
                    borderRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { 
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        padding: 12,
                        titleFont: { size: 14 },
                        bodyFont: { size: 13 }
                    }
                },
                scales: {
                    y: { 
                        beginAtZero: true,
                        ticks: { stepSize: 1 }
                    }
                }
            }
        });
    }
    
    // مخطط توزيع الجنس
    var ctxGender = document.getElementById('chartGender');
    if (ctxGender) {
        new Chart(ctxGender, {
            type: 'doughnut',
            data: {
                labels: ['ذكور', 'إناث'],
                datasets: [{
                    data: [<?php echo $genderDistribution['M']; ?>, <?php echo $genderDistribution['F']; ?>],
                    backgroundColor: ['rgba(59, 130, 246, 0.8)', 'rgba(236, 72, 153, 0.8)'],
                    borderColor: ['#3b82f6', '#ec4899'],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: { padding: 15, font: { size: 13 } }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        padding: 12
                    }
                }
            }
        });
    }
    
    // مخطط الفئات العمرية
    var ctxAge = document.getElementById('chartAge');
    if (ctxAge) {
        new Chart(ctxAge, {
            type: 'bar',
            data: {
                labels: ['0-18', '19-40', '41-60', '60+'],
                datasets: [{
                    label: 'عدد المرضى',
                    data: [
                        <?php echo $ageGroups['0-18']; ?>,
                        <?php echo $ageGroups['19-40']; ?>,
                        <?php echo $ageGroups['41-60']; ?>,
                        <?php echo $ageGroups['60+']; ?>
                    ],
                    backgroundColor: [
                        'rgba(34, 197, 94, 0.7)',
                        'rgba(59, 130, 246, 0.7)',
                        'rgba(245, 158, 11, 0.7)',
                        'rgba(239, 68, 68, 0.7)'
                    ],
                    borderColor: ['#22c55e', '#3b82f6', '#f59e0b', '#ef4444'],
                    borderWidth: 2,
                    borderRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { 
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(0,0,0,0.8)',
                        padding: 12
                    }
                },
                scales: {
                    y: { 
                        beginAtZero: true,
                        ticks: { stepSize: 1 }
                    }
                }
            }
        });
    }
    
    // تحديث عدد الإشعارات تلقائياً كل 30 ثانية
    function updateAlertsCount() {
        fetch('doctor_api.php?action=get_alerts&limit=1&unread=1')
            .then(function(r) { return r.json(); })
            .then(function(data) {
                var count = data.items ? data.items.length : 0;
                var badge = document.querySelector('.sidebar a[href*="page=alerts"]');
                if (badge) {
                    var existingBadge = badge.querySelector('span');
                    if (count > 0) {
                        if (existingBadge) {
                            existingBadge.textContent = count;
                        } else {
                            var span = document.createElement('span');
                            span.style.cssText = 'padding:2px 6px;background:#0d9488;color:white;border-radius:10px;font-size:0.75rem;margin-right:4px;';
                            span.textContent = count;
                            badge.insertBefore(span, badge.firstChild);
                        }
                    } else {
                        if (existingBadge) {
                            existingBadge.remove();
                        }
                    }
                }
            })
            .catch(function() {});
    }
    
    // تحديث عند التحميل
    updateAlertsCount();
    
    // تحديث كل 30 ثانية
    setInterval(updateAlertsCount, 30000);
})();
</script>
</body>
</html>
