<?php
/**
 * طباعة نتائج التحاليل - للطبيب
 */
require_once __DIR__ . '/_result_helpers.php';
$orderId = (int)($_GET['order_id'] ?? 0);
$tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
$doctorCond = ' AND o.doctor_id = ' . (int)$doctorId;

if ($orderId <= 0) {
    header('Location: doctor.php?page=results');
    exit;
}

$order = null;
$results = [];
try {
    $stmt = $db->prepare("SELECT o.*, p.full_name AS patient_name, p.patient_code, p.date_of_birth, p.gender, p.phone 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.name AS test_name, r.result_value, r.unit, r.reference_range, r.flag, r.notes
                             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();
    }
} catch (Throwable $e) {}

if (!$order) {
    header('Location: doctor.php?page=results');
    exit;
}

$labName = 'المختبر';
try {
    $stmt = $db->prepare('SELECT name FROM tenants WHERE id = ?');
    $stmt->execute([$tenantId]);
    $t = $stmt->fetch();
    if ($t && !empty($t['name'])) $labName = $t['name'];
} catch (Throwable $e) {}

$flagLabels = ['N' => 'طبيعي', 'L' => 'منخفض', 'H' => 'مرتفع', 'C' => 'حرج', 'P' => 'بانتظار المختبر'];
?>
<!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($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></title>
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Tajawal', Arial, sans-serif; margin: 20px; color: #1e293b; }
        .print-header { text-align: center; margin-bottom: 24px; border-bottom: 2px solid #0d9488; padding-bottom: 16px; }
        .print-header h1 { margin: 0; color: #0d9488; font-size: 1.5rem; }
        .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 20px; }
        .info-grid div { padding: 8px; background: #f8fafc; border-radius: 6px; }
        table { width: 100%; border-collapse: collapse; margin-top: 16px; }
        th, td { border: 1px solid #e2e8f0; padding: 10px; text-align: right; }
        th { background: #0d9488; color: white; }
        tr.abnormal { background: #fef2f2; }
        .flag { padding: 4px 8px; border-radius: 4px; font-size: 12px; }
        .flag-N { background: #22c55e; color: white; }
        .flag-L { background: #f59e0b; color: white; }
        .flag-H { background: #ef4444; color: white; }
        .flag-C { background: #dc2626; color: white; }
        .flag-P { background: #64748b; color: white; }
        .footer { margin-top: 24px; text-align: center; font-size: 12px; color: #64748b; }
        @media print { body { margin: 0; } .no-print { display: none !important; } }
        @media (max-width: 600px) {
            body { margin: 12px; }
            .info-grid { grid-template-columns: 1fr; }
            .no-print { flex-direction: column; align-items: stretch; }
            table { font-size: 0.85rem; }
            th, td { padding: 8px 6px; }
        }
    </style>
</head>
<body>
    <div class="report-container">
    <div class="no-print" style="margin-bottom:16px;display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
        <button onclick="window.print()" style="padding:10px 20px;background:#0d9488;color:white;border:none;border-radius:6px;cursor:pointer;">🖨️ طباعة</button>
        <button type="button" id="btnDownloadPdf" style="padding:10px 20px;background:#1e3a5f;color:white;border:none;border-radius:6px;cursor:pointer;">📥 تحميل PDF</button>
        <a href="doctor.php?page=results&order_id=<?php echo $orderId; ?>" style="color:#0d9488;">← رجوع</a>
        <a href="doctor.php?page=results&patient_id=<?php echo (int)$order['patient_id']; ?>" style="color:#0d9488;">عرض المريض</a>
    </div>

    <div class="print-header">
        <h1><?php echo htmlspecialchars($labName, ENT_QUOTES, 'UTF-8'); ?></h1>
        <p style="margin:8px 0 0;">تقرير نتائج التحاليل - Smart Doctor</p>
    </div>

    <div class="info-grid">
        <div><strong>رقم الطلب:</strong> <?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></div>
        <div><strong>التاريخ:</strong> <?php echo date('Y-m-d H:i', strtotime($order['order_date'])); ?></div>
        <div><strong>المريض:</strong> <?php echo htmlspecialchars($order['patient_name'], ENT_QUOTES, 'UTF-8'); ?></div>
        <div><strong>الرقم:</strong> <?php echo htmlspecialchars($order['patient_code'], ENT_QUOTES, 'UTF-8'); ?></div>
        <div><strong>الطبيب:</strong> د. <?php echo htmlspecialchars($_SESSION['doctor_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></div>
        <div><strong>الحالة:</strong> <?php echo $order['status'] === 'completed' ? 'مكتمل' : $order['status']; ?></div>
    </div>

    <table>
        <thead>
            <tr>
                <th>الفحص</th>
                <th>النتيجة</th>
                <th>الوحدة</th>
                <th>المدى المرجعي</th>
                <th>الحالة</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($results as $r):
            $pend = doctor_order_result_is_pending($r);
            $f = $pend ? 'P' : ($r['flag'] ?? 'N');
            $abnormal = !$pend && in_array($f, ['L','H','C'], true);
        ?>
        <tr class="<?php echo $abnormal ? 'abnormal' : ''; ?>">
            <td><strong><?php echo htmlspecialchars($r['test_name'], ENT_QUOTES, 'UTF-8'); ?></strong></td>
            <td><?php echo $pend ? '—' : htmlspecialchars((string)($r['result_value'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo $pend ? '—' : htmlspecialchars($r['unit'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo $pend ? '—' : htmlspecialchars($r['reference_range'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><span class="flag flag-<?php echo htmlspecialchars($f, ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($flagLabels[$f] ?? $f, ENT_QUOTES, 'UTF-8'); ?></span></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <div class="footer" style="margin-top:24px;">
        <p>تم الطباعة من بوابة Smart Doctor - <?php echo date('Y-m-d H:i'); ?></p>
    </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script>
    (function(){
    var doPdf = /[?&]pdf=1/.test(location.search);
    function runPdf(){ var btn = document.getElementById('btnDownloadPdf'); if (btn && typeof html2pdf !== 'undefined') { btn.click(); } }
    if (doPdf) { if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', function(){ setTimeout(runPdf, 500); }); else setTimeout(runPdf, 500); }
    })();
    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 ? el.cloneNode(true) : document.body;
        if (toClone) {
            var noPrint = toClone.querySelector && 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 || document.body).save().then(function(){ btn.disabled = false; btn.textContent = '📥 تحميل PDF'; });
    });
    </script>
</body>
</html>
