<?php
$currentPage = $page ?? 'dashboard';
$headerCriticalCount = 0;
$headerRemindersCount = 0;
$quickPatients = [];
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 r.flag = 'C' $tenantCond $doctorCond");
    $stmt->execute();
    $headerCriticalCount = (int)$stmt->fetchColumn();
} catch (Throwable $e) {}
try {
    $db->query('SELECT patient_id FROM doctor_favorite_patients LIMIT 1');
    $stmt = $db->prepare("SELECT p.id, p.full_name FROM patients p JOIN doctor_favorite_patients f ON f.patient_id = p.id WHERE f.doctor_account_id = ? ORDER BY f.created_at DESC LIMIT 5");
    $stmt->execute([$doctorAuth->accountId()]);
    $quickPatients = $stmt->fetchAll();
} catch (Throwable $e) {
    $quickPatients = [];
}
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 reminder_date < CURDATE() AND is_done = 0');
    $stmt->execute([$doctorAuth->accountId()]);
    $headerRemindersCount = (int)$stmt->fetchColumn();
} catch (Throwable $e) {}
if (empty($quickPatients)) {
    try {
        $stmt = $db->prepare("SELECT p.id, p.full_name FROM patients p JOIN lab_orders o ON o.patient_id = p.id WHERE 1=1 $tenantCond $doctorCond GROUP BY p.id ORDER BY MAX(o.order_date) DESC LIMIT 5");
        $stmt->execute();
        $quickPatients = $stmt->fetchAll();
    } catch (Throwable $e2) {}
}
?>
<link rel="stylesheet" href="doctor.css">
<script src="js/doctor.js"></script>
<header class="top-bar doctor-header">
    <div class="top-bar-left" style="display:flex;align-items:center;gap:16px;">
        <strong>🩺 Smart Doctor</strong>
        <?php if ($headerCriticalCount > 0): ?>
        <a href="doctor.php?page=results&critical=1" style="display:inline-flex;align-items:center;gap:6px;padding:6px 12px;background:#dc2626;color:white;border-radius:8px;text-decoration:none;font-size:0.9rem;" title="نتائج حرجة للمراجعة">
            ⚠️ <?php echo $headerCriticalCount; ?>
        </a>
        <?php endif; ?>
        <form method="get" action="doctor.php" class="header-search" style="margin:0;">
            <input type="hidden" name="page" value="search">
            <input type="search" name="q" placeholder="بحث مريض أو طلب..." value="<?php echo htmlspecialchars(($currentPage === 'search' ? ($_GET['q'] ?? '') : ''), ENT_QUOTES, 'UTF-8'); ?>" style="min-width:180px;padding:6px 12px;">
            <button type="submit" style="padding:6px 12px;">بحث</button>
        </form>
    </div>
    <div class="top-bar-right">
        <span style="color:rgba(255,255,255,0.9);">د. <?php echo htmlspecialchars($_SESSION['doctor_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span>
        <span style="color:rgba(255,255,255,0.6);font-size:0.9rem;">| <?php echo htmlspecialchars($_SESSION['doctor_tenant_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span>
        <a href="doctor.php?page=profile" class="<?php echo $currentPage === 'profile' ? 'active' : ''; ?>" style="color:#14b8a6;margin-left:12px;">الملف الشخصي</a>
        <button type="button" id="doctorDarkMode" title="الوضع الداكن" style="background:transparent;border:none;cursor:pointer;font-size:1.2rem;margin-right:8px;">🌙</button>
        <a href="doctor.php?page=logout" style="color:#14b8a6;">تسجيل الخروج</a>
        <span style="font-size:0.75rem;color:rgba(255,255,255,0.5);" title="Ctrl+K بحث، Ctrl+P طباعة، Ctrl+H الرئيسية">⌨️</span>
    </div>
</header>
<div class="layout">
    <nav class="sidebar" style="background:#0f172a;">
        <ul>
            <li><a href="doctor.php?page=dashboard" class="<?php echo $currentPage === 'dashboard' ? 'active' : ''; ?>">🏠 الرئيسية</a></li>
            <li><a href="doctor.php?page=patients" class="<?php echo $currentPage === 'patients' ? 'active' : ''; ?>">👥 المرضى</a></li>
            <li><a href="doctor.php?page=reminders" class="<?php echo $currentPage === 'reminders' ? 'active' : ''; ?>">⏰ التذكيرات<?php if ($headerRemindersCount > 0): ?><span style="padding:2px 6px;background:#dc2626;color:white;border-radius:10px;font-size:0.75rem;margin-right:4px;"><?php echo $headerRemindersCount; ?></span><?php endif; ?></a></li>
            <li><a href="doctor.php?page=appointments" class="<?php echo $currentPage === 'appointments' ? 'active' : ''; ?>" title="حجز مواعيد المرضى">📅 المواعيد</a></li>
            <li><a href="doctor.php?page=alerts" class="<?php echo $currentPage === 'alerts' ? 'active' : ''; ?>">🔔 التنبيهات<?php 
                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()]);
                    $alertCount = (int)$stmt->fetchColumn();
                    if ($alertCount > 0) echo '<span style="padding:2px 6px;background:#0d9488;color:white;border-radius:10px;font-size:0.75rem;margin-right:4px;">' . $alertCount . '</span>';
                } catch (Throwable $e) {}
            ?></a></li>
            <li><a href="doctor.php?page=tasks" class="<?php echo $currentPage === 'tasks' ? 'active' : ''; ?>">✅ المهام</a></li>
            <li><a href="doctor.php?page=results" class="<?php echo $currentPage === 'results' ? 'active' : ''; ?>">📋 النتائج</a></li>
            <li><a href="doctor.php?page=accounts" class="<?php echo $currentPage === 'accounts' ? 'active' : ''; ?>">💰 الحسابات المالية</a></li>
            <li><a href="doctor.php?page=statistics" class="<?php echo $currentPage === 'statistics' ? 'active' : ''; ?>">📊 الإحصائيات</a></li>
            <li><a href="doctor.php?page=search" class="<?php echo $currentPage === 'search' ? 'active' : ''; ?>">🔍 بحث</a></li>
            <li><a href="doctor.php?page=trend" class="<?php echo $currentPage === 'trend' ? 'active' : ''; ?>">📈 مقارنة النتائج</a></li>
            <li><a href="doctor.php?page=profile" class="<?php echo $currentPage === 'profile' ? 'active' : ''; ?>">👤 الملف الشخصي</a></li>
            <?php if (!empty($quickPatients)): ?>
            <li class="sidebar-group">الوصول السريع</li>
            <?php foreach ($quickPatients as $qp): ?>
            <li class="sidebar-quick-item">
                <a href="doctor.php?page=results&patient_id=<?php echo (int)$qp['id']; ?>" data-patient-id="<?php echo (int)$qp['id']; ?>" class="sidebar-quick-name"><?php echo htmlspecialchars(mb_substr($qp['full_name'], 0, 20), ENT_QUOTES, 'UTF-8'); ?><?php echo mb_strlen($qp['full_name']) > 20 ? '...' : ''; ?></a>
                <a href="doctor.php?page=trend&patient_id=<?php echo (int)$qp['id']; ?>" class="sidebar-quick-icon" title="مقارنة النتائج">📈</a>
            </li>
            <?php endforeach; ?>
            <?php endif; ?>
            <li style="border-top:1px solid rgba(255,255,255,0.15);margin-top:8px;padding-top:8px;">
                <a href="index.php" style="color:rgba(255,255,255,0.7);">← نظام المختبر</a>
            </li>
            <li style="margin-top:8px;">
                <button type="button" onclick="document.getElementById('doctorShortcutsOverlay').classList.add('doctor-shortcuts-show')" style="background:transparent;border:none;color:rgba(255,255,255,0.5);cursor:pointer;font-size:0.8rem;">⌨️ اختصارات (?)</button>
            </li>
        </ul>
    </nav>
    <div id="doctorShortcutsOverlay" class="doctor-shortcuts-overlay" onclick="if(event.target===this)this.classList.remove('doctor-shortcuts-show')">
        <div class="doctor-shortcuts-modal" onclick="event.stopPropagation()">
            <h3>⌨️ اختصارات لوحة المفاتيح</h3>
            <table class="doctor-shortcuts-table">
                <tr><td><kbd>Ctrl</kbd> + <kbd>K</kbd></td><td>بحث سريع</td></tr>
                <tr><td><kbd>Ctrl</kbd> + <kbd>H</kbd></td><td>الرئيسية</td></tr>
                <tr><td><kbd>Ctrl</kbd> + <kbd>B</kbd></td><td>إظهار/إخفاء الشريط</td></tr>
                <tr><td><kbd>?</kbd></td><td>عرض الاختصارات</td></tr>
                <tr><td><kbd>Esc</kbd></td><td>إغلاق / إلغاء</td></tr>
            </table>
            <button type="button" onclick="document.getElementById('doctorShortcutsOverlay').classList.remove('doctor-shortcuts-show')" class="btn-primary">إغلاق</button>
        </div>
    </div>
<script>
(function(){
    document.addEventListener('keydown', function(e){
        if (e.ctrlKey || e.metaKey) {
            if (e.key === 'k') { e.preventDefault(); document.querySelector('form[action*="page=search"]')?.querySelector('input[type="search"]')?.focus(); }
            if (e.key === 'p' && document.querySelector('a[href*="page=print"]')) { e.preventDefault(); document.querySelector('a[href*="page=print"]')?.click(); }
            if (e.key === 'h') { e.preventDefault(); location.href='doctor.php?page=dashboard'; }
        }
        if (e.key === 'Escape') { var s=document.querySelector('form[action*="page=search"]')?.querySelector('input[type="search"]'); if(s&&document.activeElement===s) s.blur(); }
    });
    var btn = document.getElementById('doctorDarkMode');
    var isDark = localStorage.getItem('doctor_dark_mode') === '1';
    if (isDark) document.body.classList.add('dark-mode');
    if (btn) {
        btn.textContent = isDark ? '☀️' : '🌙';
        btn.title = isDark ? 'الوضع الفاتح' : 'الوضع الداكن';
        btn.addEventListener('click', function(){
            isDark = document.body.classList.toggle('dark-mode');
            localStorage.setItem('doctor_dark_mode', isDark ? '1' : '0');
            btn.textContent = isDark ? '☀️' : '🌙';
            btn.title = isDark ? 'الوضع الفاتح' : 'الوضع الداكن';
        });
    }
})();
</script>
