<?php
/**
 * تصدير الملف الطبي للمريض - صفحة قابلة للطباعة/PDF
 * استخدم Ctrl+P لحفظ كـ PDF
 */
$patientId = (int)($_GET['patient_id'] ?? 0);
if ($patientId <= 0) {
    die('معرف المريض غير صالح');
}

$patient = null;
$orders = [];
$results = [];
$medicalNotes = [];
$diagnoses = [];
$abnormalSummary = [];

try {
    $stmt = $db->prepare("SELECT p.* FROM patients p WHERE p.id = ? LIMIT 1");
    try { $db->query('SELECT tenant_id FROM patients LIMIT 1'); $stmt = $db->prepare("SELECT p.* FROM patients p WHERE p.id = ? AND p.tenant_id = ? LIMIT 1"); $stmt->execute([$patientId, $tenantId]); } catch (Throwable $e) { $stmt->execute([$patientId]); }
    if ($stmt->rowCount() === 0) { $stmt->execute([$patientId]); }
    $patient = $stmt->fetch();
} catch (Throwable $e) {}

if (!$patient) die('المريض غير موجود');

try {
    $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 100");
    $stmt->execute([$patientId]);
    $orders = $stmt->fetchAll();
} catch (Throwable $e) {}

try {
    $db->query('SELECT id FROM patient_medical_notes LIMIT 1');
    $stmt = $db->prepare('SELECT * FROM patient_medical_notes WHERE patient_id = ? ORDER BY created_at DESC LIMIT 50');
    $stmt->execute([$patientId]);
    $medicalNotes = $stmt->fetchAll();
} catch (Throwable $e) {}

try {
    $db->query('SELECT id FROM patient_diagnoses LIMIT 1');
    $stmt = $db->prepare('SELECT * FROM patient_diagnoses WHERE patient_id = ? ORDER BY diagnosed_at DESC LIMIT 30');
    $stmt->execute([$patientId]);
    $diagnoses = $stmt->fetchAll();
} catch (Throwable $e) {}

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 20");
    $stmt->execute([$patientId]);
    $abnormalSummary = $stmt->fetchAll();
} catch (Throwable $e) {}

$noteTypeLabels = ['general'=>'عامة','lab_review'=>'مراجعة تحاليل','diagnosis'=>'تشخيص','follow_up'=>'متابعة','allergy'=>'حساسية','medication'=>'أدوية'];
$flagLabels = ['L'=>'منخفض','H'=>'مرتفع','C'=>'حرج'];

