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

$orderId = (int)($_GET['order_id'] ?? 0);
$patientId = (int)($_GET['patient_id'] ?? 0);

$order = null;
$orders = [];
$results = [];
$prevResults = [];
$patient = null;

if ($orderId > 0) {
    try {
        $stmt = $db->prepare("SELECT o.*, p.full_name AS patient_name, p.patient_code, p.date_of_birth, p.gender FROM lab_orders o JOIN patients p ON p.id = o.patient_id WHERE o.id = ? $tenantCond $doctorCond");
        $stmt->execute([$orderId]);
        $order = $stmt->fetch();
        if ($order) {
            $stmt = $db->prepare("SELECT t.id AS test_id, t.name AS test_name, r.result_value, r.unit, r.reference_range, r.flag, r.notes, r.result_date, r.validated_at
                                 FROM order_items oi
                                 JOIN tests t ON t.id = oi.test_id
                                 LEFT JOIN results r ON r.order_item_id = oi.id
                                 WHERE oi.order_id = ? ORDER BY t.name");
            $stmt->execute([$orderId]);
            $results = $stmt->fetchAll();
            $prevResults = [];
            if (!empty($results) && !empty($order['patient_id'])) {
                $testIds = array_unique(array_filter(array_column($results, 'test_id')));
                if (!empty($testIds)) {
                    $placeholders = implode(',', array_fill(0, count($testIds), '?'));
                    $stmt = $db->prepare("SELECT oi.test_id, r.result_value, o.order_date FROM results r JOIN order_items oi ON oi.id = r.order_item_id JOIN lab_orders o ON o.id = oi.order_id WHERE o.patient_id = ? AND o.id != ? AND o.order_date < ? AND oi.test_id IN ($placeholders) $tenantCond $doctorCond ORDER BY oi.test_id, o.order_date DESC");
                    $params = array_merge([$order['patient_id'], $orderId, $order['order_date']], $testIds);
                    $stmt->execute($params);
                    foreach ($stmt->fetchAll() as $pr) {
                        if (!isset($prevResults[$pr['test_id']])) $prevResults[$pr['test_id']] = $pr;
                    }
                }
            }
        }
    } catch (Throwable $e) {}
} elseif ($patientId > 0) {
    try {
        $tenantPatWhere = '';
        try {
            $db->query('SELECT tenant_id FROM patients LIMIT 1');
            $tenantPatWhere = ' AND p.tenant_id = ' . (int)$tenantId;
        } catch (Throwable $e) {}
        $sql = "SELECT p.* FROM patients p WHERE p.id = ?$tenantPatWhere LIMIT 1";
        $stmt = $db->prepare($sql);
        $stmt->execute([$patientId]);
        $patient = $stmt->fetch();
        if ($patient) {
            $stmt = $db->prepare("SELECT o.id, o.order_number, o.order_date, o.status FROM lab_orders o WHERE o.patient_id = ? $tenantCond $doctorCond ORDER BY o.order_date DESC LIMIT 50");
            $stmt->execute([$patientId]);
            $orders = $stmt->fetchAll();
        }
    } catch (Throwable $e) {}
}

$flagLabels = ['N' => 'طبيعي', 'L' => 'منخفض', 'H' => 'مرتفع', 'C' => 'حرج'];
$flagColors = ['N' => '#22c55e', 'L' => '#f59e0b', 'H' => '#ef4444', 'C' => '#dc2626'];

if ($orderId > 0 && isset($_GET['export']) && $_GET['export'] === 'excel' && !empty($order) && !empty($results)) {
    header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
    header('Content-Disposition: attachment; filename="results_' . preg_replace('/[^a-z0-9_-]/i', '_', $order['order_number']) . '_.xls"');
    echo "\xEF\xBB\xBF";
    echo "نتائج التحاليل - " . $order['order_number'] . "\n";
    echo "المريض," . $order['patient_name'] . "\n";
    echo "التاريخ," . date('Y-m-d H:i', strtotime($order['order_date'])) . "\n\n";
    echo "الفحص\tالنتيجة\tالوحدة\tالمدى المرجعي\tالحالة\tملاحظات\n";
    foreach ($results as $r) {
        $f = $r['flag'] ?? 'N';
        $fl = $flagLabels[$f] ?? $f;
        echo "\"" . str_replace('"', '""', $r['test_name']) . "\"\t\"" . ($r['result_value'] ?? '-') . "\"\t\"" . ($r['unit'] ?? '-') . "\"\t\"" . ($r['reference_range'] ?? '-') . "\"\t\"" . $fl . "\"\t\"" . str_replace('"', '""', $r['notes'] ?? '-') . "\"\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">
</head>
<body>
<?php
if ($orderId > 0 || $patientId > 0) {
    try {
        $db->query('SELECT id FROM doctor_activity_log LIMIT 1');
        $stmt = $db->prepare('INSERT INTO doctor_activity_log (doctor_account_id, action, entity_type, entity_id) VALUES (?, ?, ?, ?)');
        $stmt->execute([$doctorAuth->accountId(), $orderId > 0 ? 'view_results' : 'view_patient', $orderId > 0 ? 'order' : 'patient', $orderId > 0 ? $orderId : $patientId]);
    } catch (Throwable $e) {}
}
?>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content" id="doctorResultsMain">
    <div class="page-header doctor-results-header">
        <div class="doctor-results-breadcrumb">
            <a href="doctor.php?page=results">النتائج</a>
            <?php if (!empty($order)): ?><span>/</span><a href="doctor.php?page=results&patient_id=<?php echo (int)$order['patient_id']; ?>"><?php echo htmlspecialchars($order['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a><span>/</span><span>طلب <?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></span>
            <?php elseif (!empty($patient)): ?><span>/</span><span><?php echo htmlspecialchars($patient['full_name'], ENT_QUOTES, 'UTF-8'); ?></span>
            <?php else: ?><span>/</span><span>اختر طلباً أو مريضاً</span>
            <?php endif; ?>
        </div>
        <div class="doctor-results-actions-top">
            <a href="doctor.php?page=results" class="btn-secondary">← رجوع</a>
            <button type="button" onclick="DoctorFocusMode()" class="btn-secondary" title="وضع التركيز">🎯 تركيز</button>
        </div>
    </div>

    <?php if ($order && !empty($results)): ?>
    <div class="doctor-results-order-info card">
        <div class="doctor-order-meta">
            <div class="doctor-order-meta-item">
                <span class="doctor-order-label">رقم الطلب</span>
                <span class="doctor-order-value"><?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></span>
            </div>
            <div class="doctor-order-meta-item">
                <span class="doctor-order-label">المريض</span>
                <span class="doctor-order-value"><a href="doctor.php?page=results&patient_id=<?php echo (int)$order['patient_id']; ?>" data-patient-id="<?php echo (int)$order['patient_id']; ?>"><?php echo htmlspecialchars($order['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a></span>
                <div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:8px;">
                    <a href="doctor.php?page=results&patient_id=<?php echo (int)$order['patient_id']; ?>" class="btn-secondary btn-sm">عرض كل الطلبات</a>
                    <button type="button" class="btn-secondary btn-sm" onclick="window.DoctorQuickCopy && window.DoctorQuickCopy.copyPatientInfo(<?php echo (int)$order['patient_id']; ?>)" title="نسخ بيانات المريض">📋 نسخ</button>
                    <button type="button" class="btn-secondary btn-sm" onclick="window.DoctorQuickCopy && window.DoctorQuickCopy.copyResults(<?php echo (int)$orderId; ?>)" title="نسخ النتائج">📊 نسخ النتائج</button>
                </div>
            </div>
            <div class="doctor-order-meta-item">
                <span class="doctor-order-label">التاريخ</span>
                <span class="doctor-order-value"><?php echo date('Y-m-d H:i', strtotime($order['order_date'])); ?></span>
            </div>
            <div class="doctor-order-meta-item">
                <span class="doctor-order-label">الحالة</span>
                <?php $statusMap = ['new'=>'جديد','in_progress'=>'قيد التنفيذ','completed'=>'مكتمل','cancelled'=>'ملغي']; $statusClass = ['new'=>'status-new','in_progress'=>'status-progress','completed'=>'status-completed','cancelled'=>'status-cancelled']; $s = $order['status'] ?? 'new'; ?>
                <span class="doctor-order-badge <?php echo $statusClass[$s] ?? ''; ?>"><?php echo $statusMap[$s] ?? $s; ?></span>
            </div>
        </div>
    </div>

    <div class="doctor-results-actions card">
        <div class="doctor-actions-bar">
            <a href="doctor.php?page=print&order_id=<?php echo (int)$order['id']; ?>" target="_blank" class="btn-primary">🖨️ طباعة</a>
            <a href="modules/doctor/pdf_export.php?order_id=<?php echo (int)$order['id']; ?>" class="btn-secondary" target="_blank">📄 PDF</a>
            <a href="doctor.php?page=results&order_id=<?php echo (int)$order['id']; ?>&export=excel" class="btn-secondary">📊 Excel</a>
            <a href="doctor.php?page=results&action=share&order_id=<?php echo (int)$order['id']; ?>" class="btn-secondary">🔗 مشاركة</a>
            <a href="doctor.php?page=trend&patient_id=<?php echo (int)$order['patient_id']; ?>" class="btn-secondary">📈 مقارنة</a>
        </div>
        <?php if (isset($_SESSION['doctor_share_url'])): ?>
        <div class="doctor-share-box">
            <strong>رابط المشاركة (صالح 7 أيام):</strong>
            <div class="doctor-share-input-wrap">
                <input type="text" readonly value="<?php echo htmlspecialchars($_SESSION['doctor_share_url'], ENT_QUOTES, 'UTF-8'); ?>" id="shareUrlInput">
                <button type="button" onclick="navigator.clipboard.writeText(document.getElementById('shareUrlInput').value);this.textContent='✓ تم النسخ';setTimeout(()=>this.textContent='📋 نسخ',2000)" class="btn-primary">📋 نسخ</button>
            </div>
            <?php unset($_SESSION['doctor_share_url'], $_SESSION['doctor_share_msg']); ?>
        </div>
        <?php endif; ?>
        <?php
        $criticalCount = 0;
        foreach ($results as $r) { if (($r['flag'] ?? '') === 'C') $criticalCount++; }
        if ($criticalCount > 0): ?>
        <div class="doctor-critical-alert">
            <span class="doctor-critical-icon">⚠️</span>
            <span><strong>تنبيه:</strong> يوجد <?php echo $criticalCount; ?> نتيجة حرجة تتطلب مراجعة فورية.</span>
        </div>
        <?php endif; ?>
    </div>
    <div class="doctor-results-table-card card">
        <div class="doctor-results-table-header">
            <h3 class="doctor-card-title">النتائج (<?php echo count($results); ?> فحص)</h3>
            <label class="doctor-results-filter-toggle">
                <input type="checkbox" id="hideNormalResults" onchange="document.querySelectorAll('.result-row-normal').forEach(function(r){r.style.display=this.checked?'none':'table-row';}.bind(this));">
                <span>إخفاء الطبيعية</span>
            </label>
        </div>
        <div class="table-wrapper doctor-results-table-wrap">
            <table class="table doctor-results-table">
                <thead>
                    <tr>
                        <th>الفحص</th>
                        <th>النتيجة</th>
                        <th>الوحدة</th>
                        <th>المدى المرجعي</th>
                        <th>الحالة</th>
                        <th>ملاحظات</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($results as $r): $isAbnormal = in_array($r['flag'] ?? '', ['L','H','C']); $isCritical = ($r['flag'] ?? '') === 'C'; $prev = $prevResults[$r['test_id'] ?? 0] ?? null; ?>
                <tr class="<?php echo $isAbnormal ? 'result-row-abnormal' : 'result-row-normal'; ?> <?php echo $isCritical ? 'result-row-critical' : ''; ?>">
                    <td class="result-test-name"><strong><?php echo htmlspecialchars($r['test_name'], ENT_QUOTES, 'UTF-8'); ?></strong></td>
                    <td class="result-value">
                        <?php echo htmlspecialchars($r['result_value'] ?? '-', ENT_QUOTES, 'UTF-8'); ?>
                        <?php if ($prev && is_numeric($r['result_value'] ?? '') && is_numeric($prev['result_value'] ?? '')): $curr = (float)$r['result_value']; $pval = (float)$prev['result_value']; $diff = $curr - $pval; $arrow = $diff > 0 ? '↑' : ($diff < 0 ? '↓' : '→'); $arrowClass = $diff > 0 ? 'prev-up' : ($diff < 0 ? 'prev-down' : 'prev-same'); ?>
                        <span class="result-prev <?php echo $arrowClass; ?>" title="السابق: <?php echo htmlspecialchars($prev['result_value'], ENT_QUOTES, 'UTF-8'); ?> (<?php echo date('Y-m-d', strtotime($prev['order_date'])); ?>)"><?php echo $arrow; ?></span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo htmlspecialchars($r['unit'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td class="result-ref"><?php echo htmlspecialchars($r['reference_range'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td>
                        <?php $f = $r['flag'] ?? 'N'; $fc = $flagColors[$f] ?? '#999'; $fl = $flagLabels[$f] ?? $f; ?>
                        <span class="result-flag result-flag-<?php echo strtolower($f); ?>" style="background:<?php echo $fc; ?>;"><?php echo $fl; ?></span>
                    </td>
                    <td><?php echo htmlspecialchars($r['notes'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php elseif ($patient && isset($orders)): ?>
    <?php
    $medicalNotes = [];
    $allergyNotes = [];
    $diagnosisNotes = [];
    try {
        $db->query('SELECT id FROM patient_medical_notes LIMIT 1');
        $stmt = $db->prepare('SELECT n.* FROM patient_medical_notes n WHERE n.patient_id = ? ORDER BY n.created_at DESC LIMIT 50');
        $stmt->execute([$patientId]);
        $medicalNotes = $stmt->fetchAll();
        foreach ($medicalNotes as $mn) {
            if (($mn['note_type'] ?? '') === 'allergy') {
                $allergyNotes[] = $mn;
            } elseif (($mn['note_type'] ?? '') === 'diagnosis') {
                $diagnosisNotes[] = $mn;
            }
        }
    } catch (Throwable $e) {}
    $noteTypeLabels = ['general'=>'عامة','lab_review'=>'مراجعة تحاليل','diagnosis'=>'تشخيص','follow_up'=>'متابعة','allergy'=>'حساسية','medication'=>'أدوية'];
    
    if (isset($_GET['export_summary']) && $_GET['export_summary'] === '1') {
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="patient_' . $patient['patient_code'] . '_' . date('Y-m-d') . '.csv"');
        echo "\xEF\xBB\xBF";
        echo "ملخص المريض\n";
        echo "الاسم," . $patient['full_name'] . "\n";
        echo "الرقم," . $patient['patient_code'] . "\n";
        echo "الهاتف," . ($patient['phone'] ?? '-') . "\n";
        echo "تاريخ الميلاد," . ($patient['date_of_birth'] ? date('Y-m-d', strtotime($patient['date_of_birth'])) : '-') . "\n\n";
        echo "النتائج غير الطبيعية\n";
        echo "الفحص,النتيجة,الوحدة,الحالة,التاريخ\n";
        foreach ($patientSummary as $s) {
            echo '"' . str_replace('"', '""', $s['test_name']) . '","' . str_replace('"', '""', $s['result_value']) . '","' . ($s['unit'] ?? '') . '","' . (['L'=>'منخفض','H'=>'مرتفع','C'=>'حرج'][$s['flag'] ?? ''] ?? '') . '","' . date('Y-m-d', strtotime($s['order_date'])) . "\"\n";
        }
        echo "\nالملاحظات الطبية\n";
        foreach ($medicalNotes as $n) {
            echo date('Y-m-d', strtotime($n['created_at'])) . "," . str_replace('"', '""', $n['content']) . "\n";
        }
        exit;
    }
    ?>
    <?php
    $patientSummary = [];
    $abnormalCount = 0;
    try {
        $stmt = $db->prepare("SELECT t.name AS test_name, r.result_value, r.flag, r.unit, o.order_date
                             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 o.patient_id = ? AND r.flag IN ('L','H','C') $tenantCond $doctorCond
                             ORDER BY o.order_date DESC LIMIT 10");
        $stmt->execute([$patientId]);
        $patientSummary = $stmt->fetchAll();
        $abnormalCount = count($patientSummary);
    } catch (Throwable $e) {}
    ?>
    <?php
    $healthStatus = 'جيد';
    $healthColor = '#22c55e';
    $healthIcon = '✓';
    if (!empty($patientSummary)) {
        $hasCritical = false;
        foreach ($patientSummary as $s) { if (($s['flag'] ?? '') === 'C') { $hasCritical = true; break; } }
        if ($hasCritical) { $healthStatus = 'يحتاج مراجعة فورية'; $healthColor = '#dc2626'; $healthIcon = '⚠'; }
        else { $healthStatus = 'يحتاج متابعة'; $healthColor = '#f59e0b'; $healthIcon = '◐'; }
    }
    ?>
    <?php
    $aptStats = ['total' => 0, 'upcoming' => 0, 'past' => 0];
    $upcomingApts = [];
    try {
        $db->query('SELECT id FROM doctor_appointments LIMIT 1');
        $stmt = $db->prepare('SELECT * FROM doctor_appointments WHERE doctor_account_id = ? AND patient_id = ? ORDER BY appointment_date DESC, appointment_time DESC LIMIT 30');
        $stmt->execute([$doctorAuth->accountId(), $patientId]);
        $apts = $stmt->fetchAll();
        $todayA = date('Y-m-d');
        $nowA = date('H:i:s');
        foreach ($apts as $a) {
            $aptStats['total']++;
            $isFuture = ($a['appointment_date'] > $todayA) || ($a['appointment_date'] === $todayA && $a['appointment_time'] > $nowA);
            if ($isFuture && in_array($a['status'], ['scheduled','confirmed'], true)) {
                $aptStats['upcoming']++;
                if (count($upcomingApts) < 5) {
                    $upcomingApts[] = $a;
                }
            } else {
                $aptStats['past']++;
            }
        }
    } catch (Throwable $e) {}
    ?>
    <?php $totalOrders = isset($orders) && is_array($orders) ? count($orders) : 0; ?>
    <nav class="doctor-patient-tabs">
        <a href="#patient-summary" class="doctor-patient-tab doctor-patient-tab-active">ملخص</a>
        <a href="#patient-notes" class="doctor-patient-tab">الملاحظات</a>
        <a href="#patient-orders" class="doctor-patient-tab">الزيارات والنتائج</a>
        <a href="#patient-attachments" class="doctor-patient-tab">المرفقات</a>
    </nav>
    <?php
    $patientGenderLabel = ($patient['gender'] ?? '') === 'M' ? 'ذكر' : (($patient['gender'] ?? '') === 'F' ? 'أنثى' : 'غير محدد');
    $patientAgeYears = null;
    if (!empty($patient['date_of_birth'])) {
        try {
            $dobDate = date_create($patient['date_of_birth']);
            $nowDate = date_create('today');
            if ($dobDate && $nowDate) {
                $diff = date_diff($dobDate, $nowDate);
                $patientAgeYears = (int)$diff->y;
            }
        } catch (Throwable $e) {}
    }
    ?>
    <?php
    // جلب الحساب المالي للمريض
    $patientAccount = null;
    $accountBalance = 0;
    $pendingInvoices = 0;
    try {
        $db->query('SELECT id FROM patient_accounts LIMIT 1');
        $stmt = $db->prepare('SELECT pa.*, 
            (SELECT COUNT(*) FROM account_invoices ai WHERE ai.account_id = pa.id AND ai.status IN ("pending", "partial")) AS pending_count
            FROM patient_accounts pa 
            WHERE pa.patient_id = ? AND pa.tenant_id = ?');
        $stmt->execute([$patientId, $tenantId]);
        $patientAccount = $stmt->fetch();
        if ($patientAccount) {
            $accountBalance = (float)$patientAccount['account_balance'];
            $pendingInvoices = (int)($patientAccount['pending_count'] ?? 0);
        }
    } catch (Throwable $e) {}
    ?>
    <div id="patient-summary" class="doctor-patient-card card">
        <div class="doctor-patient-header">
            <div class="doctor-patient-info">
                <h3 class="doctor-patient-name"><?php echo htmlspecialchars($patient['full_name'], ENT_QUOTES, 'UTF-8'); ?></h3>
                <div class="doctor-patient-meta">
                    <span>الرقم: <?php echo htmlspecialchars($patient['patient_code'], ENT_QUOTES, 'UTF-8'); ?></span>
                    <span>الجنس: <?php echo $patientGenderLabel; ?></span>
                    <span>العمر: <?php echo $patientAgeYears !== null ? $patientAgeYears . ' سنة' : 'غير معروف'; ?></span>
                    <?php if (!empty($patient['date_of_birth'])): ?>
                    <span>ت. الميلاد: <?php echo htmlspecialchars(date('Y-m-d', strtotime($patient['date_of_birth'])), ENT_QUOTES, 'UTF-8'); ?></span>
                    <?php endif; ?>
                    <span>الهاتف: <?php if (!empty($patient['phone'])): ?><a href="tel:<?php echo htmlspecialchars(preg_replace('/[^0-9+]/', '', $patient['phone']), ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($patient['phone'], ENT_QUOTES, 'UTF-8'); ?></a><?php else: ?>-<?php endif; ?></span>
                    <?php if (!empty($patient['address'])): ?>
                    <span>العنوان: <?php echo htmlspecialchars($patient['address'], ENT_QUOTES, 'UTF-8'); ?></span>
                    <?php endif; ?>
                    <?php if ($patientAccount): ?>
                    <span style="padding:4px 12px;background:<?php echo $accountBalance >= 0 ? '#22c55e' : '#dc2626'; ?>20;color:<?php echo $accountBalance >= 0 ? '#22c55e' : '#dc2626'; ?>;border-radius:12px;font-weight:600;">
                        💰 الرصيد: <?php echo number_format($accountBalance, 2); ?> د.ع
                        <?php if ($pendingInvoices > 0): ?>
                        <span style="margin-right:8px;color:#f59e0b;">(<?php echo $pendingInvoices; ?> فاتورة معلقة)</span>
                        <?php endif; ?>
                    </span>
                    <?php endif; ?>
                    <button type="button" class="btn-secondary btn-sm" onclick="window.DoctorQuickCopy && window.DoctorQuickCopy.copyPatientInfo(<?php echo (int)$patientId; ?>)" title="نسخ بيانات المريض">📋 نسخ البيانات</button>
                    <button type="button" class="btn-secondary btn-sm" onclick="window.DoctorQuickCopy && window.DoctorQuickCopy.copy(location.href, 'الرابط')" title="نسخ رابط الصفحة">🔗 نسخ الرابط</button>
                    <?php if ($patientAccount): ?>
                    <a href="doctor.php?page=accounts&patient_id=<?php echo (int)$patientId; ?>" class="btn-primary btn-sm" title="عرض الحساب المالي">💰 الحساب المالي</a>
                    <?php endif; ?>
                </div>
            </div>
            <div class="doctor-health-badge" style="background:<?php echo $healthColor; ?>22;border:1px solid <?php echo $healthColor; ?>;color:<?php echo $healthColor; ?>">
                <span class="doctor-health-icon"><?php echo $healthIcon; ?></span>
                <span class="doctor-health-text"><?php echo $healthStatus; ?></span>
            </div>
        </div>
        <div class="doctor-patient-actions">
            <a href="doctor.php?page=trend&patient_id=<?php echo (int)$patientId; ?>" class="btn-secondary">📈 مقارنة النتائج</a>
            <a href="#reminder" class="btn-secondary">⏰ تذكير متابعة</a>
            <a href="doctor.php?page=results&patient_id=<?php echo (int)$patientId; ?>&export_summary=1" class="btn-secondary">📥 تصدير ملخص</a>
            <?php if ($aptStats['total'] > 0): ?>
            <span class="doctor-shortcut-hint">زيارات: <?php echo $aptStats['total']; ?> · القادمة: <?php echo $aptStats['upcoming']; ?></span>
            <?php endif; ?>
        </div>
        <div class="doctor-patient-stats">
            <div class="doctor-patient-stat-card">
                <span class="doctor-patient-stat-label">إجمالي الطلبات</span>
                <span class="doctor-patient-stat-value"><?php echo $totalOrders; ?></span>
            </div>
            <div class="doctor-patient-stat-card">
                <span class="doctor-patient-stat-label">نتائج غير طبيعية</span>
                <span class="doctor-patient-stat-value"><?php echo $abnormalCount; ?></span>
            </div>
            <div class="doctor-patient-stat-card">
                <span class="doctor-patient-stat-label">كل المواعيد</span>
                <span class="doctor-patient-stat-value"><?php echo $aptStats['total']; ?></span>
            </div>
            <div class="doctor-patient-stat-card">
                <span class="doctor-patient-stat-label">مواعيد قادمة</span>
                <span class="doctor-patient-stat-value"><?php echo $aptStats['upcoming']; ?></span>
            </div>
        </div>
        <?php if (!empty($allergyNotes)): ?>
        <div class="doctor-alert doctor-alert-critical" style="margin-top:12px;">
            <span class="doctor-alert-icon">⚠️</span>
            <div class="doctor-alert-content">
                <strong>تنبيهات حساسية:</strong>
                <div class="doctor-allergy-badges">
                    <?php foreach (array_slice($allergyNotes, 0, 6) as $an):
                        $label = trim($an['content'] ?? '');
                        $label = preg_replace('/^حساسية\\s+من\\s+/u', '', $label);
                    ?>
                    <span class="doctor-allergy-badge"><?php echo htmlspecialchars($label, ENT_QUOTES, 'UTF-8'); ?></span>
                    <?php endforeach; ?>
                </div>
                <button type="button" class="btn-secondary btn-sm doctor-allergy-add-btn" id="doctorAddAllergyBtn">+ إضافة حساسية دواء</button>
            </div>
        </div>
        <?php endif; ?>
        <?php if (!empty($diagnosisNotes)): ?>
        <div class="doctor-reminder-card doctor-reminder-upcoming" style="margin-top:12px;">
            <div class="doctor-reminder-card-header">
                <strong>ملخص الأمراض المزمنة / التشخيصات</strong>
            </div>
            <div>
                <ul style="margin:0;padding-right:18px;font-size:0.9rem;">
                    <?php foreach (array_slice($diagnosisNotes, 0, 3) as $dn): ?>
                    <li><?php echo htmlspecialchars($dn['content'], ENT_QUOTES, 'UTF-8'); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
        <?php endif; ?>
        <div id="reminder" class="card" style="margin-top:16px;padding:16px;background:var(--bg-secondary);">
            <h4 style="margin-top:0;">⏰ تذكير متابعة</h4>
            <form method="post" action="doctor.php?page=reminders&action=add" id="reminderForm" style="display:flex;gap:12px;flex-wrap:wrap;align-items:end;">
                <input type="hidden" name="patient_id" value="<?php echo (int)$patientId; ?>">
                <input type="hidden" name="redirect" value="results">
                <div><label>التاريخ</label><input type="date" name="reminder_date" id="reminderDate" required value="<?php echo date('Y-m-d', strtotime('+2 weeks')); ?>"></div>
                <div style="flex:1;min-width:150px;"><label>ملاحظة</label><input type="text" name="note" id="reminderNote" placeholder="متابعة، إعادة فحص..."></div>
                <button type="submit" class="btn-primary">إضافة</button>
                <button type="button" class="btn-secondary" id="smartReminderBtn" title="اقتراح تذكير بناءً على النتائج غير الطبيعية">💡 اقتراح ذكي</button>
            </form>
            <script>
            (function(){
                var btn = document.getElementById('smartReminderBtn');
                if (btn) btn.onclick = function(){
                    btn.disabled = true; btn.textContent = 'جاري...';
                    fetch('doctor_api.php?action=smart_reminder_suggest&patient_id=<?php echo (int)$patientId; ?>')
                        .then(function(r){return r.json();})
                        .then(function(d){
                            if (d.suggestions && d.suggestions[0]) {
                                var s = d.suggestions[0];
                                document.getElementById('reminderDate').value = s.date;
                                document.getElementById('reminderNote').value = s.note || '';
                            }
                            btn.disabled = false; btn.textContent = '💡 اقتراح ذكي';
                        })
                        .catch(function(){ btn.disabled = false; btn.textContent = '💡 اقتراح ذكي'; });
                };
            })();
            </script>
        </div>
        <?php if (!empty($patientSummary)): ?>
        <div class="doctor-abnormal-summary">
            <strong>ملخص النتائج غير الطبيعية:</strong>
            <ul class="doctor-abnormal-list">
                <?php foreach ($patientSummary as $s): ?>
                <li>
                    <span class="doctor-abnormal-test"><?php echo htmlspecialchars($s['test_name'], ENT_QUOTES, 'UTF-8'); ?>:</span>
                    <span class="doctor-abnormal-value"><?php echo htmlspecialchars($s['result_value'], ENT_QUOTES, 'UTF-8'); ?> <?php echo htmlspecialchars($s['unit'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span>
                    <span class="doctor-abnormal-flag <?php echo ($s['flag'] ?? '') === 'C' ? 'flag-critical' : 'flag-warning'; ?>"><?php echo (['L'=>'منخفض','H'=>'مرتفع','C'=>'حرج'][$s['flag'] ?? ''] ?? ''); ?></span>
                    <span class="doctor-abnormal-date"><?php echo date('Y-m-d', strtotime($s['order_date'])); ?></span>
                </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
    </div>

    <div id="patient-notes" class="doctor-notes-card card">
        <h3 class="doctor-card-title">📝 الملاحظات الطبية</h3>
        <?php if (isset($_SESSION['doctor_note_msg'])): ?><div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['doctor_note_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_note_msg']); ?></div><?php endif; ?>
        <?php if (isset($_SESSION['doctor_note_error'])): ?><div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['doctor_note_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_note_error']); ?></div><?php endif; ?>
        <div class="doctor-note-filters">
            <button type="button" class="doctor-note-filter-chip doctor-note-filter-active" data-filter="all">الكل</button>
            <?php foreach ($noteTypeLabels as $k=>$v): ?>
            <button type="button" class="doctor-note-filter-chip" data-filter="<?php echo $k; ?>"><?php echo $v; ?></button>
            <?php endforeach; ?>
        </div>
        <?php
        $noteTemplates = [
            'lab_review' => ['مراجعة تحاليل طبيعية', 'مراجعة تحاليل - بعض النتائج تحتاج متابعة', 'مراجعة تحاليل - نتائج حرجة'],
            'diagnosis' => ['سكري - تحت السيطرة', 'ضغط دم - يحتاج تعديل علاج', 'فقر دم - يحتاج مكملات', 'كوليسترول مرتفع'],
            'follow_up' => ['متابعة بعد أسبوعين', 'متابعة بعد شهر', 'مراجعة عند الحاجة'],
            'allergy' => ['حساسية من البنسلين', 'حساسية من أدوية معينة'],
            'medication' => ['يحتاج تعديل الجرعة', 'الاستمرار على العلاج الحالي'],
        ];
        ?>
        <form method="post" action="doctor.php?page=results&action=add_note" class="doctor-note-form">
            <input type="hidden" name="patient_id" value="<?php echo (int)$patientId; ?>">
            <div class="doctor-note-form-grid">
                <div>
                    <label>نوع الملاحظة</label>
                    <select name="note_type" id="noteTypeSelect">
                        <?php foreach ($noteTypeLabels as $k=>$v): ?><option value="<?php echo $k; ?>"><?php echo $v; ?></option><?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>الملاحظة</label>
                    <textarea name="content" id="noteContent" required placeholder="أدخل الملاحظة..." rows="2" style="width:100%;resize:vertical;"></textarea>
                    <div style="margin-top:6px;">
                        <small style="color:var(--text-muted);">قوالب سريعة:</small>
                        <?php foreach ($noteTemplates as $type => $tpls): ?>
                        <?php foreach ($tpls as $t): ?>
                        <button type="button" onclick="document.getElementById('noteContent').value='<?php echo addslashes(htmlspecialchars($t, ENT_QUOTES, 'UTF-8')); ?>';document.getElementById('noteTypeSelect').value='<?php echo $type; ?>'" style="margin:2px;padding:4px 8px;font-size:0.8rem;background:var(--bg-secondary);border:1px solid var(--border);border-radius:4px;cursor:pointer;"><?php echo htmlspecialchars($t, ENT_QUOTES, 'UTF-8'); ?></button>
                        <?php endforeach; ?>
                        <?php endforeach; ?>
                    </div>
                </div>
                <button type="submit" class="btn-primary">حفظ</button>
            </div>
        </form>
        <?php if (!empty($medicalNotes)): ?>
        <div style="border-top:1px solid var(--border);padding-top:12px;">
            <?php foreach ($medicalNotes as $n): ?>
            <div class="doctor-note-item" data-type="<?php echo htmlspecialchars($n['note_type'], ENT_QUOTES, 'UTF-8'); ?>">
                <div class="doctor-note-header-row">
                    <span class="doctor-note-meta"><?php echo $noteTypeLabels[$n['note_type']] ?? $n['note_type']; ?> · <?php echo date('Y-m-d H:i', strtotime($n['created_at'])); ?></span>
                    <div class="doctor-note-actions">
                        <button type="button"
                                class="btn-secondary btn-sm doctor-note-edit-btn"
                                data-id="<?php echo (int)$n['id']; ?>"
                                data-type="<?php echo htmlspecialchars($n['note_type'], ENT_QUOTES, 'UTF-8'); ?>"
                                data-content="<?php echo htmlspecialchars($n['content'], ENT_QUOTES, 'UTF-8'); ?>">
                            تعديل
                        </button>
                        <a href="doctor.php?page=results&action=delete_note&id=<?php echo (int)$n['id']; ?>&patient_id=<?php echo (int)$patientId; ?>"
                           class="doctor-note-delete"
                           onclick="return confirm('حذف هذه الملاحظة؟');">
                            حذف
                        </a>
                    </div>
                </div>
                <p class="doctor-note-content" id="doctor-note-view-<?php echo (int)$n['id']; ?>"><?php echo nl2br(htmlspecialchars($n['content'], ENT_QUOTES, 'UTF-8')); ?></p>
                <form method="post"
                      action="doctor.php?page=results&action=edit_note"
                      class="doctor-note-edit-form"
                      id="doctor-note-form-<?php echo (int)$n['id']; ?>">
                    <input type="hidden" name="note_id" value="<?php echo (int)$n['id']; ?>">
                    <input type="hidden" name="patient_id" value="<?php echo (int)$patientId; ?>">
                    <div class="doctor-note-edit-grid">
                        <div>
                            <label>النوع</label>
                            <select name="note_type">
                                <?php foreach ($noteTypeLabels as $k=>$v): ?>
                                <option value="<?php echo $k; ?>" <?php echo $k === $n['note_type'] ? 'selected' : ''; ?>><?php echo $v; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="doctor-note-edit-content">
                            <label>الملاحظة</label>
                            <textarea name="content" rows="2"><?php echo htmlspecialchars($n['content'], ENT_QUOTES, 'UTF-8'); ?></textarea>
                        </div>
                        <div class="doctor-note-edit-actions">
                            <button type="submit" class="btn-primary btn-sm">حفظ</button>
                            <button type="button" class="btn-secondary btn-sm doctor-note-cancel-btn" data-id="<?php echo (int)$n['id']; ?>">إلغاء</button>
                        </div>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <p style="color:var(--text-muted);font-size:0.9rem;">لا توجد ملاحظات مسجلة.</p>
        <?php endif; ?>
    </div>

    <script>
    (function(){
        var editButtons = document.querySelectorAll('.doctor-note-edit-btn');
        editButtons.forEach(function(btn){
            btn.addEventListener('click', function(){
                var id = this.getAttribute('data-id');
                var form = document.getElementById('doctor-note-form-' + id);
                var view = document.getElementById('doctor-note-view-' + id);
                if (!form || !view) return;
                form.style.display = 'block';
                view.style.display = 'none';
            });
        });
        var cancelButtons = document.querySelectorAll('.doctor-note-cancel-btn');
        cancelButtons.forEach(function(btn){
            btn.addEventListener('click', function(){
                var id = this.getAttribute('data-id');
                var form = document.getElementById('doctor-note-form-' + id);
                var view = document.getElementById('doctor-note-view-' + id);
                if (!form || !view) return;
                form.style.display = 'none';
                view.style.display = 'block';
            });
        });
        var filterChips = document.querySelectorAll('.doctor-note-filter-chip');
        var noteItems = document.querySelectorAll('.doctor-note-item');
        filterChips.forEach(function(chip){
            chip.addEventListener('click', function(){
                var type = this.getAttribute('data-filter');
                filterChips.forEach(function(c){ c.classList.remove('doctor-note-filter-active'); });
                this.classList.add('doctor-note-filter-active');
                noteItems.forEach(function(item){
                    var t = item.getAttribute('data-type');
                    if (type === 'all' || type === t) {
                        item.style.display = '';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });
        });
        var tabs = document.querySelectorAll('.doctor-patient-tab');
        tabs.forEach(function(tab){
            tab.addEventListener('click', function(){
                tabs.forEach(function(t){ t.classList.remove('doctor-patient-tab-active'); });
                this.classList.add('doctor-patient-tab-active');
            });
        });
        var addAllergyBtn = document.getElementById('doctorAddAllergyBtn');
        if (addAllergyBtn) {
            addAllergyBtn.addEventListener('click', function(){
                var notesTab = document.querySelector('.doctor-patient-tab[href="#patient-notes"]');
                if (notesTab) notesTab.click();
                location.hash = '#patient-notes';
                var typeSelect = document.getElementById('noteTypeSelect');
                if (typeSelect) typeSelect.value = 'allergy';
                var noteArea = document.getElementById('noteContent');
                if (noteArea) noteArea.focus();
            });
        }
    })();
    </script>

    <div id="patient-orders" class="doctor-patient-orders card">
        <h3 class="doctor-card-title">طلبات التحاليل <span class="doctor-orders-count"><?php echo count($orders); ?></span></h3>
        <?php if (empty($orders)): ?>
        <p class="doctor-empty-message">لا توجد طلبات</p>
        <?php else: ?>
        <div class="doctor-orders-timeline">
            <?php foreach ($orders as $o): $statusAr = ['new'=>'جديد','in_progress'=>'قيد التنفيذ','completed'=>'مكتمل','cancelled'=>'ملغي']; $statusCl = ['new'=>'status-new','in_progress'=>'status-progress','completed'=>'status-completed','cancelled'=>'status-cancelled']; $st = $o['status'] ?? 'new'; ?>
            <div class="doctor-order-timeline-item">
                <div class="doctor-order-timeline-dot"></div>
                <div class="doctor-order-timeline-content">
                    <div class="doctor-order-timeline-header">
                        <span class="doctor-order-num"><?php echo htmlspecialchars($o['order_number'], ENT_QUOTES, 'UTF-8'); ?></span>
                        <span class="doctor-order-date"><?php echo date('Y-m-d', strtotime($o['order_date'])); ?></span>
                        <span class="doctor-order-badge <?php echo $statusCl[$st] ?? ''; ?>"><?php echo $statusAr[$st] ?? $st; ?></span>
                    </div>
                    <div class="doctor-order-timeline-actions">
                        <a href="doctor.php?page=results&order_id=<?php echo (int)$o['id']; ?>" class="btn-secondary btn-sm">عرض النتائج</a>
                        <?php if ($o['status'] === 'completed'): ?>
                        <a href="doctor.php?page=print&order_id=<?php echo (int)$o['id']; ?>" target="_blank" class="btn-secondary btn-sm" title="طباعة">🖨️</a>
                        <a href="doctor.php?page=print&order_id=<?php echo (int)$o['id']; ?>&pdf=1" target="_blank" class="btn-secondary btn-sm" title="PDF">📥</a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <?php
    $attachments = [];
    try {
        $db->query('SELECT id FROM patient_attachments LIMIT 1');
        $stmt = $db->prepare('SELECT id, file_name, file_path, created_at FROM patient_attachments WHERE patient_id = ? ORDER BY id DESC LIMIT 20');
        $stmt->execute([$patientId]);
        $attachments = $stmt->fetchAll();
    } catch (Throwable $e) {}
    ?>
    <?php if (!empty($attachments)): ?>
    <div id="patient-attachments" class="card">
        <h3 class="doctor-card-title">📎 مرفقات وتقارير</h3>
        <ul class="attachments-list">
            <?php foreach ($attachments as $a): ?>
            <li>
                <a href="<?php echo htmlspecialchars($a['file_path'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" target="_blank" class="attachment-link">📄 <?php echo htmlspecialchars($a['file_name'], ENT_QUOTES, 'UTF-8'); ?></a>
                <span class="attachment-date"><?php echo htmlspecialchars($a['created_at'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span>
            </li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>

    <?php else: ?>
    <?php
    $filterStatus = $_GET['status'] ?? '';
    $filterFrom = trim($_GET['from'] ?? '');
    $filterTo = trim($_GET['to'] ?? '');
    $filterCritical = isset($_GET['critical']) && $_GET['critical'] === '1';
    $filterTestId = (int)($_GET['test_id'] ?? 0);
    $sqlFilter = '';
    $sqlParams = [];
    if ($filterStatus !== '') {
        $sqlFilter .= ' AND o.status = ?';
        $sqlParams[] = $filterStatus;
    }
    if ($filterFrom !== '') {
        $sqlFilter .= ' AND o.order_date >= ?';
        $sqlParams[] = $filterFrom . ' 00:00:00';
    }
    if ($filterTo !== '') {
        $sqlFilter .= ' AND o.order_date <= ?';
        $sqlParams[] = $filterTo . ' 23:59:59';
    }
    if ($filterCritical) {
        $sqlFilter .= ' AND EXISTS (SELECT 1 FROM order_items oi2 JOIN results r2 ON r2.order_item_id = oi2.id WHERE oi2.order_id = o.id AND r2.flag = "C")';
    }
    if ($filterTestId > 0) {
        $sqlFilter .= ' AND EXISTS (SELECT 1 FROM order_items oi2 WHERE oi2.order_id = o.id AND oi2.test_id = ?)';
        $sqlParams[] = $filterTestId;
    }
    $testsForFilter = [];
    try {
        $stmt = $db->prepare("SELECT DISTINCT t.id, t.name FROM tests t JOIN order_items oi ON oi.test_id = t.id JOIN lab_orders o ON o.id = oi.order_id WHERE 1=1 $tenantCond $doctorCond ORDER BY t.name");
        $stmt->execute();
        $testsForFilter = $stmt->fetchAll();
    } catch (Throwable $e) {}
    $recentForSelect = [];
    try {
        $stmt = $db->prepare("SELECT o.id, o.order_number, o.order_date, o.status, o.patient_id, p.full_name AS patient_name FROM lab_orders o JOIN patients p ON p.id = o.patient_id WHERE 1=1 $tenantCond $doctorCond $sqlFilter ORDER BY o.order_date DESC LIMIT 50");
        $stmt->execute($sqlParams);
        $recentForSelect = $stmt->fetchAll();
    } catch (Throwable $e) {}

    if (isset($_GET['export']) && $_GET['export'] === 'csv' && !empty($recentForSelect)) {
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="orders_' . date('Y-m-d') . '.csv"');
        echo "\xEF\xBB\xBF";
        echo "رقم الطلب,المريض,التاريخ,الحالة\n";
        foreach ($recentForSelect as $o) {
            echo '"' . str_replace('"', '""', $o['order_number']) . '","' . str_replace('"', '""', $o['patient_name']) . '","' . date('Y-m-d H:i', strtotime($o['order_date'])) . '","' . $o['status'] . "\"\n";
        }
        exit;
    }
    ?>
    <div class="doctor-results-filter-card card">
        <h3 class="doctor-card-title">البحث عن الطلبات</h3>
        <form method="get" class="doctor-results-filter-form">
            <input type="hidden" name="page" value="results">
            <div style="display:flex;gap:4px;flex-wrap:wrap;">
                <a href="doctor.php?page=results&from=<?php echo date('Y-m-d'); ?>&to=<?php echo date('Y-m-d'); ?><?php echo $filterStatus ? '&status=' . urlencode($filterStatus) : ''; ?><?php echo $filterTestId ? '&test_id=' . $filterTestId : ''; ?><?php echo $filterCritical ? '&critical=1' : ''; ?>" class="btn-secondary" style="padding:6px 10px;font-size:0.85rem;<?php echo $filterFrom === date('Y-m-d') && $filterTo === date('Y-m-d') ? 'background:#0d9488;color:white;border-color:#0d9488;' : ''; ?>">اليوم</a>
                <a href="doctor.php?page=results&from=<?php echo date('Y-m-d', strtotime('-1 day')); ?>&to=<?php echo date('Y-m-d', strtotime('-1 day')); ?><?php echo $filterStatus ? '&status=' . urlencode($filterStatus) : ''; ?><?php echo $filterTestId ? '&test_id=' . $filterTestId : ''; ?><?php echo $filterCritical ? '&critical=1' : ''; ?>" class="btn-secondary" style="padding:6px 10px;font-size:0.85rem;">أمس</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'); ?><?php echo $filterStatus ? '&status=' . urlencode($filterStatus) : ''; ?><?php echo $filterTestId ? '&test_id=' . $filterTestId : ''; ?><?php echo $filterCritical ? '&critical=1' : ''; ?>" class="btn-secondary" style="padding:6px 10px;font-size:0.85rem;">هذا الأسبوع</a>
                <a href="doctor.php?page=results&from=<?php echo date('Y-m-01'); ?>&to=<?php echo date('Y-m-d'); ?><?php echo $filterStatus ? '&status=' . urlencode($filterStatus) : ''; ?><?php echo $filterTestId ? '&test_id=' . $filterTestId : ''; ?><?php echo $filterCritical ? '&critical=1' : ''; ?>" class="btn-secondary" style="padding:6px 10px;font-size:0.85rem;">هذا الشهر</a>
            </div>
            <select name="status" style="min-width:120px;">
                <option value="">كل الحالات</option>
                <option value="completed" <?php echo $filterStatus === 'completed' ? 'selected' : ''; ?>>مكتمل</option>
                <option value="in_progress" <?php echo $filterStatus === 'in_progress' ? 'selected' : ''; ?>>قيد التنفيذ</option>
                <option value="new" <?php echo $filterStatus === 'new' ? 'selected' : ''; ?>>جديد</option>
            </select>
            <select name="test_id" style="min-width:180px;">
                <option value="">كل الفحوصات</option>
                <?php foreach ($testsForFilter as $tf): ?>
                <option value="<?php echo (int)$tf['id']; ?>" <?php echo $filterTestId === (int)$tf['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($tf['name'], ENT_QUOTES, 'UTF-8'); ?></option>
                <?php endforeach; ?>
            </select>
            <input type="date" name="from" value="<?php echo htmlspecialchars($filterFrom, ENT_QUOTES, 'UTF-8'); ?>" placeholder="من">
            <input type="date" name="to" value="<?php echo htmlspecialchars($filterTo, ENT_QUOTES, 'UTF-8'); ?>" placeholder="إلى">
            <label><input type="checkbox" name="critical" value="1" <?php echo $filterCritical ? 'checked' : ''; ?>> نتائج حرجة فقط</label>
            <button type="submit">تطبيق</button>
            <?php if ($filterStatus || $filterFrom || $filterTo || $filterCritical || $filterTestId): ?>
            <a href="doctor.php?page=results" class="btn-secondary">إلغاء</a>
            <?php endif; ?>
            <a href="doctor.php?page=results&export=csv<?php echo $filterStatus ? '&status=' . urlencode($filterStatus) : ''; echo $filterTestId ? '&test_id=' . $filterTestId : ''; echo $filterFrom ? '&from=' . urlencode($filterFrom) : ''; echo $filterTo ? '&to=' . urlencode($filterTo) : ''; echo $filterCritical ? '&critical=1' : ''; ?>" class="btn-secondary">📥 تصدير CSV</a>
        </form>
    </div>
    <div class="card">
        <h3 style="margin-top:0;">اختر طلباً لعرض النتائج</h3>
        <p style="color:var(--text-muted);margin-bottom:16px;">أو <a href="doctor.php?page=patients">اختر مريضاً</a> لعرض جميع طلباته وملاحظاته.</p>
        <?php if (!empty($recentForSelect)): ?>
        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>رقم الطلب</th>
                        <th>المريض</th>
                        <th>التاريخ</th>
                        <th>الحالة</th>
                        <th>إجراء</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($recentForSelect 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'] ?? 0); ?>" <?php if (!empty($o['patient_id'])): ?>data-patient-id="<?php echo (int)$o['patient_id']; ?>"<?php endif; ?>><?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><span class="badge badge-<?php echo $o['status'] === 'completed' ? 'completed' : 'warning'; ?>"><?php echo $o['status'] === 'completed' ? 'مكتمل' : 'قيد التنفيذ'; ?></span></td>
                    <td>
                        <a href="doctor.php?page=results&order_id=<?php echo (int)$o['id']; ?>">عرض</a>
                        <?php if ($o['status'] === 'completed'): ?>
                        <a href="doctor.php?page=print&order_id=<?php echo (int)$o['id']; ?>" target="_blank" class="btn-secondary" style="padding:4px 8px;font-size:12px;margin-right:4px;">🖨️</a>
                        <a href="doctor.php?page=print&order_id=<?php echo (int)$o['id']; ?>&pdf=1" target="_blank" class="btn-secondary" style="padding:4px 8px;font-size:12px;">📥</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <p style="text-align:center;color:var(--text-muted);padding:40px;">لا توجد طلبات حديثة.</p>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</main>
</body>
</html>
