<?php

use App\Core\Auth;
use App\Core\Tenant;

$orderId = (int)($_GET['order_id'] ?? 0);
$shareToken = trim($_GET['share_token'] ?? '');
if ($shareToken !== '') {
    try {
        $db->query('SELECT id FROM report_share_links LIMIT 1');
        $stmt = $db->prepare('SELECT order_id FROM report_share_links WHERE token = ? AND expires_at > NOW()');
        $stmt->execute([$shareToken]);
        $row = $stmt->fetch();
        if ($row) $orderId = (int)$row['order_id'];
    } catch (Throwable $e) {}
}
$tenantId = Tenant::id();

// تفعيل إظهار الشعار تلقائياً إذا طلب المستخدم
if (isset($_GET['enable_logo']) && isset($auth) && $auth instanceof Auth && $auth->can('settings.manage')) {
    try {
        $hasTenant = false;
        try { $db->query('SELECT tenant_id FROM settings LIMIT 1'); $hasTenant = true; } catch (Throwable $e) {}
        $stmt = $hasTenant
            ? $db->prepare('INSERT INTO settings (tenant_id, setting_key, setting_value, updated_at) VALUES (?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()')
            : $db->prepare('INSERT INTO settings (setting_key, setting_value, updated_at) VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()');
        if ($hasTenant) {
            $stmt->execute([$tenantId, 'print_report_logo', '1']);
        } else {
            $stmt->execute(['print_report_logo', '1']);
        }
        header('Location: index.php?page=print_result&order_id=' . $orderId . (isset($_GET['debug_logo']) ? '&debug_logo=1' : ''));
        exit;
    } catch (Throwable $e) {}
}

$fromPortal = isset($_GET['from_portal']) && isset($_GET['token']);
$portalToken = $_GET['token'] ?? '';
$maskResults = isset($auth) && $auth instanceof Auth && $auth->maskResults();
$officialCopy = isset($_GET['official']) && $_GET['official'] === '1';

if ($orderId <= 0) {
    echo 'طلب غير معروف';
    return;
}

$order = null;
$items = [];

try {
    $orderTenantWhere = '';
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $orderTenantWhere = ' AND o.tenant_id = :tid'; } catch (Throwable $e) {}
    $orderCols = 'o.order_number, o.order_date, o.status, o.patient_id, p.full_name AS patient_name, p.gender, p.date_of_birth, p.phone, d.full_name AS doctor_name';
    try { $db->query('SELECT approved_at FROM lab_orders LIMIT 1'); $orderCols .= ', o.approved_at, o.approved_by, o.report_id'; } catch (Throwable $e) {}
    $stmt = $db->prepare(
        'SELECT ' . $orderCols . ' FROM lab_orders o
         JOIN patients p ON p.id = o.patient_id
         LEFT JOIN doctors d ON d.id = o.doctor_id
         WHERE o.id = :id' . $orderTenantWhere
    );
    $params = ['id' => $orderId];
    if ($orderTenantWhere) $params['tid'] = $tenantId;
    $stmt->execute($params);
    $order = $stmt->fetch();

    $techCol = '';
    try { $db->query('SELECT tech_name FROM results LIMIT 1'); $techCol = ', r.tech_name'; } catch (Throwable $e) {}
    $eduCol = '';
    try { $db->query('SELECT educational_content FROM tests LIMIT 1'); $eduCol = ', t.educational_content'; } catch (Throwable $e) {}
    $stmt = $db->prepare(
        'SELECT t.name AS test_name, t.unit, t.reference_range' . $eduCol . ',
                r.result_value, r.flag, r.notes' . $techCol . '
         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 = :id'
    );
    $stmt->execute(['id' => $orderId]);
    $items = $stmt->fetchAll();
} catch (Throwable $e) {
}

if (!$order) {
    echo 'الطلب غير موجود';
    return;
}