$age = null;
if (!empty($patient['date_of_birth'])) {
    $dob = date_create($patient['date_of_birth']);
    $now = date_create('today');
    if ($dob && $now) $age = date_diff($dob, $now)->y;
}
?>
<!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($patient['full_name'], ENT_QUOTES, 'UTF-8'); ?></title>
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Tajawal', sans-serif; padding: 20px; max-width: 900px; margin: 0 auto; }
        h1 { color: #0d9488; border-bottom: 2px solid #0d9488; padding-bottom: 8px; }
        h2 { color: #334155; margin-top: 24px; }
        table { width: 100%; border-collapse: collapse; margin: 12px 0; }
        th, td { border: 1px solid #e2e8f0; padding: 8px 12px; text-align: right; }
        th { background: #f1f5f9; }
        .meta { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; margin: 16px 0; }
        .meta-item { padding: 12px; background: #f8fafc; border-radius: 8px; }
        .meta-label { font-weight: bold; color: #64748b; font-size: 0.9rem; }
        .meta-value { font-size: 1.1rem; }
        .note-item { padding: 10px; margin: 8px 0; background: #f8fafc; border-right: 4px solid #0d9488; border-radius: 4px; }
        .diagnosis-item { padding: 8px; margin: 4px 0; }
        @media print { body { padding: 0; } .no-print { display: none; } }
        @media (max-width: 600px) { body { padding: 12px; } .meta { grid-template-columns: 1fr; } table { font-size: 0.85rem; } th, td { padding: 6px 8px; } }
    </style>
</head>
<body>
    <div class="no-print" style="margin-bottom:20px;">
        <button onclick="window.print()" style="padding:10px 20px;background:#0d9488;color:white;border:none;border-radius:8px;cursor:pointer;">🖨️ طباعة / حفظ PDF</button>
        <a href="doctor.php?page=results&patient_id=<?php echo (int)$patientId; ?>" style="margin-right:12px;">← رجوع</a>
    </div>

    <h1>الملف الطبي - <?php echo htmlspecialchars($patient['full_name'], ENT_QUOTES, 'UTF-8'); ?></h1>
    <p style="color:#64748b;">تم الإنشاء: <?php echo date('Y-m-d H:i'); ?> | Smart Doctor</p>

    <h2>البيانات الأساسية</h2>
    <div class="meta">
        <div class="meta-item"><span class="meta-label">الكود</span><div class="meta-value"><?php echo htmlspecialchars($patient['patient_code'], ENT_QUOTES, 'UTF-8'); ?></div></div>
        <div class="meta-item"><span class="meta-label">الجنس</span><div class="meta-value"><?php echo ($patient['gender'] ?? '') === 'M' ? 'ذكر' : (($patient['gender'] ?? '') === 'F' ? 'أنثى' : '-'); ?></div></div>
        <div class="meta-item"><span class="meta-label">العمر</span><div class="meta-value"><?php echo $age !== null ? $age . ' سنة' : '-'; ?></div></div>
        <div class="meta-item"><span class="meta-label">الهاتف</span><div class="meta-value"><?php echo htmlspecialchars($patient['phone'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div></div>
        <div class="meta-item"><span class="meta-label">تاريخ الميلاد</span><div class="meta-value"><?php echo !empty($patient['date_of_birth']) ? date('Y-m-d', strtotime($patient['date_of_birth'])) : '-'; ?></div></div>
    </div>

    <?php if (!empty($diagnoses)): ?>
    <h2>التصنيفات التشخيصية</h2>
    <ul>
        <?php foreach ($diagnoses as $d): ?>
        <li class="diagnosis-item"><strong><?php echo htmlspecialchars($d['diagnosis_name'], ENT_QUOTES, 'UTF-8'); ?></strong><?php if (!empty($d['diagnosis_code'])): ?> (<?php echo htmlspecialchars($d['diagnosis_code'], ENT_QUOTES, 'UTF-8'); ?>)<?php endif; ?> - <?php echo date('Y-m-d', strtotime($d['diagnosed_at'] ?? $d['created_at'])); ?></li>
        <?php endforeach; ?>
    </ul>
    <?php endif; ?>

    <?php if (!empty($abnormalSummary)): ?>
    <h2>ملخص النتائج غير الطبيعية</h2>
    <table>
        <thead><tr><th>الفحص</th><th>النتيجة</th><th>الحالة</th><th>التاريخ</th></tr></thead>
        <tbody>
        <?php foreach ($abnormalSummary as $s): ?>
        <tr><td><?php echo htmlspecialchars($s['test_name'], ENT_QUOTES, 'UTF-8'); ?></td><td><?php echo htmlspecialchars($s['result_value'], ENT_QUOTES, 'UTF-8'); ?> <?php echo htmlspecialchars($s['unit'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td><td><?php echo $flagLabels[$s['flag'] ?? ''] ?? '-'; ?></td><td><?php echo date('Y-m-d', strtotime($s['order_date'])); ?></td></tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <?php if (!empty($medicalNotes)): ?>
    <h2>الملاحظات الطبية</h2>
    <?php foreach ($medicalNotes as $n): ?>
    <div class="note-item">
        <strong><?php echo $noteTypeLabels[$n['note_type']] ?? $n['note_type']; ?></strong> - <?php echo date('Y-m-d H:i', strtotime($n['created_at'])); ?><br>
        <?php echo nl2br(htmlspecialchars($n['content'], ENT_QUOTES, 'UTF-8')); ?>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>

    <h2>سجل الطلبات (<?php echo count($orders); ?>)</h2>
    <table>
        <thead><tr><th>رقم الطلب</th><th>التاريخ</th><th>الحالة</th></tr></thead>
        <tbody>
        <?php foreach (array_slice($orders, 0, 30) as $o): ?>
        <tr><td><?php echo htmlspecialchars($o['order_number'], ENT_QUOTES, 'UTF-8'); ?></td><td><?php echo date('Y-m-d', strtotime($o['order_date'])); ?></td><td><?php echo htmlspecialchars($o['status'], ENT_QUOTES, 'UTF-8'); ?></td></tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <p style="margin-top:24px;color:#94a3b8;font-size:0.9rem;">تم إنشاء هذا التقرير بواسطة Smart Doctor - بوابة الأطباء</p>
</body>
</html>
