<?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) {}
}
$headerDoctorPhoto = null;
try {
    $stmt = $db->prepare('SELECT photo FROM doctor_accounts WHERE id = ?');
    $stmt->execute([$doctorAuth->accountId()]);
    $row = $stmt->fetch();
    if ($row && !empty($row['photo']) && file_exists(__DIR__ . '/../../' . $row['photo'])) {
        $headerDoctorPhoto = $row['photo'];
    }
} catch (Throwable $e) {}
?>
<link rel="manifest" href="doctor-manifest.json">
<meta name="theme-color" content="#0d9488">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="csrf-token" content="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="doctor.css">
<script>window.DOCTOR_CSRF_TOKEN = "<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>";</script>
<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;">
        <button type="button" id="doctorMobileMenuBtn" class="doctor-mobile-menu-btn" aria-label="فتح القائمة" title="القائمة">
            <span class="doctor-hamburger"></span><span class="doctor-hamburger"></span><span class="doctor-hamburger"></span>
        </button>
        <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" style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
        <a href="doctor.php?page=profile" style="display:flex;align-items:center;gap:10px;text-decoration:none;color:inherit;">
            <div style="width:40px;height:40px;border-radius:50%;overflow:hidden;background:rgba(255,255,255,0.15);flex-shrink:0;border:2px solid rgba(255,255,255,0.25);display:flex;align-items:center;justify-content:center;">
                <?php if ($headerDoctorPhoto): ?>
                <img src="<?php echo htmlspecialchars($headerDoctorPhoto, ENT_QUOTES, 'UTF-8'); ?>" alt="" style="width:100%;height:100%;object-fit:cover;">
                <?php else: ?>
                <span style="font-size:1.1rem;">👨‍⚕️</span>
                <?php endif; ?>
            </div>
            <span style="color:rgba(255,255,255,0.95);font-weight:500;">د. <?php echo htmlspecialchars($_SESSION['doctor_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span>
        </a>
        <span style="color:rgba(255,255,255,0.55);font-size:0.9rem;">|</span>
        <span style="color:rgba(255,255,255,0.7);font-size:0.9rem;"><?php echo htmlspecialchars($_SESSION['doctor_tenant_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span>
        <?php if (!empty($_SESSION['unified_logged_in']) && is_array($_SESSION['unified_available_portals'] ?? null) && count($_SESSION['unified_available_portals']) > 1): ?>
        <a href="index.php?page=choose_portal" class="btn-secondary" style="padding:4px 10px;text-decoration:none;">تبديل البوابة</a>
        <?php endif; ?>
        <a href="doctor.php?page=profile" class="<?php echo $currentPage === 'profile' ? 'active' : ''; ?>" style="color:#14b8a6;">الملف الشخصي</a>
        <button type="button" id="doctorDarkMode" title="الوضع الداكن" style="background:transparent;border:none;cursor:pointer;font-size:1.2rem;margin-right:8px;">🌙</button>
        <form method="post" action="doctor.php?page=logout" style="display:inline;">
            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
            <button type="submit" class="btn-link" style="background:none;border:none;padding:0;color:#14b8a6;cursor:pointer;">تسجيل الخروج</button>
        </form>
        <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="doctor-mobile-overlay" id="doctorMobileOverlay"></div>
<div class="layout">
    <nav class="sidebar doctor-sidebar" id="doctorSidebar" 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=booking_link" class="<?php echo $currentPage === 'booking_link' ? '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=reports" class="<?php echo $currentPage === 'reports' ? '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') { 
            if (document.body.classList.contains('doctor-mobile-menu-open')) document.body.classList.remove('doctor-mobile-menu-open');
            else { 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 ? 'الوضع الفاتح' : 'الوضع الداكن';
        });
    }
    // PWA registration
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('doctor-sw.js').catch(function(){});
    }
    // الإشعارات تُدار من DoctorNotifications في doctor.js (توحيد الـ polling)
    if (window._lastCritical === undefined) window._lastCritical = 0;
    // Request notification permission on first visit
    if ('Notification' in window && Notification.permission === 'default') {
        setTimeout(function(){ Notification.requestPermission(); }, 3000);
    }
    // القائمة المنسدلة للموبايل
    var menuBtn = document.getElementById('doctorMobileMenuBtn');
    var sidebar = document.getElementById('doctorSidebar');
    var overlay = document.getElementById('doctorMobileOverlay');
    function toggleMobileMenu() {
        document.body.classList.toggle('doctor-mobile-menu-open');
    }
    function closeMobileMenu() {
        document.body.classList.remove('doctor-mobile-menu-open');
    }
    if (menuBtn) menuBtn.addEventListener('click', toggleMobileMenu);
    if (overlay) overlay.addEventListener('click', closeMobileMenu);
    document.querySelectorAll('.doctor-sidebar a, .doctor-sidebar button').forEach(function(el) {
        el.addEventListener('click', function() { if (window.innerWidth <= 992) closeMobileMenu(); });
    });
})();
</script>