if ($fromPortal) {
    $secret = $config['security']['portal_token_secret'] ?? 'lab_portal';
    $expected = md5($orderId . ($order['patient_id'] ?? 0) . $secret);
    if ($portalToken !== $expected) {
        http_response_code(403);
        echo 'رابط غير صالح أو منتهي الصلاحية.';
        return;
    }
}
if ($shareToken !== '' && $orderId <= 0) {
    http_response_code(403);
    echo 'رابط المشاركة غير صالح أو منتهي الصلاحية.';
    return;
}

$labName = 'مختبر تحاليل';
$labPhone = '';
$labLogo = '';
$logoUrlRaw = ''; // للمسار الأصلي من قاعدة البيانات
$primaryColor = '#0d9488';
// حساب المسار الأساسي للتطبيق (يتم استخدامه لاحقاً في الكود)
$scriptDirForLogo = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
if ($scriptDirForLogo === '/') $scriptDirForLogo = '';
$basePathForLogo = $scriptDirForLogo;
try {
    $db->query('SELECT tenant_id FROM settings LIMIT 1');
    $stmt = $db->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('lab_name','lab_phone') AND tenant_id = ?");
    $stmt->execute([$tenantId]);
    $settings = [];
    foreach ($stmt->fetchAll() as $r) {
        if (!isset($settings[$r['setting_key']])) $settings[$r['setting_key']] = $r['setting_value'] ?? '';
    }
    if (!empty($settings['lab_name'])) $labName = $settings['lab_name'];
    if (isset($settings['lab_phone'])) $labPhone = $settings['lab_phone'] ?? '';
} catch (Throwable $e) {
    try {
        $stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('lab_name','lab_phone')");
        foreach ($stmt->fetchAll() as $r) {
            if ($r['setting_key'] === 'lab_name') $labName = $r['setting_value'] ?: $labName;
            if ($r['setting_key'] === 'lab_phone') $labPhone = $r['setting_value'] ?? '';
        }
    } catch (Throwable $e2) {}
}
try {
    $stmt = $db->prepare('SELECT name, logo_url, primary_color FROM tenants WHERE id = ?');
    $stmt->execute([$tenantId]);
    $t = $stmt->fetch();
    if ($t) {
        if (!empty($t['name'])) $labName = $t['name'];
        $logoUrlRaw = trim((string)($t['logo_url'] ?? ''));
        // تنظيف المسار من أي `/` إضافية في البداية والنهاية
        $logoUrlRaw = trim($logoUrlRaw, '/');
        // حفظ المسار الأصلي للتصحيح
        // إذا كان المسار نسبي (uploads/logos/...)، استخدم المسار الأساسي للتطبيق
        if (!empty($logoUrlRaw)) {
            // إذا كان رابط خارجي، استخدمه كما هو
            if (strpos($logoUrlRaw, 'http') === 0 || strpos($logoUrlRaw, '//') === 0) {
                $labLogo = $logoUrlRaw;
            } else {
                // مسار محلي - استخدم المسار الأساسي للتطبيق
                $labLogo = $basePathForLogo . '/' . $logoUrlRaw;
                // التحقق من وجود الملف (اختياري - للتصحيح فقط)
                $logoPath = __DIR__ . '/../' . $logoUrlRaw;
                if (!file_exists($logoPath)) {
                    // جرب مع / في البداية
                    $logoPathAlt = __DIR__ . '/../' . ltrim($logoUrlRaw, '/');
                    if (file_exists($logoPathAlt)) {
                        $labLogo = $basePathForLogo . '/' . ltrim($logoUrlRaw, '/');
                    }
                }
            }
        } else {
            $labLogo = '';
        }
        $primaryColor = (string)($t['primary_color'] ?? '#0d9488');
    }
} catch (Throwable $e) {
    // في حالة الخطأ، اترك $labLogo فارغاً
    $labLogo = '';
}
$printSettings = [];
try {
    $hasTenant = false;
    try { $db->query('SELECT tenant_id FROM settings LIMIT 1'); $hasTenant = true; } catch (Throwable $e) {}
    $stmt = $hasTenant ? $db->prepare('SELECT setting_key, setting_value FROM settings WHERE tenant_id = ? AND setting_key LIKE "print_%"') : $db->query('SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE "print_%"');
    if ($hasTenant) $stmt->execute([$tenantId]);
    if ($stmt) foreach ($stmt->fetchAll() as $r) { $printSettings[$r['setting_key']] = $r['setting_value'] ?? ''; }
} catch (Throwable $e) {}
if (!empty($printSettings['print_report_color'])) $primaryColor = $printSettings['print_report_color'];
// حفظ حالة إعدادات الطباعة (لا نحذف $labLogo هنا، سنستخدمه للتحقق لاحقاً)
// ملاحظة: إذا لم يكن هناك إعداد في قاعدة البيانات، افترض أن اللوجو مفعّل (القيمة الافتراضية '1')
$logoSettingDisabled = isset($printSettings['print_report_logo']) && $printSettings['print_report_logo'] === '0';
// لا نحذف $labLogo هنا حتى نتمكن من عرض رسالة توضيحية إذا كان موجوداً لكن معطلاً
$tenantSlugParam = trim($_GET['tenant'] ?? '');
$isApproved = !empty($order['approved_at']);
$reportId = $order['report_id'] ?? strtoupper(substr(md5($orderId . ($order['order_number'] ?? '') . date('Y-m-d')), 0, 8));
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
$scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
if ($scriptDir === '/') $scriptDir = '';
$verifyUrl = $baseUrl . $scriptDir . '/verify_report.php?code=' . urlencode($reportId);
$showQr = ($printSettings['print_report_show_qr'] ?? '1') === '1';
$qrUrl = $showQr ? 'https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=' . urlencode($verifyUrl) : '';
$printFooter = trim($printSettings['print_report_footer'] ?? '');

