<?php
/**
 * مقارنة نتائج فحص مع الزمن - للمريض
 */
require_once __DIR__ . '/_result_helpers.php';
$patientId = (int)($_GET['patient_id'] ?? 0);
$testId = (int)($_GET['test_id'] ?? 0);

$patient = null;
$testsWithResults = [];
$trendData = [];

if ($patientId > 0) {
    try {
        $stmt = $db->prepare("SELECT p.* FROM patients p JOIN lab_orders o ON o.patient_id = p.id WHERE p.id = ? $tenantCond $doctorCond LIMIT 1");
        $stmt->execute([$patientId]);
        $patient = $stmt->fetch();

        if ($patient) {
            $stmt = $db->prepare("SELECT DISTINCT t.id, t.name, t.unit, t.reference_range
                                  FROM order_items oi
                                  JOIN lab_orders o ON o.id = oi.order_id
                                  JOIN tests t ON t.id = oi.test_id
                                  LEFT JOIN results r ON r.order_item_id = oi.id
                                  WHERE o.patient_id = ? AND oi.test_id IS NOT NULL AND r.result_value IS NOT NULL AND r.result_value != ''
                                  $tenantCond $doctorCond
                                  ORDER BY t.name");
            $stmt->execute([$patientId]);
            $testsWithResults = $stmt->fetchAll();

            if ($testId > 0) {
                $stmt = $db->prepare("SELECT o.order_date, r.result_value, r.flag, o.order_number
                                     FROM order_items oi
                                     JOIN lab_orders o ON o.id = oi.order_id
                                     JOIN results r ON r.order_item_id = oi.id
                                     WHERE o.patient_id = ? AND oi.test_id = ?
                                     $tenantCond $doctorCond
                                     ORDER BY o.order_date ASC");
                $stmt->execute([$patientId, $testId]);
                $trendData = $stmt->fetchAll();
            }
        }
    } catch (Throwable $e) {}
}

$selectedTest = null;
if ($testId > 0) {
    foreach ($testsWithResults as $t) {
        if ((int)$t['id'] === $testId) { $selectedTest = $t; break; }
    }
}

if (isset($_GET['export']) && $_GET['export'] === 'csv' && $selectedTest && !empty($trendData)) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="trend_' . preg_replace('/[^a-z0-9_-]/i', '_', $selectedTest['name']) . '_' . $patient['patient_code'] . '.csv"');
    echo "\xEF\xBB\xBF";
    echo "المريض," . $patient['full_name'] . "\n";
    echo "الفحص," . $selectedTest['name'] . "\n";
    echo "المدى المرجعي," . ($selectedTest['reference_range'] ?? '-') . "\n\n";
    echo "التاريخ,رقم الطلب,النتيجة,الحالة\n";
    foreach ($trendData as $d) {
        $fl = ['N'=>'طبيعي','L'=>'منخفض','H'=>'مرتفع','C'=>'حرج','P'=>'بانتظار المختبر'];
        $pend = doctor_order_result_is_pending($d);
        $st = $pend ? $fl['P'] : ($fl[$d['flag'] ?? ''] ?? '');
        echo date('Y-m-d H:i', strtotime($d['order_date'])) . ',"' . str_replace('"', '""', $d['order_number']) . '","' . str_replace('"', '""', $d['result_value'] ?? '') . '","' . $st . "\"\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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content">
    <?php
    $doctorPageTitle = '📈 مقارنة النتائج';
    $doctorPageDesc = $patient
        ? ('المريض: ' . $patient['full_name'] . ' — اختر فحصاً لعرض تطور القيم عبر الزمن وتصدير CSV.')
        : 'اختر مريضاً من القائمة أو من صفحة نتائج المريض لمقارنة فحص واحد عبر الطلبات.';
    $doctorPageLinks = [
        ['href' => 'doctor.php?page=patients', 'label' => '👥 المرضى'],
        ['href' => 'doctor.php?page=results' . ($patient ? '&patient_id=' . (int)$patient['id'] : ''), 'label' => '📋 النتائج'],
    ];
    include __DIR__ . '/_page_intro.php';
    ?>
    <?php if ($patient): ?>
    <div style="display:flex;justify-content:flex-end;margin-bottom:16px;">
        <a href="doctor.php?page=results&patient_id=<?php echo (int)$patient['id']; ?>" class="btn-secondary">← رجوع للمريض</a>
    </div>
    <?php endif; ?>

    <?php if (!$patient): ?>
    <div class="card">
        <p style="color:var(--text-muted);">اختر مريضاً لعرض مقارنة نتائج فحوصاته عبر الزمن.</p>
        <a href="doctor.php?page=patients" class="btn-primary" style="margin-top:12px;display:inline-block;">← اختر من قائمة المرضى</a>
    </div>
    <?php endif; ?>

    <?php if ($patient): ?>
    <div class="card" style="margin-bottom:20px;">
        <strong>المريض:</strong> <?php echo htmlspecialchars($patient['full_name'], ENT_QUOTES, 'UTF-8'); ?>
        | <strong>الرقم:</strong> <?php echo htmlspecialchars($patient['patient_code'], ENT_QUOTES, 'UTF-8'); ?>
    </div>

    <div class="card" style="margin-bottom:20px;">
        <h3 style="margin-top:0;">اختر الفحص للمقارنة</h3>
        <form method="get" style="display:flex;gap:12px;align-items:center;">
            <input type="hidden" name="page" value="trend">
            <input type="hidden" name="patient_id" value="<?php echo $patientId; ?>">
            <select name="test_id" onchange="this.form.submit()" style="min-width:250px;">
                <option value="">-- اختر الفحص --</option>
                <?php foreach ($testsWithResults as $t): ?>
                <option value="<?php echo (int)$t['id']; ?>" <?php echo $testId === (int)$t['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?>
                    <?php if (!empty($t['unit'])): ?>(<?php echo htmlspecialchars($t['unit'], ENT_QUOTES, 'UTF-8'); ?>)<?php endif; ?>
                </option>
                <?php endforeach; ?>
            </select>
            <button type="submit">عرض</button>
        </form>
    </div>

    <?php if ($selectedTest && !empty($trendData)): ?>
    <div class="card">
        <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;">
            <h3 style="margin-top:0;"><?php echo htmlspecialchars($selectedTest['name'], ENT_QUOTES, 'UTF-8'); ?></h3>
            <a href="doctor.php?page=trend&patient_id=<?php echo $patientId; ?>&test_id=<?php echo $testId; ?>&export=csv" class="btn-secondary">📥 تصدير CSV</a>
        </div>
        <?php if (!empty($selectedTest['reference_range'])): ?>
        <p style="color:var(--text-muted);margin-bottom:16px;">المدى المرجعي: <?php echo htmlspecialchars($selectedTest['reference_range'], ENT_QUOTES, 'UTF-8'); ?></p>
        <?php endif; ?>
        <div style="height:300px;">
            <canvas id="trendChart"></canvas>
        </div>
        <div class="table-wrapper" style="margin-top:20px;">
            <table class="table">
                <thead>
                    <tr>
                        <th>التاريخ</th>
                        <th>رقم الطلب</th>
                        <th>النتيجة</th>
                        <th>الحالة</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($trendData as $d): ?>
                <tr>
                    <td><?php echo date('Y-m-d H:i', strtotime($d['order_date'])); ?></td>
                    <td><?php echo htmlspecialchars($d['order_number'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($d['result_value'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td>
                        <?php
                        $fl = ['N'=>'طبيعي','L'=>'منخفض','H'=>'مرتفع','C'=>'حرج','P'=>'بانتظار المختبر'];
                        $fc = ['N'=>'#22c55e','L'=>'#f59e0b','H'=>'#ef4444','C'=>'#dc2626','P'=>'#64748b'];
                        $pend = doctor_order_result_is_pending($d);
                        $f = $pend ? 'P' : ($d['flag'] ?? 'N');
                        ?>
                        <span style="padding:4px 8px;background:<?php echo $fc[$f] ?? '#999'; ?>;color:white;border-radius:4px;font-size:12px;"><?php echo htmlspecialchars($fl[$f] ?? $f, ENT_QUOTES, 'UTF-8'); ?></span>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <script>
    (function(){
        var ctx = document.getElementById('trendChart');
        if (ctx) {
            var labels = <?php echo json_encode(array_map(function($d){ return date('Y-m-d', strtotime($d['order_date'])); }, $trendData)); ?>;
            var values = <?php echo json_encode(array_map(function($d){ return is_numeric($d['result_value']) ? (float)$d['result_value'] : null; }, $trendData)); ?>;
            var numericValues = values.filter(function(v){ return v !== null; });
            var refRange = '<?php echo addslashes($selectedTest['reference_range'] ?? ''); ?>';
            var refMin = null, refMax = null;
            if (refRange && /[\d.-]+/.test(refRange)) {
                var m = refRange.match(/([\d.]+)\s*[-–]\s*([\d.]+)/);
                if (m) { refMin = parseFloat(m[1]); refMax = parseFloat(m[2]); }
                else { var single = refRange.match(/([\d.]+)/); if (single) refMax = parseFloat(single[1]); }
            }
            var datasets = [{
                label: '<?php echo addslashes($selectedTest['name']); ?>',
                data: values,
                borderColor: '#0d9488',
                backgroundColor: 'rgba(13, 148, 136, 0.1)',
                fill: true,
                tension: 0.3
            }];
            if (refMin !== null && !isNaN(refMin)) {
                datasets.push({ label: 'الحد الأدنى', data: labels.map(function(){ return refMin; }), borderColor: '#f59e0b', borderDash: [5,5], fill: false, pointRadius: 0 });
            }
            if (refMax !== null && !isNaN(refMax) && refMax !== refMin) {
                datasets.push({ label: 'الحد الأعلى', data: labels.map(function(){ return refMax; }), borderColor: '#ef4444', borderDash: [5,5], fill: false, pointRadius: 0 });
            }
            new Chart(ctx, {
                type: 'line',
                data: { labels: labels, datasets: datasets },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: { beginAtZero: numericValues.length && Math.min.apply(null, numericValues) >= 0 }
                    }
                }
            });
        }
    })();
    </script>
    <?php elseif ($testId > 0 && empty($trendData)): ?>
    <div class="card">
        <p style="color:var(--text-muted);">لا توجد بيانات كافية لهذا الفحص.</p>
    </div>
    <?php endif; ?>

    <?php if (empty($testsWithResults)): ?>
    <div class="card">
        <p style="color:var(--text-muted);">لا توجد فحوصات مكتملة لهذا المريض.</p>
    </div>
    <?php endif; ?>
    <?php endif; ?>
</main>
</body>
</html>
