<?php
/**
 * عرض نتائج التحاليل - حسب الطلب أو المريض
 */
require_once __DIR__ . '/_result_helpers.php';
$tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
$doctorIdScoped = isset($doctorId) ? (int)$doctorId : 0;
/* طبيب غير مربوط (0): لا تعرض طلبات المختبر كلها */
$doctorCond = $doctorIdScoped > 0 ? ' AND o.doctor_id = ' . $doctorIdScoped : ' AND 1=0';

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

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

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();
            try {
                $testTenantAnd = '';
                $params = [];
                try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $testTenantAnd = ' WHERE tenant_id = ?'; $params[] = $tenantId; } catch (Throwable $e) {}
                $sqlTests = 'SELECT id, name, test_code, default_price FROM tests' . $testTenantAnd . ' ORDER BY name ASC LIMIT 500';
                $stmt = $params ? $db->prepare($sqlTests) : $db->query($sqlTests);
                if ($params) $stmt->execute($params);
                $doctorOrderTests = $stmt->fetchAll();
            } catch (Throwable $e) {
                $doctorOrderTests = [];
            }
        }
    } catch (Throwable $e) {}
}

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

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) {
        if (doctor_order_result_is_pending($r)) {
            $f = 'P';
            $fl = $flagLabels['P'];
        } else {
            $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">
    <?php if (isset($_SESSION['doctor_msg'])): ?>
    <div class="alert alert-success" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['doctor_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_msg']); ?></div>
    <?php endif; ?>
    <?php if (isset($_SESSION['doctor_error'])): ?>
    <div class="alert alert-danger" style="margin-bottom:16px;"><?php echo htmlspecialchars($_SESSION['doctor_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_error']); ?></div>
    <?php endif; ?>

    <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 (empty($order) && empty($patient)): ?>
    <?php
    $doctorPageTitle = '📋 نتائج التحاليل';
    $doctorPageDesc = 'صفِّ الطلبات بالتاريخ والحالة والفحص، أو اعرض النتائج الحرجة فقط، ثم افتح الطلب للطباعة أو المشاركة.';
    $doctorPageLinks = [
        ['href' => 'doctor.php?page=patients', 'label' => '👥 المرضى'],
        ['href' => 'doctor.php?page=search', 'label' => '🔍 بحث'],
        ['href' => 'doctor.php?page=trend', 'label' => '📈 مقارنة'],
    ];
    include __DIR__ . '/_page_intro.php';
    ?>
    <?php endif; ?>

    <?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>
    <?php
    $pendingResultsCount = 0;
    foreach ($results as $pr) {
        if (doctor_order_result_is_pending($pr)) {
            $pendingResultsCount++;
        }
    }
    if ($pendingResultsCount > 0): ?>
    <div class="alert alert-info" style="margin-bottom:16px;border-color:#94a3b8;background:#f1f5f9;color:#334155;">
        <strong>بانتظار المختبر:</strong> <?php echo (int)$pendingResultsCount; ?> فحص/فحوص لم تُسجَّل نتائجها بعد. تظهر «طبيعي / مرتفع / منخفض» فقط بعد إدخال القيم من نظام المختبر.
    </div>
    <?php endif; ?>

    <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>
            <form method="post" action="doctor.php?page=results" style="display:inline;">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="action" value="share">
                <input type="hidden" name="order_id" value="<?php echo (int)$order['id']; ?>">
                <button type="submit" class="btn-secondary">🔗 مشاركة</button>
            </form>
            <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 (!doctor_order_result_is_pending($r) && ($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):
                    $isPending = doctor_order_result_is_pending($r);
                    $isAbnormal = !$isPending && in_array($r['flag'] ?? '', ['L','H','C'], true);
                    $isCritical = !$isPending && ($r['flag'] ?? '') === 'C';
                    $prev = $prevResults[$r['test_id'] ?? 0] ?? null;
                    $rowClass = $isPending ? 'result-row-pending' : ($isAbnormal ? 'result-row-abnormal' : 'result-row-normal');
                ?>
                <tr class="<?php echo $rowClass; ?> <?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 $isPending ? '—' : htmlspecialchars((string)($r['result_value'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?>
                        <?php if (!$isPending && $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 $isPending ? '—' : htmlspecialchars($r['unit'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td class="result-ref"><?php echo $isPending ? '—' : htmlspecialchars($r['reference_range'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td>
                        <?php
                        if ($isPending) {
                            $f = 'P';
                        } else {
                            $f = $r['flag'] ?? 'N';
                        }
                        $fc = $flagColors[$f] ?? '#999';
                        $fl = $flagLabels[$f] ?? $f;
                        ?>
                        <span class="result-flag result-flag-<?php echo htmlspecialchars(strtolower((string)$f), ENT_QUOTES, 'UTF-8'); ?>" style="background:<?php echo $fc; ?>;"><?php echo htmlspecialchars($fl, ENT_QUOTES, 'UTF-8'); ?></span>
                    </td>
                    <td><?php echo $isPending ? '—' : 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'=>'أدوية'];
    ?>
    <?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) {}

    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";
        echo "التاريخ,النوع,المحتوى\n";
        foreach ($medicalNotes as $n) {
            $ntLabel = $noteTypeLabels[$n['note_type'] ?? ''] ?? ($n['note_type'] ?? '');
            echo date('Y-m-d', strtotime($n['created_at'])) . ',"' . str_replace('"', '""', $ntLabel) . '","' . str_replace('"', '""', $n['content']) . "\"\n";
        }
        exit;
    }
    ?>
    <?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; ?>
    <?php
    // Triage Score مبسط للمريض: مزيج نتائج حرجة + نتائج غير طبيعية + تذكيرات متأخرة + ضغط المواعيد
    $overdueRemindersCount = 0;
    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 patient_id = ? AND is_done = 0 AND reminder_date < CURDATE()');
        $stmt->execute([$doctorAuth->accountId(), $patientId]);
        $overdueRemindersCount = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {}
    $criticalCount = 0;
    foreach ($patientSummary as $s) {
        if (($s['flag'] ?? '') === 'C') $criticalCount++;
    }
    $triageScore = min(100, ($criticalCount * 40) + (max(0, $abnormalCount - $criticalCount) * 8) + ($overdueRemindersCount * 12) + (int)min(10, $aptStats['upcoming']));
    $triageLevel = 'منخفض';
    $triageColor = '#22c55e';
    if ($triageScore >= 70) { $triageLevel = 'عالي'; $triageColor = '#dc2626'; }
    elseif ($triageScore >= 40) { $triageLevel = 'متوسط'; $triageColor = '#f59e0b'; }
    ?>
    <?php $medicalNotesCount = count($medicalNotes); ?>
    <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">الملاحظات<?php if ($medicalNotesCount > 0): ?> <span class="doctor-tab-count"><?php echo $medicalNotesCount; ?></span><?php endif; ?></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 
                            $waUrl = function_exists('doctor_wa_link') ? doctor_wa_link($patient['phone'], '') : '';
                            if ($waUrl): ?><a href="<?php echo htmlspecialchars($waUrl, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener" title="واتساب مجاني" style="color:#25D366;margin-right:6px;">💬</a><?php endif; ?><?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>
            <span style="padding:6px 12px;border-radius:14px;background:<?php echo $triageColor; ?>22;border:1px solid <?php echo $triageColor; ?>;color:<?php echo $triageColor; ?>;font-weight:700;">
                Triage: <?php echo $triageLevel; ?> (<?php echo (int)$triageScore; ?>/100)
            </span>
            <?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 class="doctor-patient-stat-card" style="border-color:<?php echo $triageColor; ?>55;">
                <span class="doctor-patient-stat-label">Triage Score</span>
                <span class="doctor-patient-stat-value" style="color:<?php echo $triageColor; ?>;"><?php echo (int)$triageScore; ?></span>
            </div>
            <div class="doctor-patient-stat-card">
                <span class="doctor-patient-stat-label">تذكيرات متأخرة</span>
                <span class="doctor-patient-stat-value"><?php echo (int)$overdueRemindersCount; ?></span>
            </div>
        </div>
        <div class="card" style="margin-top:16px;padding:16px;background:var(--bg-secondary);">
            <h4 style="margin-top:0;">🧪 طلب تحاليل جديد للمختبر</h4>
            <?php if (empty($doctorOrderTests)): ?>
            <p style="color:var(--text-muted);margin:0;">لا توجد فحوصات متاحة حالياً في هذا المختبر.</p>
            <?php else: ?>
            <form method="post" action="doctor.php?page=results&action=create_order" style="display:flex;flex-direction:column;gap:12px;">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="patient_id" value="<?php echo (int)$patientId; ?>">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                    <div>
                        <label>أولوية الطلب</label>
                        <select name="priority">
                            <option value="normal">عادي</option>
                            <option value="high">عالي</option>
                            <option value="urgent">عاجل</option>
                        </select>
                    </div>
                    <div>
                        <label>نوع العينة</label>
                        <select name="sample_type">
                            <option value="blood">دم</option>
                            <option value="urine">بول</option>
                            <option value="stool">براز</option>
                            <option value="swab">مسحة</option>
                            <option value="serum">مصل</option>
                            <option value="plasma">بلازما</option>
                            <option value="other">أخرى</option>
                        </select>
                    </div>
                </div>
                <div>
                    <label for="doctorOrderTestsSearch">الفحوصات المطلوبة</label>
                    <input type="search" id="doctorOrderTestsSearch" autocomplete="off" placeholder="بحث بالاسم أو الكود (مثال: ALT، أنزيم، CHEM)…" inputmode="search" style="width:100%;max-width:100%;margin-bottom:8px;padding:8px 12px;border:1px solid var(--border);border-radius:8px;font-size:0.95rem;">
                    <div id="doctorOrderTestsList" style="max-height:220px;overflow:auto;border:1px solid var(--border);border-radius:8px;padding:10px;background:white;">
                        <?php foreach ($doctorOrderTests as $t):
                            $filterRaw = trim(($t['name'] ?? '') . ' ' . ($t['test_code'] ?? ''));
                            $filterAttr = function_exists('mb_strtolower') ? mb_strtolower($filterRaw, 'UTF-8') : strtolower($filterRaw);
                        ?>
                        <label class="doctor-order-test-row" data-filter-text="<?php echo htmlspecialchars($filterAttr, ENT_QUOTES, 'UTF-8'); ?>" style="display:flex;gap:8px;align-items:center;padding:4px 0;">
                            <input type="checkbox" name="tests[]" value="<?php echo (int)$t['id']; ?>">
                            <span>
                                <?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?>
                                <?php if (!empty($t['test_code'])): ?>
                                    <small style="color:var(--text-muted);">(<?php echo htmlspecialchars($t['test_code'], ENT_QUOTES, 'UTF-8'); ?>)</small>
                                <?php endif; ?>
                            </span>
                        </label>
                        <?php endforeach; ?>
                    </div>
                    <p id="doctorOrderTestsNoMatch" style="display:none;margin:6px 0 0;font-size:0.85rem;color:var(--text-muted);">لا توجد فحوصات تطابق البحث.</p>
                    <script>
                    (function(){
                        var inp = document.getElementById('doctorOrderTestsSearch');
                        var box = document.getElementById('doctorOrderTestsList');
                        var emptyMsg = document.getElementById('doctorOrderTestsNoMatch');
                        if (!inp || !box) return;
                        function norm(s){ return (s || '').toString().toLowerCase().trim(); }
                        function filter(){
                            var q = norm(inp.value);
                            var rows = box.querySelectorAll('.doctor-order-test-row');
                            var n = 0;
                            for (var i = 0; i < rows.length; i++) {
                                var row = rows[i];
                                var hay = norm(row.getAttribute('data-filter-text') || row.textContent || '');
                                var show = !q || hay.indexOf(q) !== -1;
                                row.style.display = show ? 'flex' : 'none';
                                if (show) n++;
                            }
                            if (emptyMsg) emptyMsg.style.display = (q && n === 0) ? 'block' : 'none';
                        }
                        inp.addEventListener('input', filter);
                        inp.addEventListener('search', filter);
                    })();
                    </script>
                </div>
                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                    <button type="submit" class="btn-primary">إرسال الطلب للمختبر</button>
                    <small style="color:var(--text-muted);align-self:center;">بعد الإرسال يظهر الطلب مباشرة في نظام المختبر ليتم استلام العينة وإدخال النتائج.</small>
                </div>
            </form>
            <?php endif; ?>
        </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="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                <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-toolbar">
            <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>
            <div class="doctor-note-search-wrap">
                <label for="doctorNotesSearch" class="visually-hidden">بحث في الملاحظات</label>
                <input type="search" id="doctorNotesSearch" class="doctor-note-search" autocomplete="off" placeholder="بحث في نص الملاحظات…" inputmode="search">
            </div>
        </div>
        <?php
        $noteTemplates = [
            'general' => ['ملاحظة سريرية عامة', 'مراجعة دورية للمريض'],
            'lab_review' => ['مراجعة تحاليل طبيعية', 'مراجعة تحاليل - بعض النتائج تحتاج متابعة', 'مراجعة تحاليل - نتائج حرجة'],
            'diagnosis' => ['سكري - تحت السيطرة', 'ضغط دم - يحتاج تعديل علاج', 'فقر دم - يحتاج مكملات', 'كوليسترول مرتفع'],
            'follow_up' => ['متابعة بعد أسبوعين', 'متابعة بعد شهر', 'مراجعة عند الحاجة'],
            'allergy' => ['حساسية من البنسلين', 'حساسية من أدوية معينة'],
            'medication' => ['يحتاج تعديل الجرعة', 'الاستمرار على العلاج الحالي'],
        ];
        $currentDoctorAccountId = (int)$doctorAuth->accountId();
        ?>
        <form method="post" action="doctor.php?page=results&action=add_note" class="doctor-note-form">
            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
            <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="4" class="doctor-note-textarea-main"></textarea>
                    <details class="doctor-note-templates">
                        <summary>قوالب سريعة</summary>
                        <div class="doctor-note-templates-inner">
                            <?php foreach ($noteTemplates as $tplType => $tpls): ?>
                            <div class="doctor-note-template-group">
                                <span class="doctor-note-template-group-label"><?php echo $noteTypeLabels[$tplType] ?? $tplType; ?></span>
                                <div class="doctor-note-template-chips">
                                    <?php foreach ($tpls as $ti => $t): ?>
                                    <button type="button" class="doctor-note-template-btn" data-type="<?php echo htmlspecialchars($tplType, ENT_QUOTES, 'UTF-8'); ?>" data-index="<?php echo (int)$ti; ?>"><?php echo htmlspecialchars($t, ENT_QUOTES, 'UTF-8'); ?></button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </details>
                </div>
                <button type="submit" class="btn-primary">حفظ</button>
            </div>
        </form>
        <script>
        window.__doctorNoteTemplates = <?php echo json_encode($noteTemplates, JSON_UNESCAPED_UNICODE); ?>;
        </script>
        <?php if (!empty($medicalNotes)): ?>
        <p id="doctorNotesFilterEmpty" class="doctor-notes-filter-empty" style="display:none;">لا توجد ملاحظات تطابق البحث أو الفلتر الحالي.</p>
        <div class="doctor-notes-list-wrap" style="border-top:1px solid var(--border);padding-top:12px;">
            <?php foreach ($medicalNotes as $n): ?>
            <?php
            $noteAccId = isset($n['doctor_account_id']) ? (int)$n['doctor_account_id'] : 0;
            $isMyNote = ($noteAccId > 0 && $noteAccId === $currentDoctorAccountId);
            $nt = $n['note_type'] ?? 'general';
            $searchHay = $n['content'] ?? '';
            $searchHayLower = function_exists('mb_strtolower') ? mb_strtolower($searchHay, 'UTF-8') : strtolower($searchHay);
            ?>
            <div class="doctor-note-item <?php echo $isMyNote ? 'doctor-note-item--mine' : 'doctor-note-item--readonly'; ?> doctor-note-type--<?php echo htmlspecialchars(preg_replace('/[^a-z0-9_]/i', '', $nt) ?: 'general', ENT_QUOTES, 'UTF-8'); ?>" data-type="<?php echo htmlspecialchars($nt, ENT_QUOTES, 'UTF-8'); ?>" data-search-text="<?php echo htmlspecialchars($searchHayLower, ENT_QUOTES, 'UTF-8'); ?>">
                <div class="doctor-note-header-row">
                    <div class="doctor-note-meta-block">
                        <span class="doctor-note-type-badge doctor-note-type-badge--<?php echo htmlspecialchars(preg_replace('/[^a-z0-9_]/i', '', $nt) ?: 'general', ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($noteTypeLabels[$nt] ?? $nt, ENT_QUOTES, 'UTF-8'); ?></span>
                        <span class="doctor-note-meta"><?php echo date('Y-m-d H:i', strtotime($n['created_at'])); ?><?php if (!$isMyNote): ?> · <span class="doctor-note-readonly-hint">قراءة فقط (طبيب آخر)</span><?php endif; ?></span>
                    </div>
                    <?php if ($isMyNote): ?>
                    <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($nt, ENT_QUOTES, 'UTF-8'); ?>">
                            تعديل
                        </button>
                        <form method="post" action="doctor.php?page=results" style="display:inline;" onsubmit="return confirm('حذف هذه الملاحظة؟');">
                            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                            <input type="hidden" name="action" value="delete_note">
                            <input type="hidden" name="id" value="<?php echo (int)$n['id']; ?>">
                            <input type="hidden" name="patient_id" value="<?php echo (int)$patientId; ?>">
                            <button type="submit" class="doctor-note-delete">حذف</button>
                        </form>
                    </div>
                    <?php endif; ?>
                </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>
                <?php if ($isMyNote): ?>
                <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="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                    <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>
                <?php endif; ?>
            </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');
        var searchInput = document.getElementById('doctorNotesSearch');
        var filterEmptyMsg = document.getElementById('doctorNotesFilterEmpty');
        var activeFilter = 'all';
        function norm(s){ return (s || '').toString().toLowerCase().trim(); }
        function applyNoteFilters(){
            var q = searchInput ? norm(searchInput.value) : '';
            var visible = 0;
            noteItems.forEach(function(item){
                var t = item.getAttribute('data-type');
                var hay = norm(item.getAttribute('data-search-text') || item.textContent || '');
                var typeOk = (activeFilter === 'all' || activeFilter === t);
                var searchOk = !q || hay.indexOf(q) !== -1;
                var show = typeOk && searchOk;
                item.style.display = show ? '' : 'none';
                if (show) visible++;
            });
            if (filterEmptyMsg) filterEmptyMsg.style.display = (noteItems.length && visible === 0) ? 'block' : 'none';
        }
        filterChips.forEach(function(chip){
            chip.addEventListener('click', function(){
                activeFilter = this.getAttribute('data-filter') || 'all';
                filterChips.forEach(function(c){ c.classList.remove('doctor-note-filter-active'); });
                this.classList.add('doctor-note-filter-active');
                applyNoteFilters();
            });
        });
        if (searchInput) {
            searchInput.addEventListener('input', applyNoteFilters);
            searchInput.addEventListener('search', applyNoteFilters);
        }
        document.querySelectorAll('.doctor-note-template-btn').forEach(function(btn){
            btn.addEventListener('click', function(){
                var tplType = this.getAttribute('data-type');
                var idx = parseInt(this.getAttribute('data-index'), 10);
                var tpls = window.__doctorNoteTemplates && window.__doctorNoteTemplates[tplType];
                if (!tpls || tpls[idx] === undefined) return;
                var sel = document.getElementById('noteTypeSelect');
                var ta = document.getElementById('noteContent');
                if (sel) sel.value = tplType;
                if (ta) { ta.value = tpls[idx]; ta.focus(); }
            });
        });
        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>