$didLogPrint = false;
if (isset($_GET['log_print']) && $isApproved && isset($auth) && $auth->check()) {
    try {
        $db->query('SELECT id FROM print_log LIMIT 1');
        $pt = $officialCopy ? 'official' : 'normal';
        $stmt = $db->prepare('INSERT INTO print_log (order_id, user_id, print_type, copies, ip_address, tenant_id) VALUES (?, ?, ?, 1, ?, ?)');
        $stmt->execute([
            $orderId,
            $_SESSION['user_id'] ?? null,
            $pt,
            $_SERVER['REMOTE_ADDR'] ?? null,
            $tenantId
        ]);
        $didLogPrint = true;
    } catch (Throwable $e) {}
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>تقرير نتائج - <?php echo htmlspecialchars($labName, ENT_QUOTES, 'UTF-8'); ?></title>
    <link rel="stylesheet" href="styles.css">
    <style>
        <?php
        $printPaper = $printSettings['print_report_paper'] ?? 'A4';
        $fontSize = $printSettings['print_report_font_size'] ?? 'normal';
        $orientation = $printSettings['print_report_orientation'] ?? 'portrait';
        $margin = $printSettings['print_report_margin'] ?? 'normal';
        $marginSize = $margin === 'small' ? '5mm' : ($margin === 'large' ? '20mm' : '12mm');
        $baseSize = $fontSize === 'small' ? '11px' : ($fontSize === 'large' ? '14px' : '12px');
        $showWatermark = ($printSettings['print_report_watermark'] ?? '1') === '1';
        $tableStriped = ($printSettings['print_report_table_striped'] ?? '1') === '1';
        $headerText = trim($printSettings['print_report_header_text'] ?? '');
        ?>
        @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Arabic:wght@400;500;600;700&display=swap');
        @page { size: <?php echo htmlspecialchars($printPaper, ENT_QUOTES, 'UTF-8'); ?> <?php echo htmlspecialchars($orientation, ENT_QUOTES, 'UTF-8'); ?>; margin: <?php echo $marginSize; ?>; }
        .lab-report { font-family: 'IBM Plex Sans Arabic', 'IBM Plex Sans', 'Tajawal', sans-serif; font-size: <?php echo $baseSize; ?>; color: #1a1a1a; line-height: 1.5; }
        .lab-report .report-container { max-width: 100%; }
        .lab-report .report-header { border: none; padding-bottom: 20px; margin-bottom: 20px; border-bottom: 2px solid <?php echo htmlspecialchars($primaryColor, ENT_QUOTES, 'UTF-8'); ?>; display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 20px; }
        .lab-report .report-header .lab-brand { display: flex; align-items: center; gap: 16px; }
        .lab-report .report-header .lab-brand img { max-height: 64px; max-width: 140px; object-fit: contain; }
        .lab-report .report-header .lab-info { text-align: right; }
        .lab-report .report-header .lab-info .lab-name { font-size: 1.35rem; font-weight: 700; color: <?php echo htmlspecialchars($primaryColor, ENT_QUOTES, 'UTF-8'); ?>; margin: 0 0 4px; letter-spacing: -0.02em; }
        .lab-report .report-header .lab-info .lab-meta { font-size: 0.85rem; color: #5f6368; }
        .lab-report .report-header .order-meta { text-align: left; direction: ltr; }
        .lab-report .report-header .order-meta .order-id { font-size: 1.1rem; font-weight: 700; color: #1a1a1a; }
        .lab-report .report-header .order-meta .order-date { font-size: 0.9rem; color: #5f6368; }
        .lab-report .report-title { font-size: 1.15rem; font-weight: 600; color: #1a1a1a; text-align: center; margin: 24px 0 20px; padding: 10px 0; border-top: 1px solid #e8eaed; border-bottom: 1px solid #e8eaed; letter-spacing: 0.02em; }
        .lab-report .report-patient { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 8px 24px; padding: 16px 20px; background: #f8f9fa; border-radius: 6px; margin-bottom: 24px; border: 1px solid #e8eaed; }
        .lab-report .report-patient .patient-field { display: flex; gap: 8px; }
        .lab-report .report-patient .patient-field strong { min-width: 90px; color: #5f6368; font-weight: 500; }
        .lab-report .report-patient .patient-field span { color: #1a1a1a; font-weight: 500; }
        .lab-report .results-table { width: 100%; border-collapse: collapse; font-size: <?php echo $baseSize; ?>; box-shadow: 0 1px 3px rgba(0,0,0,0.06); border-radius: 6px; overflow: hidden; }
        .lab-report .results-table thead th { background: <?php echo htmlspecialchars($primaryColor, ENT_QUOTES, 'UTF-8'); ?>; color: #fff; font-weight: 600; padding: 12px 16px; text-align: right; font-size: 0.9em; }
        .lab-report .results-table tbody td { padding: 12px 16px; border-bottom: 1px solid #e8eaed; text-align: right; }
        <?php if ($tableStriped): ?>.lab-report .results-table tbody tr:nth-child(even) { background: #fafbfc; }<?php endif; ?>
        .lab-report .results-table tbody tr:last-child td { border-bottom: none; }
        .lab-report .results-table tbody tr.result-out-of-range { background: #fef3e8 !important; }
        .lab-report .results-table tbody tr.result-out-of-range td:nth-child(2) { font-weight: 700; color: #c2410c; }
        .lab-report .results-table .test-name { font-weight: 500; color: #1a1a1a; }
        .lab-report .results-table .result-value { font-weight: 600; }
        .lab-report .results-table .ref-range { font-size: 0.9em; color: #5f6368; }
        .lab-report .results-table .flag-badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 0.8em; font-weight: 600; }
        .lab-report .results-table .flag-L { background: #dbeafe; color: #1d4ed8; }
        .lab-report .results-table .flag-H { background: #fee2e2; color: #b91c1c; }
        .lab-report .results-table .flag-C { background: #fef3c7; color: #b45309; }
        .lab-report .report-footer { margin-top: 32px; padding-top: 20px; border-top: 2px solid #e8eaed; display: flex; justify-content: space-between; align-items: flex-end; flex-wrap: wrap; gap: 20px; }
        .lab-report .report-footer .footer-left .legal-timestamp { font-size: 0.8rem; color: #5f6368; margin-top: 4px; }
        .lab-report .report-footer .footer-left .signature-line { margin-top: 24px; padding-top: 4px; border-top: 1px solid #1a1a1a; font-size: 0.85rem; max-width: 200px; }
        .lab-report .report-footer .qr-box { text-align: center; padding: 8px; border: 1px solid #e8eaed; border-radius: 6px; background: #fff; }
        .lab-report .report-footer .qr-box img { display: block; }
        .lab-report .legal-watermark { position: fixed; top: 50%; left: 50%; transform: translate(-50%,-50%) rotate(-25deg); font-size: 2.8rem; color: rgba(0,0,0,0.06); white-space: nowrap; z-index: 0; pointer-events: none; font-weight: 700; }
        @media print { .lab-report .legal-watermark { color: rgba(0,0,0,0.05); } .lab-report .results-table { box-shadow: none; } }
    </style>
</head>
<body class="print-page lab-report">
    <?php if ($showWatermark): ?>
    <?php if (!$isApproved): ?>
    <div class="legal-watermark" aria-hidden="true" style="font-size:2.2rem;color:rgba(220,38,38,0.2);">غير معتمد — قيد المراجعة</div>
    <?php elseif ($officialCopy): ?>
    <div class="legal-watermark" aria-hidden="true">نسخة رسمية — <?php echo date('Y-m-d H:i:s'); ?></div>
    <?php else: ?>
    <div class="legal-watermark" aria-hidden="true">نسخة للاطلاع — <?php echo date('Y-m-d H:i'); ?></div>
    <?php endif; ?>
    <?php endif; ?>
    <div class="report-container">
        <div class="no-print" style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:16px;align-items:center;">
            <?php if (!$isApproved): ?>
            <span class="alert alert-danger" style="margin:0;flex:1;">التقرير قيد المراجعة. الطباعة متاحة فقط بعد الاعتماد النهائي من صفحة النتائج.</span>
            <button type="button" onclick="window.print()" style="padding:10px 20px;background:#0d9488;color:#fff;border:none;border-radius:6px;font-weight:600;cursor:pointer;">طباعة</button>
            <button type="button" id="btnDownloadPdf" style="padding:10px 20px;background:#f1f5f9;color:#334155;border:1px solid #e2e8f0;border-radius:6px;font-weight:600;cursor:pointer;">تحميل PDF</button>
            <?php else: ?>
            <?php $printBase = 'index.php?page=print_result'.($shareToken ? '&share_token='.urlencode($shareToken) : '&order_id='.$orderId.($fromPortal ? '&from_portal=1&token='.urlencode($portalToken) : '')).($tenantSlugParam ? '&tenant='.urlencode($tenantSlugParam) : ''); ?>
            <?php $canLogPrint = isset($auth) && $auth instanceof Auth && $auth->check(); ?>
            <?php if ($canLogPrint): ?>
            <a href="<?php echo htmlspecialchars($printBase . '&log_print=1&official=1'); ?>" class="btn-primary" target="_blank" style="padding:10px 20px;background:#0d9488;color:#fff;border-radius:6px;font-weight:600;text-decoration:none;">طباعة نسخة رسمية</a>
            <a href="<?php echo htmlspecialchars($printBase . '&log_print=1'); ?>" target="_blank" style="padding:10px 20px;background:#f1f5f9;color:#334155;border-radius:6px;font-weight:600;text-decoration:none;">طباعة عادية</a>
            <?php endif; ?>
            <button type="button" onclick="window.print()" style="padding:10px 20px;background:#0d9488;color:#fff;border:none;border-radius:6px;font-weight:600;cursor:pointer;">طباعة</button>
            <button type="button" id="btnDownloadPdf" style="padding:10px 20px;background:#f1f5f9;color:#334155;border:1px solid #e2e8f0;border-radius:6px;font-weight:600;cursor:pointer;">تحميل PDF</button>
            <?php endif; ?>
        </div>
        <?php if ($headerText): ?><div style="text-align:center;padding:8px 0;margin-bottom:12px;font-size:0.9em;color:#5f6368;border-bottom:1px solid #e8eaed;"><?php echo htmlspecialchars($headerText, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
        <div class="report-header">
            <div class="lab-brand">
                <?php 
                $logoEnabled = !$logoSettingDisabled;
                $hasLogoInDb = !empty($labLogo);
                $showLogo = $hasLogoInDb && $logoEnabled;
                $debugMode = isset($_GET['debug_logo']);
                if ($showLogo): ?>
                <img src="<?php echo htmlspecialchars($labLogo, ENT_QUOTES, 'UTF-8'); ?>" alt="Logo" onerror="this.style.display='none'">
                <?php elseif ($hasLogoInDb && !$logoEnabled): ?>
                <div class="no-print" style="padding:10px;background:#fff3cd;border:1px solid #ffc107;border-radius:4px;font-size:0.85em;">
                    <strong>⚠️ الشعار معطّل</strong>
                    <?php if (isset($auth) && $auth instanceof Auth && $auth->can('settings.manage')): ?>
                    <a href="index.php?page=print_result&order_id=<?php echo $orderId; ?>&enable_logo=1" style="color:var(--primary);font-weight:600;margin-right:8px;">تفعيل</a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <div class="lab-info">
                    <div class="lab-name"><?php echo htmlspecialchars($labName, ENT_QUOTES, 'UTF-8'); ?></div>
                    <div class="lab-meta"><?php echo htmlspecialchars($labPhone ?: '', ENT_QUOTES, 'UTF-8'); ?></div>
                </div>
            </div>
            <div class="order-meta">
                <div class="order-id"><?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></div>
                <div class="order-date"><?php echo htmlspecialchars($order['order_date'], ENT_QUOTES, 'UTF-8'); ?> • <?php echo htmlspecialchars($order['status'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
        </div>
        <h2 class="report-title">تقرير نتائج الفحوصات المخبرية</h2>
        <div class="report-patient">
            <div class="patient-field"><strong>اسم المريض:</strong> <span><?php echo htmlspecialchars($order['patient_name'], ENT_QUOTES, 'UTF-8'); ?></span></div>
            <div class="patient-field"><strong>الجنس:</strong> <span><?php echo $order['gender'] === 'M' ? 'ذكر' : ($order['gender'] === 'F' ? 'أنثى' : '-'); ?></span></div>
            <div class="patient-field"><strong>تاريخ الميلاد:</strong> <span><?php echo htmlspecialchars($order['date_of_birth'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></span></div>
            <div class="patient-field"><strong>الهاتف:</strong> <span><?php echo htmlspecialchars($order['phone'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></span></div>
            <div class="patient-field"><strong>الطبيب المحوِّل:</strong> <span><?php echo htmlspecialchars($order['doctor_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></span></div>
        </div>
        <?php if (empty($items)): ?>
        <div class="alert alert-warning">لا توجد فحوصات في هذا الطلب، أو لم تُدخل النتائج بعد. تأكد من إدخال النتائج من صفحة النتائج أولاً.</div>
        <?php else: ?>
        <table class="results-table">
            <thead>
                <tr>
                    <th>الفحص</th>
                    <th>النتيجة</th>
                    <th>الوحدة</th>
                    <th>المدى المرجعي</th>
                    <th>الملاحظة</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($items as $row): 
                $isOut = in_array($row['flag'] ?? '', ['L','H','C']);
                $flag = $row['flag'] ?? '';
                $flagLabel = '';
                if ($flag === 'L') $flagLabel = 'منخفض';
                elseif ($flag === 'H') $flagLabel = 'مرتفع';
                elseif ($flag === 'C') $flagLabel = 'حرج';
                ?>
                <tr<?php echo $isOut ? ' class="result-out-of-range"' : ''; ?>>
                    <td class="test-name">
                        <?php echo htmlspecialchars($row['test_name'], ENT_QUOTES, 'UTF-8'); ?>
                        <?php if (!empty($row['educational_content'])): ?>
                        <div style="font-size:0.85em;color:#5f6368;margin-top:4px;font-weight:400;"><?php echo nl2br(htmlspecialchars($row['educational_content'], ENT_QUOTES, 'UTF-8')); ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="result-value"><?php echo $maskResults ? '—' : htmlspecialchars($row['result_value'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['unit'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td class="ref-range"><?php echo htmlspecialchars($row['reference_range'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td>
                        <?php if ($maskResults): ?>
                        —
                        <?php elseif ($flagLabel): ?>
                        <span class="flag-badge flag-<?php echo htmlspecialchars($flag, ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($flagLabel, ENT_QUOTES, 'UTF-8'); ?></span>
                        <?php elseif (!empty($row['notes'])): ?>
                        <?php echo htmlspecialchars($row['notes'], ENT_QUOTES, 'UTF-8'); ?>
                        <?php else: ?>
                        —
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
        <div class="report-footer">
            <div class="footer-left">
                <?php $techName = ($items[0] ?? [])['tech_name'] ?? null; if ($techName): ?>
                <div style="font-size:0.9em;color:#5f6368;"><strong>الفني:</strong> <?php echo htmlspecialchars($techName, ENT_QUOTES, 'UTF-8'); ?></div>
                <?php endif; ?>
                <div class="legal-timestamp">Report ID: <?php echo htmlspecialchars($reportId, ENT_QUOTES, 'UTF-8'); ?></div>
                <div class="legal-timestamp">Printed: <?php echo date('Y-m-d H:i'); ?></div>
                <?php $sig = null; try { $db->query('SELECT approved_signature FROM lab_orders LIMIT 1'); $s = $db->prepare('SELECT approved_signature FROM lab_orders WHERE id = ?'); $s->execute([$orderId]); $sig = $s->fetchColumn(); } catch (Throwable $e) {} ?>
                <div class="signature-line"><?php echo $sig ? htmlspecialchars($sig, ENT_QUOTES, 'UTF-8') : 'المدير الفني ________________'; ?></div>
                <?php if ($printFooter): ?><div class="legal-timestamp" style="margin-top:12px;"><?php echo htmlspecialchars($printFooter, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
            </div>
            <?php if ($isApproved && $showQr && $qrUrl): ?>
            <div class="qr-box">
                <img src="<?php echo htmlspecialchars($qrUrl, ENT_QUOTES, 'UTF-8'); ?>" alt="Verify" width="72" height="72">
                <div style="font-size:0.7rem;color:#5f6368;margin-top:4px;">Verify Report</div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script>
    document.getElementById('btnDownloadPdf') && document.getElementById('btnDownloadPdf').addEventListener('click', function(){
        var btn = this;
        btn.disabled = true;
        btn.textContent = 'جاري التحميل...';
        var el = document.querySelector('.report-container');
        var toClone = el.cloneNode(true);
        var noPrint = toClone.querySelector('.no-print');
        if (noPrint) noPrint.remove();
        var opt = { margin: 10, filename: 'تقرير_<?php echo preg_replace('/[^a-z0-9_-]/i', '_', $order['order_number'] ?? 'result'); ?>.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2, useCORS: true }, jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' } };
        html2pdf().set(opt).from(toClone).save().then(function(){ btn.disabled = false; btn.textContent = 'تحميل PDF'; });
    });
    </script>
</body>
</html>