<?php
/**
 * بحث سريع - المرضى والطلبات
 */
$q = trim($_GET['q'] ?? '');
$searchType = $_GET['type'] ?? 'all';
$dateFrom = trim($_GET['from'] ?? '');
$dateTo = trim($_GET['to'] ?? '');
$patients = [];
$orders = [];

$recentSearches = [];
try {
    $db->query('SELECT id FROM doctor_search_history LIMIT 1');
    $stmt = $db->prepare('SELECT search_query, search_type FROM doctor_search_history WHERE doctor_account_id = ? ORDER BY created_at DESC LIMIT 8');
    $stmt->execute([$doctorAuth->accountId()]);
    $recentSearches = $stmt->fetchAll();
} catch (Throwable $e) {}

if (strlen($q) >= 2) {
    try {
        $like = '%' . $q . '%';
        $tenantPat = '';
        try { $db->query('SELECT tenant_id FROM patients LIMIT 1'); $tenantPat = ' AND p.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
        $dateFilter = '';
        $dateParams = [];
        if ($dateFrom !== '') { $dateFilter .= ' AND o.order_date >= ?'; $dateParams[] = $dateFrom . ' 00:00:00'; }
        if ($dateTo !== '') { $dateFilter .= ' AND o.order_date <= ?'; $dateParams[] = $dateTo . ' 23:59:59'; }

        if ($searchType !== 'order') {
            // بحث في المرضى - نسخة محسّنة
            try {
                // التحقق من وجود عمود national_id
                $hasNationalId = false;
                try {
                    $db->query('SELECT national_id FROM patients LIMIT 1');
                    $hasNationalId = true;
                } catch (Throwable $e) {}
                
                if ($dateFilter === '') {
                    // بدون فلترة التاريخ - بحث أسرع
                    if ($hasNationalId) {
                        $sql = "SELECT DISTINCT p.id, p.patient_code, p.full_name, p.phone, p.date_of_birth, p.gender,
                            COALESCE((SELECT COUNT(*) FROM lab_orders o2 WHERE o2.patient_id = p.id AND o2.tenant_id = ? AND o2.doctor_id = ?), 0) AS orders_count
                            FROM patients p
                            WHERE (p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ? OR p.national_id LIKE ?) $tenantPat
                            ORDER BY 
                                CASE WHEN p.full_name LIKE ? THEN 1 ELSE 2 END,
                                CASE WHEN EXISTS (SELECT 1 FROM lab_orders o3 WHERE o3.patient_id = p.id AND o3.tenant_id = ? AND o3.doctor_id = ?) THEN 1 ELSE 2 END,
                                p.full_name
                            LIMIT 20";
                        $exactLike = $q . '%';
                        $stmt = $db->prepare($sql);
                        $stmt->execute([$tenantId, $doctorId, $like, $like, $like, $like, $exactLike, $tenantId, $doctorId]);
                    } else {
                        $sql = "SELECT DISTINCT p.id, p.patient_code, p.full_name, p.phone, p.date_of_birth, p.gender,
                            COALESCE((SELECT COUNT(*) FROM lab_orders o2 WHERE o2.patient_id = p.id AND o2.tenant_id = ? AND o2.doctor_id = ?), 0) AS orders_count
                            FROM patients p
                            WHERE (p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ?) $tenantPat
                            ORDER BY 
                                CASE WHEN p.full_name LIKE ? THEN 1 ELSE 2 END,
                                CASE WHEN EXISTS (SELECT 1 FROM lab_orders o3 WHERE o3.patient_id = p.id AND o3.tenant_id = ? AND o3.doctor_id = ?) THEN 1 ELSE 2 END,
                                p.full_name
                            LIMIT 20";
                        $exactLike = $q . '%';
                        $stmt = $db->prepare($sql);
                        $stmt->execute([$tenantId, $doctorId, $like, $like, $like, $exactLike, $tenantId, $doctorId]);
                    }
                } else {
                    // مع فلترة التاريخ
                    if ($hasNationalId) {
                        $sql = "SELECT DISTINCT p.id, p.patient_code, p.full_name, p.phone, p.date_of_birth, p.gender,
                            COUNT(DISTINCT o.id) AS orders_count
                            FROM patients p
                            INNER JOIN lab_orders o ON o.patient_id = p.id AND o.tenant_id = ? AND o.doctor_id = ? $dateFilter
                            WHERE (p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ? OR p.national_id LIKE ?) $tenantPat
                            GROUP BY p.id
                            ORDER BY 
                                CASE WHEN p.full_name LIKE ? THEN 1 ELSE 2 END,
                                p.full_name
                            LIMIT 20";
                        $exactLike = $q . '%';
                        $params = array_merge([$tenantId, $doctorId], $dateParams, [$like, $like, $like, $like, $exactLike]);
                    } else {
                        $sql = "SELECT DISTINCT p.id, p.patient_code, p.full_name, p.phone, p.date_of_birth, p.gender,
                            COUNT(DISTINCT o.id) AS orders_count
                            FROM patients p
                            INNER JOIN lab_orders o ON o.patient_id = p.id AND o.tenant_id = ? AND o.doctor_id = ? $dateFilter
                            WHERE (p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ?) $tenantPat
                            GROUP BY p.id
                            ORDER BY 
                                CASE WHEN p.full_name LIKE ? THEN 1 ELSE 2 END,
                                p.full_name
                            LIMIT 20";
                        $exactLike = $q . '%';
                        $params = array_merge([$tenantId, $doctorId], $dateParams, [$like, $like, $like, $exactLike]);
                    }
                    $stmt = $db->prepare($sql);
                    $stmt->execute($params);
                }
                $patients = $stmt->fetchAll();
            } catch (Throwable $e) {
                error_log("Search patients error: " . $e->getMessage());
                $patients = [];
            }
        }
        
        if ($searchType !== 'patient') {
            // بحث في الطلبات - نسخة محسّنة
            try {
                // التحقق من وجود عمود notes
                $hasNotes = false;
                try {
                    $db->query('SELECT notes FROM lab_orders LIMIT 1');
                    $hasNotes = true;
                } catch (Throwable $e) {}
                
                if ($hasNotes) {
                    $sql = "SELECT o.id, o.order_number, o.order_date, o.status, 
                        p.full_name AS patient_name, p.id AS patient_id, p.patient_code,
                        (SELECT COUNT(*) FROM order_items oi2 WHERE oi2.order_id = o.id) AS tests_count
                        FROM lab_orders o 
                        JOIN patients p ON p.id = o.patient_id
                        WHERE (o.order_number LIKE ? OR p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ? OR o.notes LIKE ?)
                        AND o.tenant_id = ? AND o.doctor_id = ? $dateFilter
                        ORDER BY 
                            CASE WHEN o.order_number LIKE ? THEN 1 ELSE 2 END,
                            o.order_date DESC
                        LIMIT 20";
                    $exactLike = $q . '%';
                    $params = array_merge([$like, $like, $like, $like, $like, $tenantId, $doctorId], $dateParams, [$exactLike]);
                } else {
                    $sql = "SELECT o.id, o.order_number, o.order_date, o.status, 
                        p.full_name AS patient_name, p.id AS patient_id, p.patient_code,
                        (SELECT COUNT(*) FROM order_items oi2 WHERE oi2.order_id = o.id) AS tests_count
                        FROM lab_orders o 
                        JOIN patients p ON p.id = o.patient_id
                        WHERE (o.order_number LIKE ? OR p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ?)
                        AND o.tenant_id = ? AND o.doctor_id = ? $dateFilter
                        ORDER BY 
                            CASE WHEN o.order_number LIKE ? THEN 1 ELSE 2 END,
                            o.order_date DESC
                        LIMIT 20";
                    $exactLike = $q . '%';
                    $params = array_merge([$like, $like, $like, $like, $tenantId, $doctorId], $dateParams, [$exactLike]);
                }
                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                $orders = $stmt->fetchAll();
            } catch (Throwable $e) {
                error_log("Search orders error: " . $e->getMessage());
                $orders = [];
            }
        }
    } catch (Throwable $e) {}
}
?>
<!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">
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content">
    <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>

    <!-- نموذج البحث المحسّن -->
    <div class="card" style="margin-bottom:24px;background:linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);border:2px solid var(--primary, #0d9488);">
        <form method="get" class="doctor-search-form" id="doctorSearchForm" style="padding:24px;">
            <input type="hidden" name="page" value="search">
            
            <!-- شريط البحث الرئيسي -->
            <div class="doctor-search-row" style="margin-bottom:20px;">
                <div style="position:relative;flex:1;">
                    <input type="search" name="q" id="doctorSearchInput" 
                        value="<?php echo htmlspecialchars($q, ENT_QUOTES, 'UTF-8'); ?>" 
                        placeholder="🔍 ابحث عن: اسم المريض، الرقم، رقم الطلب، الهاتف..." 
                        autofocus
                        style="width:100%;padding:14px 50px 14px 16px;font-size:1.1rem;border-radius:12px;border:2px solid var(--border);transition:all 0.3s;">
                    <button type="submit" style="position:absolute;left:8px;top:50%;transform:translateY(-50%);background:var(--primary);color:white;border:none;padding:10px 20px;border-radius:8px;cursor:pointer;font-weight:600;font-size:1rem;">
                        بحث
                    </button>
                </div>
            </div>

            <!-- الفلاتر -->
            <div class="doctor-search-filters" style="display:grid;grid-template-columns:auto 1fr 1fr;gap:16px;align-items:center;padding:16px;background:var(--bg-secondary);border-radius:10px;">
                <div style="display:flex;gap:16px;align-items:center;flex-wrap:wrap;">
                    <strong style="color:var(--text-primary);">النوع:</strong>
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 12px;border-radius:8px;transition:background 0.2s;" onmouseover="this.style.background='rgba(13,148,136,0.1)'" onmouseout="this.style.background='transparent'">
                        <input type="radio" name="type" value="all" <?php echo $searchType === 'all' ? 'checked' : ''; ?> style="cursor:pointer;">
                        <span>الكل</span>
                    </label>
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 12px;border-radius:8px;transition:background 0.2s;" onmouseover="this.style.background='rgba(13,148,136,0.1)'" onmouseout="this.style.background='transparent'">
                        <input type="radio" name="type" value="patient" <?php echo $searchType === 'patient' ? 'checked' : ''; ?> style="cursor:pointer;">
                        <span>👥 المرضى فقط</span>
                    </label>
                    <label style="display:flex;align-items:center;gap:6px;cursor:pointer;padding:8px 12px;border-radius:8px;transition:background 0.2s;" onmouseover="this.style.background='rgba(13,148,136,0.1)'" onmouseout="this.style.background='transparent'">
                        <input type="radio" name="type" value="order" <?php echo $searchType === 'order' ? 'checked' : ''; ?> style="cursor:pointer;">
                        <span>📋 الطلبات فقط</span>
                    </label>
                </div>
                
                <div style="display:flex;gap:12px;align-items:center;">
                    <label style="display:flex;align-items:center;gap:8px;font-weight:500;">
                        <span>من:</span>
                        <input type="date" name="from" value="<?php echo htmlspecialchars($dateFrom, ENT_QUOTES, 'UTF-8'); ?>" style="padding:8px 12px;border-radius:8px;border:1px solid var(--border);">
                    </label>
                </div>
                
                <div style="display:flex;gap:12px;align-items:center;">
                    <label style="display:flex;align-items:center;gap:8px;font-weight:500;">
                        <span>إلى:</span>
                        <input type="date" name="to" value="<?php echo htmlspecialchars($dateTo, ENT_QUOTES, 'UTF-8'); ?>" style="padding:8px 12px;border-radius:8px;border:1px solid var(--border);">
                    </label>
                </div>
            </div>

            <!-- نصائح سريعة -->
            <div style="margin-top:16px;padding:12px;background:#ecfdf5;border-radius:8px;border-right:4px solid #0d9488;">
                <div style="font-size:0.9rem;color:#047857;">
                    <strong>💡 نصائح:</strong> استخدم <kbd style="padding:2px 6px;background:white;border-radius:4px;">Ctrl+K</kbd> للبحث السريع، 
                    أو ابحث بالاسم الكامل للحصول على نتائج أدق
                </div>
            </div>
        </form>
    </div>

    <?php if ($q === ''): ?>
    <!-- حالة فارغة - بدون بحث -->
    <div class="card" style="text-align:center;padding:60px 24px;background:linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);">
        <div style="font-size:4rem;margin-bottom:20px;opacity:0.3;">🔍</div>
        <h2 style="margin:0 0 12px;color:var(--text-primary);">ابدأ البحث الآن</h2>
        <p style="color:var(--text-muted);margin:0 0 24px;font-size:1.05rem;">
            أدخل كلمة بحث (حرفين على الأقل) للبحث في المرضى والطلبات
        </p>
        <div style="display:inline-flex;gap:8px;padding:12px 20px;background:white;border-radius:10px;box-shadow:0 2px 8px rgba(0,0,0,0.1);">
            <kbd style="padding:4px 8px;background:var(--bg-secondary);border-radius:4px;font-size:0.9rem;">Ctrl+K</kbd>
            <span style="color:var(--text-muted);">للبحث السريع</span>
        </div>
        
        <?php if (!empty($recentSearches)): ?>
        <div class="doctor-recent-search" style="margin-top:40px;padding-top:32px;border-top:2px solid var(--border);">
            <h3 style="margin:0 0 16px;font-size:1.1rem;color:var(--text-primary);">📚 عمليات بحث سابقة</h3>
            <div class="doctor-recent-search-tags" style="display:flex;flex-wrap:wrap;gap:10px;justify-content:center;">
                <?php foreach ($recentSearches as $rs): ?>
                <a href="doctor.php?page=search&q=<?php echo urlencode($rs['search_query']); ?>&type=<?php echo urlencode($rs['search_type'] ?? 'all'); ?>" 
                    class="doctor-search-tag" 
                    style="padding:10px 18px;background:white;border:2px solid var(--primary);border-radius:20px;text-decoration:none;color:var(--primary);font-weight:500;transition:all 0.2s;display:inline-flex;align-items:center;gap:6px;">
                    <span>🔍</span>
                    <span><?php echo htmlspecialchars($rs['search_query'], ENT_QUOTES, 'UTF-8'); ?></span>
                </a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
    <?php elseif (strlen($q) < 2): ?>
    <div class="alert alert-warning">أدخل حرفين على الأقل للبحث.</div>
    <?php else: ?>
    <?php if (!empty($patients)): ?>
    <div class="card" style="margin-bottom:24px;border-right:4px solid #0d9488;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:16px;border-bottom:2px solid var(--border);">
            <h3 style="margin:0;font-size:1.3rem;display:flex;align-items:center;gap:10px;">
                <span>👥</span> المرضى
            </h3>
            <span style="padding:6px 14px;background:var(--primary);color:white;border-radius:20px;font-weight:600;font-size:0.9rem;">
                <?php echo count($patients); ?> نتيجة
            </span>
        </div>
        <div class="table-wrapper">
            <table class="table" style="border-collapse:separate;border-spacing:0;">
                <thead>
                    <tr style="background:linear-gradient(135deg, #0f172a, #1e3a5f);color:white;">
                        <th style="padding:14px 16px;text-align:right;font-weight:600;">الرقم</th>
                        <th style="padding:14px 16px;text-align:right;font-weight:600;">الاسم</th>
                        <th style="padding:14px 16px;text-align:right;font-weight:600;">العمر</th>
                        <th style="padding:14px 16px;text-align:right;font-weight:600;">الهاتف</th>
                        <th style="padding:14px 16px;text-align:center;font-weight:600;">الطلبات</th>
                        <th style="padding:14px 16px;text-align:center;font-weight:600;">إجراءات</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($patients as $p): 
                    $age = $p['date_of_birth'] ? (date('Y') - date('Y', strtotime($p['date_of_birth']))) : '-';
                ?>
                <tr style="transition:background 0.2s;border-bottom:1px solid var(--border);">
                    <td style="padding:14px 16px;">
                        <span style="font-family:monospace;color:var(--primary);font-weight:600;">
                            <?php echo htmlspecialchars($p['patient_code'], ENT_QUOTES, 'UTF-8'); ?>
                        </span>
                    </td>
                    <td style="padding:14px 16px;">
                        <a href="doctor.php?page=results&patient_id=<?php echo (int)$p['id']; ?>" 
                            data-patient-id="<?php echo (int)$p['id']; ?>"
                            style="font-weight:600;color:var(--text-primary);text-decoration:none;display:flex;align-items:center;gap:8px;"
                            onmouseover="this.style.color='var(--primary)'" 
                            onmouseout="this.style.color='var(--text-primary)'">
                            <span><?php echo htmlspecialchars($p['full_name'], ENT_QUOTES, 'UTF-8'); ?></span>
                        </a>
                    </td>
                    <td style="padding:14px 16px;color:var(--text-muted);">
                        <?php echo $age; ?> <?php echo $age !== '-' ? 'سنة' : ''; ?>
                        <?php if ($p['gender']): ?>
                        <span style="margin-right:8px;color:var(--text-muted);">|</span>
                        <?php echo $p['gender'] === 'M' ? '👨' : ($p['gender'] === 'F' ? '👩' : ''); ?>
                        <?php endif; ?>
                    </td>
                    <td style="padding:14px 16px;">
                        <?php if (!empty($p['phone'])): ?>
                        <a href="tel:<?php echo htmlspecialchars(preg_replace('/[^0-9+]/', '', $p['phone']), ENT_QUOTES, 'UTF-8'); ?>" 
                            style="color:var(--primary);text-decoration:none;display:inline-flex;align-items:center;gap:4px;">
                            <span>📞</span>
                            <span><?php echo htmlspecialchars($p['phone'], ENT_QUOTES, 'UTF-8'); ?></span>
                        </a>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">-</span>
                        <?php endif; ?>
                    </td>
                    <td style="padding:14px 16px;text-align:center;">
                        <span style="display:inline-flex;align-items:center;gap:6px;padding:6px 12px;background:var(--bg-secondary);border-radius:20px;font-weight:600;">
                            <span>📋</span>
                            <span><?php echo (int)$p['orders_count']; ?></span>
                        </span>
                    </td>
                    <td style="padding:14px 16px;">
                        <div style="display:flex;gap:8px;justify-content:center;flex-wrap:wrap;">
                            <a href="doctor.php?page=results&patient_id=<?php echo (int)$p['id']; ?>" 
                                class="btn-sm" 
                                style="padding:6px 14px;background:var(--primary);color:white;border-radius:6px;text-decoration:none;font-size:0.85rem;font-weight:500;">
                                عرض
                            </a>
                            <a href="doctor.php?page=trend&patient_id=<?php echo (int)$p['id']; ?>" 
                                title="مقارنة النتائج"
                                style="padding:6px 12px;background:var(--bg-secondary);color:var(--text-primary);border-radius:6px;text-decoration:none;font-size:0.9rem;">
                                📈
                            </a>
                            <button onclick="window.DoctorQuickInfo && window.DoctorQuickInfo.show(<?php echo (int)$p['id']; ?>)" 
                                title="معلومات سريعة"
                                style="padding:6px 12px;background:var(--bg-secondary);color:var(--text-primary);border:none;border-radius:6px;cursor:pointer;font-size:0.9rem;">
                                ⚡
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($orders)): ?>
    <div class="card" style="border-right:4px solid #3b82f6;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:16px;border-bottom:2px solid var(--border);">
            <h3 style="margin:0;font-size:1.3rem;display:flex;align-items:center;gap:10px;">
                <span>📋</span> الطلبات
            </h3>
            <span style="padding:6px 14px;background:#3b82f6;color:white;border-radius:20px;font-weight:600;font-size:0.9rem;">
                <?php echo count($orders); ?> نتيجة
            </span>
        </div>
        <div class="table-wrapper">
            <table class="table" style="border-collapse:separate;border-spacing:0;">
                <thead>
                    <tr style="background:linear-gradient(135deg, #1e3a5f, #3b82f6);color:white;">
                        <th style="padding:14px 16px;text-align:right;font-weight:600;">رقم الطلب</th>
                        <th style="padding:14px 16px;text-align:right;font-weight:600;">المريض</th>
                        <th style="padding:14px 16px;text-align:right;font-weight:600;">التاريخ</th>
                        <th style="padding:14px 16px;text-align:center;font-weight:600;">الفحوصات</th>
                        <th style="padding:14px 16px;text-align:center;font-weight:600;">الحالة</th>
                        <th style="padding:14px 16px;text-align:center;font-weight:600;">إجراءات</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($orders as $o): 
                    $statusLabels = ['new' => 'جديد', 'in_progress' => 'قيد التنفيذ', 'completed' => 'مكتمل', 'cancelled' => 'ملغي'];
                    $statusColors = ['new' => '#3b82f6', 'in_progress' => '#f59e0b', 'completed' => '#22c55e', 'cancelled' => '#ef4444'];
                    $status = $o['status'] ?? 'new';
                ?>
                <tr style="transition:background 0.2s;border-bottom:1px solid var(--border);">
                    <td style="padding:14px 16px;">
                        <span style="font-family:monospace;color:var(--primary);font-weight:600;">
                            <?php echo htmlspecialchars($o['order_number'], ENT_QUOTES, 'UTF-8'); ?>
                        </span>
                    </td>
                    <td style="padding:14px 16px;">
                        <a href="doctor.php?page=results&patient_id=<?php echo (int)$o['patient_id']; ?>" 
                            style="font-weight:600;color:var(--text-primary);text-decoration:none;display:flex;align-items:center;gap:8px;"
                            onmouseover="this.style.color='var(--primary)'" 
                            onmouseout="this.style.color='var(--text-primary)'">
                            <span>👤</span>
                            <span><?php echo htmlspecialchars($o['patient_name'], ENT_QUOTES, 'UTF-8'); ?></span>
                        </a>
                        <?php if (!empty($o['patient_code'])): ?>
                        <div style="font-size:0.85rem;color:var(--text-muted);margin-top:4px;">
                            <?php echo htmlspecialchars($o['patient_code'], ENT_QUOTES, 'UTF-8'); ?>
                        </div>
                        <?php endif; ?>
                    </td>
                    <td style="padding:14px 16px;color:var(--text-muted);">
                        <div style="display:flex;align-items:center;gap:6px;">
                            <span>📅</span>
                            <span><?php echo date('Y-m-d', strtotime($o['order_date'])); ?></span>
                        </div>
                        <div style="font-size:0.85rem;margin-top:4px;color:var(--text-muted);">
                            <?php echo date('H:i', strtotime($o['order_date'])); ?>
                        </div>
                    </td>
                    <td style="padding:14px 16px;text-align:center;">
                        <span style="display:inline-flex;align-items:center;gap:6px;padding:6px 12px;background:var(--bg-secondary);border-radius:20px;font-weight:600;">
                            <span>🧪</span>
                            <span><?php echo (int)($o['tests_count'] ?? 0); ?></span>
                        </span>
                    </td>
                    <td style="padding:14px 16px;text-align:center;">
                        <span style="padding:6px 14px;background:<?php echo $statusColors[$status] ?? '#999'; ?>20;color:<?php echo $statusColors[$status] ?? '#999'; ?>;border-radius:20px;font-weight:600;font-size:0.85rem;">
                            <?php echo $statusLabels[$status] ?? $status; ?>
                        </span>
                    </td>
                    <td style="padding:14px 16px;">
                        <div style="display:flex;gap:8px;justify-content:center;flex-wrap:wrap;">
                            <a href="doctor.php?page=results&order_id=<?php echo (int)$o['id']; ?>" 
                                class="btn-sm" 
                                style="padding:6px 14px;background:var(--primary);color:white;border-radius:6px;text-decoration:none;font-size:0.85rem;font-weight:500;">
                                عرض النتائج
                            </a>
                            <?php if (!empty($o['patient_id'])): ?>
                            <a href="doctor.php?page=trend&patient_id=<?php echo (int)$o['patient_id']; ?>" 
                                title="مقارنة النتائج"
                                style="padding:6px 12px;background:var(--bg-secondary);color:var(--text-primary);border-radius:6px;text-decoration:none;font-size:0.9rem;">
                                📈
                            </a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <?php if (empty($patients) && empty($orders) && strlen($q) >= 2): ?>
    <div class="card" style="text-align:center;padding:60px 24px;background:linear-gradient(135deg, #fef2f2 0%, #ffffff 100%);border:2px dashed #fecaca;">
        <div style="font-size:4rem;margin-bottom:20px;opacity:0.5;">🔍</div>
        <h3 style="margin:0 0 12px;color:var(--text-primary);">لم يتم العثور على نتائج</h3>
        <p style="color:var(--text-muted);margin:0 0 24px;font-size:1.05rem;">
            لم يتم العثور على نتائج لـ <strong style="color:var(--primary);">«<?php echo htmlspecialchars($q, ENT_QUOTES, 'UTF-8'); ?>»</strong>
        </p>
        <div style="display:flex;gap:12px;justify-content:center;flex-wrap:wrap;">
            <a href="doctor.php?page=search" class="btn-primary" style="padding:10px 20px;text-decoration:none;">
                🔄 بحث جديد
            </a>
            <a href="doctor.php?page=patients" class="btn-secondary" style="padding:10px 20px;text-decoration:none;">
                👥 عرض جميع المرضى
            </a>
        </div>
        <div style="margin-top:32px;padding:20px;background:white;border-radius:10px;text-align:right;">
            <strong style="display:block;margin-bottom:12px;color:var(--text-primary);">💡 نصائح للبحث:</strong>
            <ul style="list-style:none;padding:0;margin:0;color:var(--text-muted);line-height:2;">
                <li>✓ تأكد من كتابة الاسم بشكل صحيح</li>
                <li>✓ جرب البحث برقم المريض أو رقم الطلب</li>
                <li>✓ استخدم جزء من الاسم فقط</li>
                <li>✓ جرب البحث بالهاتف</li>
            </ul>
        </div>
    </div>
    <?php endif; ?>
    <?php endif; ?>
</main>
<script>
(function(){
    var form = document.getElementById('doctorSearchForm');
    var inp = document.getElementById('doctorSearchInput');
    
    // حفظ البحث عند إرسال النموذج
    if (form) {
        form.addEventListener('submit', function() {
            if (inp && inp.value && inp.value.length >= 2) {
                var fd = new FormData();
                fd.append('action', 'save_search');
                fd.append('q', inp.value);
                fd.append('type', form.querySelector('input[name="type"]:checked')?.value || 'all');
                fetch('doctor_api.php', { method: 'POST', body: fd }).catch(function(){});
            }
        });
    }
    
    // بحث فوري أثناء الكتابة (debounced)
    if (inp) {
        var searchTimeout;
        inp.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            var query = this.value.trim();
            if (query.length >= 2) {
                searchTimeout = setTimeout(function() {
                    // يمكن إضافة بحث AJAX هنا لاحقاً
                }, 500);
            }
        });
        
        // التركيز التلقائي
        if (!inp.value) {
            setTimeout(function() { inp.focus(); }, 100);
        }
    }
    
    // اختصار Ctrl+K
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
            e.preventDefault();
            if (inp) {
                inp.focus();
                inp.select();
            }
        }
    });
})();
</script>
</body>
</html>
