<?php

use App\Core\WhatsApp;
use App\Core\Tenant;
use App\Core\ResultValidator;
use App\Core\Auth;

$action = $_GET['action'] ?? 'index';

try {
    $db->exec("ALTER TABLE lab_orders ADD COLUMN completed_at DATETIME NULL");
} catch (Throwable $e) {
}

if (!($auth instanceof Auth) || !$auth->can('results.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى هذه الصفحة';
    return;
}
$tenantId = Tenant::id();
$tenantOrderAnd = '';
$tenantOrderParams = [];
$testTenantAnd = '';
$testTenantParams = [];
try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantOrderAnd = ' AND o.tenant_id = :tid'; $tenantOrderParams['tid'] = $tenantId; } catch (Throwable $e) {}
try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $testTenantAnd = ' AND t.tenant_id = :ttid'; $testTenantParams['ttid'] = $tenantId; } catch (Throwable $e) {}

if ($action === 'enter' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || (!$auth->can('results.edit') && !$auth->can('results.validate'))) {
        http_response_code(403);
        echo 'غير مسموح باعتماد النتائج';
        return;
    }
    $itemId = (int)($_POST['item_id'] ?? 0);
    $value = trim($_POST['result_value'] ?? '');
    $flag = $_POST['flag'] ?? null;
    $notes = trim($_POST['notes'] ?? '');
    $confirmCritical = isset($_POST['confirm_critical']);

    if ($itemId > 0) {
        try {
            $db->beginTransaction();

            $stmt = $db->prepare(
                'SELECT oi.order_id, o.patient_id
                 FROM order_items oi
                 JOIN lab_orders o ON o.id = oi.order_id
                 WHERE oi.id = :id' . $tenantOrderAnd . '
                 FOR UPDATE'
            );
            $stmt->execute(array_merge(['id' => $itemId], $tenantOrderParams));
            $row = $stmt->fetch();

            if ($row) {
                $orderId = (int)$row['order_id'];
                $patientId = (int)$row['patient_id'];

                $stmt = $db->prepare(
                    'SELECT t.reference_range, t.critical_value_min, t.critical_value_max, t.id AS test_id,
                            p.date_of_birth, p.gender
                     FROM order_items oi
                     JOIN lab_orders o ON o.id = oi.order_id
                     JOIN patients p ON p.id = o.patient_id
                     JOIN tests t ON t.id = oi.test_id
                     WHERE oi.id = :id' . $tenantOrderAnd . $testTenantAnd
                );
                $stmt->execute(array_merge(['id' => $itemId], $tenantOrderParams, $testTenantParams));
                $testRow = $stmt->fetch();
                $refRange = $testRow['reference_range'] ?? null;
                $criticalMin = isset($testRow['critical_value_min']) ? (float)$testRow['critical_value_min'] : null;
                $criticalMax = isset($testRow['critical_value_max']) ? (float)$testRow['critical_value_max'] : null;
                $ageYears = null;
                if (!empty($testRow['date_of_birth'])) {
                    $ageYears = (time() - strtotime($testRow['date_of_birth'])) / (365.25 * 24 * 3600);
                }
                $refFromTable = ResultValidator::getReferenceRangeForPatient($db, (int)$testRow['test_id'], $ageYears, $testRow['gender'] ?? null);
                if ($refFromTable['reference_range'] !== null) {
                    $refRange = $refFromTable['reference_range'];
                    $criticalMin = $refFromTable['critical_min'] ?? $criticalMin;
                    $criticalMax = $refFromTable['critical_max'] ?? $criticalMax;
                }

                $resultStatus = ResultValidator::checkValue($value, $refRange, $criticalMin, $criticalMax);
                if ($resultStatus === 'critical' && !$confirmCritical) {
                    $_SESSION['result_enter_error'] = 'قيمة حرجة! يرجى التأكيد قبل الحفظ.';
                    $_SESSION['result_enter_data'] = ['item_id' => $itemId, 'value' => $value, 'flag' => $flag, 'notes' => $notes];
                    header('Location: index.php?page=results&action=enter&item_id=' . $itemId . '&critical=1');
                    exit;
                }

                $stmt = $db->prepare('SELECT id FROM results WHERE order_item_id = :id');
                $stmt->execute(['id' => $itemId]);
                $existing = $stmt->fetch();

                $techName = $_SESSION['user_name'] ?? '';
                try {
                    $db->query('SELECT tech_name FROM results LIMIT 1');
                } catch (Throwable $e) { $techName = ''; }
                if ($existing) {
                    $stmt = $db->prepare(
                        'UPDATE results SET result_value = :val, flag = :flag, notes = :notes, result_date = NOW(), validated_at = NOW()' . ($techName !== '' ? ', tech_name = :tech' : '') . ' WHERE order_item_id = :id'
                    );
                    $params = ['id' => $itemId, 'val' => $value !== '' ? $value : null, 'flag' => $flag ?: null, 'notes' => $notes !== '' ? $notes : null];
                    if ($techName !== '') $params['tech'] = $techName;
                    $stmt->execute($params);
                } else {
                    $stmt = $db->prepare(
                        'INSERT INTO results (order_item_id, result_value, flag, notes, result_date, validated_at' . ($techName !== '' ? ', tech_name' : '') . ') VALUES (:id, :val, :flag, :notes, NOW(), NOW()' . ($techName !== '' ? ', :tech' : '') . ')'
                    );
                    $params = ['id' => $itemId, 'val' => $value !== '' ? $value : null, 'flag' => $flag ?: null, 'notes' => $notes !== '' ? $notes : null];
                    if ($techName !== '') $params['tech'] = $techName;
                    $stmt->execute($params);
                }

                $stmt = $db->prepare(
                    "UPDATE order_items
                     SET status = 'validated'
                     WHERE id = :id"
                );
                $stmt->execute(['id' => $itemId]);

                // ─── قواعد الانعكاس: إذا تحقق الشرط → إضافة فحص تلقائياً ─────────────────
                try {
                    $stmt = $db->prepare('SELECT oi.test_id, oi.sample_id FROM order_items oi WHERE oi.id = ?');
                    $stmt->execute([$itemId]);
                    $oiRow = $stmt->fetch();
                    if ($oiRow) {
                        $triggerTestId = (int)$oiRow['test_id'];
                        $sampleId = !empty($oiRow['sample_id']) ? (int)$oiRow['sample_id'] : null;
                        $refRulesSql = 'SELECT id, add_test_id, condition_type, condition_value FROM reflex_rules WHERE trigger_test_id = ? AND is_active = 1';
                        $refRulesParams = [$triggerTestId];
                        try {
                            $db->query('SELECT tenant_id FROM reflex_rules LIMIT 1');
                            $refRulesSql .= ' AND tenant_id = ?';
                            $refRulesParams[] = (int)\App\Core\Tenant::id();
                        } catch (Throwable $e) {}
                        $refRules = $db->prepare($refRulesSql);
                        $refRules->execute($refRulesParams);
                        foreach ($refRules->fetchAll() as $rule) {
                            $condType = $rule['condition_type'] ?? '';
                            $condVal = $rule['condition_value'] ?? '';
                            $addTestId = (int)$rule['add_test_id'];
                            $matches = false;
                            $numVal = null;
                            if (is_numeric(str_replace(',', '.', trim($value ?? '')))) {
                                $numVal = (float)str_replace(',', '.', trim($value));
                            }
                            if ($condType === 'below' && $numVal !== null && $condVal !== '' && is_numeric($condVal) && $numVal < (float)$condVal) $matches = true;
                            elseif ($condType === 'above' && $numVal !== null && $condVal !== '' && is_numeric($condVal) && $numVal > (float)$condVal) $matches = true;
                            elseif ($condType === 'equals' && (string)trim($value ?? '') === (string)trim($condVal)) $matches = true;
                            elseif ($condType === 'not_equals' && (string)trim($value ?? '') !== (string)trim($condVal) && trim($value ?? '') !== '') $matches = true;
                            if ($matches && $addTestId > 0) {
                                $exists = $db->prepare('SELECT 1 FROM order_items WHERE order_id = ? AND test_id = ? LIMIT 1');
                                $exists->execute([$orderId, $addTestId]);
                                if (!$exists->fetch()) {
                                    $priceStmt = $db->prepare('SELECT default_price FROM tests WHERE id = ? LIMIT 1');
                                    $priceStmt->execute([$addTestId]);
                                    $priceRow = $priceStmt->fetch();
                                    $reflexPrice = isset($priceRow['default_price']) ? (float)$priceRow['default_price'] : 0;
                                    try {
                                        $ins = $db->prepare('INSERT INTO order_items (order_id, test_id, panel_id, sample_id, price, status) VALUES (?, ?, NULL, ?, ?, ?)');
                                        $ins->execute([$orderId, $addTestId, $sampleId ?: null, $reflexPrice, 'pending']);
                                    } catch (Throwable $ex) {
                                        $ins = $db->prepare('INSERT INTO order_items (order_id, test_id, price, status) VALUES (?, ?, ?, ?)');
                                        $ins->execute([$orderId, $addTestId, $reflexPrice, 'pending']);
                                    }
                                    if (isset($auditLog)) {
                                        $auditLog->log('reflex_test_added', 'order_item', (int)$db->lastInsertId(), null, json_encode(['trigger_test_id' => $triggerTestId, 'add_test_id' => $addTestId, 'rule_id' => $rule['id'], 'value' => $value], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                                    }
                                    $_SESSION['reflex_added'] = ($_SESSION['reflex_added'] ?? 0) + 1;
                                }
                            }
                        }
                    }
                } catch (Throwable $e) {}

                $stmt = $db->prepare(
                    "SELECT COUNT(*) AS total,
                            SUM(CASE WHEN status = 'validated' THEN 1 ELSE 0 END) AS done
                     FROM order_items
                     WHERE order_id = :order_id"
                );
                $stmt->execute(['order_id' => $orderId]);
                $agg = $stmt->fetch();

                if ($agg && (int)$agg['total'] > 0 && (int)$agg['total'] === (int)$agg['done']) {
                    $stmt = $db->prepare(
                        "UPDATE lab_orders
                         SET status = 'completed',
                             completed_at = CASE WHEN completed_at IS NULL THEN NOW() ELSE completed_at END
                         WHERE id = :id"
                    );
                    $stmt->execute(['id' => $orderId]);

                    // إرسال واتساب/SMS فقط عند اكتمال جميع النتائج
                    $whatsapp = new WhatsApp($db, $config['whatsapp'] ?? []);
                    $whatsapp->createNotificationForOrder($orderId, $patientId);
                    try {
                        $smsConfig = ['enabled' => false, 'provider' => 'unifonic'];
                        $stmt = $db->prepare("SELECT setting_key, setting_value FROM settings WHERE tenant_id = ? AND setting_key LIKE 'sms_%'");
                        $stmt->execute([\App\Core\Tenant::id()]);
                        foreach ($stmt->fetchAll() as $r) {
                            $k = str_replace('sms_', '', $r['setting_key']);
                            $smsConfig[$k] = $r['setting_value'] ?? '';
                        }
                        $smsConfig['enabled'] = ($smsConfig['enabled'] ?? '0') === '1';
                        $smsConfig['app_sid'] = $smsConfig['app_sid'] ?? $smsConfig['account_sid'] ?? '';
                        $smsConfig['sender_id'] = $smsConfig['sender_id'] ?? $smsConfig['from_number'] ?? '';
                        $sms = new \App\Core\SMS($db, $smsConfig, (int)\App\Core\Tenant::id());
                        if ($sms->isEnabled()) $sms->sendResultsReady($orderId, $patientId);
                    } catch (Throwable $e) {}
                }

                $db->commit();
                if (isset($auditLog)) {
                    $auditLog->log(
                        'result_validated',
                        'order_item',
                        $itemId,
                        null,
                        json_encode([
                            'order_id' => $orderId,
                            'patient_id' => $patientId,
                            'value' => $value,
                            'flag' => $flag,
                            'notes' => $notes
                        ], JSON_UNESCAPED_UNICODE),
                        $_SESSION['user_id'] ?? null
                    );
                }
            } else {
                $db->rollBack();
                $_SESSION['result_save_error'] = 'العنصر غير موجود أو غير صالح.';
            }
        } catch (Throwable $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $_SESSION['result_save_error'] = 'حدث خطأ أثناء الحفظ: ' . $e->getMessage();
        }
    } else {
        $_SESSION['result_save_error'] = 'معرف العنصر غير صالح.';
    }

    $retOrderId = isset($orderId) ? $orderId : (int)($_POST['return_order_id'] ?? 0);
    if (!isset($_SESSION['result_save_error'])) {
        $reflexCount = $_SESSION['reflex_added'] ?? 0;
        unset($_SESSION['reflex_added']);
        $_SESSION['result_save_ok'] = 'تم حفظ النتيجة بنجاح.' . ($reflexCount > 0 ? ' تم إضافة ' . $reflexCount . ' فحص انعكاسي تلقائياً.' : '');
        header('Location: index.php?page=results' . ($retOrderId ? '&order_id=' . $retOrderId : ''));
    } else {
        // عند الخطأ: الرجوع لنموذج الإدخال إن وُجد item_id صالح
        if ($itemId > 0) {
            header('Location: index.php?page=results&action=enter&item_id=' . $itemId);
        } else {
            header('Location: index.php?page=results' . ($retOrderId ? '&order_id=' . $retOrderId : ''));
        }
    }
    exit;
}

if ($action === 'enter') {
    if (!($auth instanceof Auth) || (!$auth->can('results.edit') && !$auth->can('results.validate'))) {
        http_response_code(403);
        echo 'غير مسموح بإدخال النتائج';
        return;
    }
    $itemId = (int)($_GET['item_id'] ?? 0);
    $item = null;
    $existingResult = null;

    if ($itemId > 0) {
        try {
            $stmt = $db->prepare(
                'SELECT oi.id, oi.order_id, o.order_number, p.full_name AS patient_name, p.phone, p.date_of_birth, p.gender,
                        t.name AS test_name, t.test_code, t.unit, t.reference_range, t.id AS test_id
                 FROM order_items oi
                 JOIN lab_orders o ON o.id = oi.order_id
                 JOIN patients p ON p.id = o.patient_id
                 JOIN tests t ON t.id = oi.test_id
                 WHERE oi.id = :id' . $tenantOrderAnd . $testTenantAnd
            );
            $stmt->execute(array_merge(['id' => $itemId], $tenantOrderParams, $testTenantParams));
            $item = $stmt->fetch();

            if ($item) {
                $ageYears = null;
                if (!empty($item['date_of_birth'])) {
                    $ageYears = (time() - strtotime($item['date_of_birth'])) / (365.25 * 24 * 3600);
                }
                $refFromTable = ResultValidator::getReferenceRangeForPatient($db, (int)$item['test_id'], $ageYears, $item['gender'] ?? null);
                if ($refFromTable['reference_range'] !== null) {
                    $item['reference_range'] = $refFromTable['reference_range'];
                }
                $stmt = $db->prepare(
                    'SELECT result_value, flag, notes
                     FROM results
                     WHERE order_item_id = :id'
                );
                $stmt->execute(['id' => $itemId]);
                $existingResult = $stmt->fetch();
            }
        } catch (Throwable $e) {
        }
    }

    if (!$item) {
        echo '<div class="page-header"><h1>نتائج الفحوصات</h1><a href="index.php?page=results" class="btn-secondary">← رجوع</a></div>';
        echo '<div class="alert alert-danger">العنصر غير موجود</div>';
        return;
    }

    $isCritical = isset($_GET['critical']);
    $savedData = $_SESSION['result_enter_data'] ?? [];
    if ($isCritical && !empty($savedData) && (int)($savedData['item_id'] ?? 0) === $itemId) {
        $existingResult = array_merge($existingResult ?? [], ['result_value' => $savedData['value'] ?? '', 'flag' => $savedData['flag'] ?? '', 'notes' => $savedData['notes'] ?? '']);
    }
    ?>
    <div class="page-header">
        <h1>إدخال نتيجة فحص</h1>
        <a href="index.php?page=results&order_id=<?php echo (int)$item['order_id']; ?>" class="btn-secondary">← رجوع للطلب</a>
    </div>
    <?php if (!empty($_SESSION['result_save_error'])): ?>
    <div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['result_save_error'], ENT_QUOTES, 'UTF-8'); ?></div>
    <?php unset($_SESSION['result_save_error']); endif; ?>
    <?php if ($isCritical && !empty($_SESSION['result_enter_error'])): ?>
    <div class="alert alert-danger critical-value-alert" style="border:3px solid #dc2626;background:#fef2f2;padding:20px;border-radius:12px;margin:16px 0;">
        <div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;">
            <span style="font-size:2rem;">⚠️</span>
            <div>
                <strong style="font-size:1.2em;color:#991b1b;">تنبيه: قيمة حرجة</strong>
                <p style="margin:8px 0 0;color:#b91c1c;"><?php echo htmlspecialchars($_SESSION['result_enter_error'], ENT_QUOTES, 'UTF-8'); ?></p>
            </div>
        </div>
        <p style="margin:12px 0;color:#7f1d1d;">يرجى التحقق من القيمة قبل الحفظ. إذا كانت صحيحة، اضغط تأكيد.</p>
        <form method="post" action="index.php?page=results&action=enter" style="margin-top:16px;">
            <input type="hidden" name="item_id" value="<?php echo (int)$itemId; ?>">
            <input type="hidden" name="result_value" value="<?php echo htmlspecialchars($savedData['value'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="flag" value="<?php echo htmlspecialchars($savedData['flag'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="notes" value="<?php echo htmlspecialchars($savedData['notes'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="confirm_critical" value="1">
            <input type="hidden" name="return_order_id" value="<?php echo (int)$item['order_id']; ?>">
            <button type="submit" class="btn-primary" style="background:#dc2626;border-color:#b91c1c;">تأكيد وحفظ رغم القيمة الحرجة</button>
            <a href="index.php?page=results&order_id=<?php echo (int)$item['order_id']; ?>" class="btn-secondary" style="margin-right:8px;">إلغاء</a>
        </form>
    </div>
    <?php endif; ?>
    <div class="section-card results-enter-card">
        <div class="results-enter-info">
            <div class="results-enter-info-row">
                <span><strong>رقم الطلب:</strong></span>
                <span><code><?php echo htmlspecialchars($item['order_number'], ENT_QUOTES, 'UTF-8'); ?></code></span>
            </div>
            <div class="results-enter-info-row">
                <span><strong>المريض:</strong></span>
                <span><?php echo htmlspecialchars($item['patient_name'], ENT_QUOTES, 'UTF-8'); ?></span>
            </div>
            <div class="results-enter-info-row">
                <span><strong>الفحص:</strong></span>
                <span><?php echo htmlspecialchars($item['test_name'], ENT_QUOTES, 'UTF-8'); ?></span>
            </div>
            <div class="results-enter-info-row">
                <span><strong>الوحدة:</strong></span>
                <span><?php echo htmlspecialchars($item['unit'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></span>
            </div>
            <div class="results-enter-info-row">
                <span><strong>المدى المرجعي:</strong></span>
                <span><?php echo htmlspecialchars($item['reference_range'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></span>
            </div>
        </div>
        <form method="post" action="index.php?page=results&action=enter" class="form-grid">
            <input type="hidden" name="item_id" value="<?php echo (int)$itemId; ?>">
            <input type="hidden" name="return_order_id" value="<?php echo (int)$item['order_id']; ?>">
            <div class="form-group">
                <label>النتيجة</label>
                <input type="text" name="result_value" id="result_value" required value="<?php echo htmlspecialchars($existingResult['result_value'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="أدخل القيمة" style="font-size:1.1rem;padding:12px;">
                <?php
                $tc = strtoupper($item['test_code'] ?? '');
                if (strpos($tc, 'BMI') !== false): ?>
                <small class="form-hint"><button type="button" class="btn-link" onclick="var w=prompt('الوزن (كغم)'); var h=prompt('الطول (سم)'); if(w&&h){ document.getElementById('result_value').value=(parseFloat(w)/((parseFloat(h)/100)**2)).toFixed(1); }">حساب BMI</button></small>
                <?php elseif (strpos($tc, 'LDL') !== false): ?>
                <small class="form-hint"><button type="button" class="btn-link" onclick="var c=prompt('الكوليسترول الكلي'); var h=prompt('HDL'); var t=prompt('TG'); if(c&&h&&t){ document.getElementById('result_value').value=Math.round(parseFloat(c)-parseFloat(h)-parseFloat(t)/5); }">حساب LDL</button></small>
                <?php endif; ?>
            </div>
            <div class="form-group">
                <label>الحالة</label>
                <select name="flag" style="padding:12px;">
                    <option value="">طبيعي</option>
                    <option value="L" <?php echo isset($existingResult['flag']) && $existingResult['flag'] === 'L' ? 'selected' : ''; ?>>منخفض</option>
                    <option value="H" <?php echo isset($existingResult['flag']) && $existingResult['flag'] === 'H' ? 'selected' : ''; ?>>مرتفع</option>
                    <option value="C" <?php echo isset($existingResult['flag']) && $existingResult['flag'] === 'C' ? 'selected' : ''; ?>>حرج</option>
                </select>
            </div>
            <div class="form-group full-width">
                <label>ملاحظات</label>
                <textarea name="notes" id="result_notes" rows="3" placeholder="ملاحظات اختيارية"><?php echo htmlspecialchars($existingResult['notes'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                <?php
                $resultTemplates = [];
                try {
                    $db->query('SELECT id FROM result_summary_templates LIMIT 1');
                    $tid = \App\Core\Tenant::id();
                    $stmt = $db->prepare('SELECT id, title, template_text FROM result_summary_templates WHERE tenant_id = ? OR tenant_id IS NULL ORDER BY category, title');
                    $stmt->execute([$tid]);
                    $resultTemplates = $stmt->fetchAll();
                } catch (Throwable $e) {}
                if (!empty($resultTemplates)): ?>
                <div style="margin-top:8px;display:flex;flex-wrap:wrap;gap:6px;">
                    <span style="font-size:0.85rem;color:var(--text-muted);align-self:center;">إدراج قالب:</span>
                    <?php foreach ($resultTemplates as $tmpl): ?>
                    <button type="button" class="btn-secondary result-template-btn" style="padding:4px 10px;font-size:0.85rem;" data-text="<?php echo htmlspecialchars(str_replace(["\r\n","\r","\n"], ["\n","\n","\n"], $tmpl['template_text']), ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($tmpl['title'], ENT_QUOTES, 'UTF-8'); ?></button>
                    <?php endforeach; ?>
                </div>
                <script>
                document.querySelectorAll('.result-template-btn').forEach(function(btn){
                    btn.addEventListener('click', function(){
                        var ta = document.getElementById('result_notes');
                        var t = this.getAttribute('data-text') || '';
                        ta.value = ta.value ? ta.value + '\n' + t : t;
                    });
                });
                </script>
                <?php endif; ?>
            </div>
            <div class="form-actions full-width">
                <button type="submit" class="btn-primary">حفظ النتيجة</button>
                <a href="index.php?page=results&order_id=<?php echo (int)$item['order_id']; ?>" class="btn-secondary">إلغاء</a>
            </div>
        </form>
    </div>
    <?php
    unset($_SESSION['result_enter_error'], $_SESSION['result_enter_data']);
    return;
}

$items = [];
$userBranchId = isset($auth) && $auth instanceof \App\Core\Auth ? $auth->branchId() : null;
$resultSearch = trim($_GET['q'] ?? '');
$resultStatusFilter = trim($_GET['status'] ?? '');
$resultTenantId = $tenantId;

// إنشاء رابط مشاركة للتقرير (لإرساله للطبيب)
if ($action === 'create_share' && ($auth->can('results.print') || $auth->can('results.view')) && !$auth->maskResults()) {
    $shareOrderId = (int)($_GET['order_id'] ?? $_POST['order_id'] ?? 0);
    if ($shareOrderId > 0) {
        try {
            try {
                $db->query('SELECT tenant_id FROM lab_orders LIMIT 1');
                $stmt = $db->prepare('SELECT id FROM lab_orders WHERE id = ? AND tenant_id = ?');
                $stmt->execute([$shareOrderId, $tenantId]);
                if (!$stmt->fetch()) {
                    header('Location: index.php?page=results' . ($shareOrderId ? '&order_id=' . $shareOrderId : ''));
                    exit;
                }
            } catch (Throwable $e) {}
            $db->query('SELECT id FROM report_share_links LIMIT 1');
            $token = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', strtotime('+7 days'));
            $stmt = $db->prepare('INSERT INTO report_share_links (order_id, token, expires_at) VALUES (?, ?, ?)');
            $stmt->execute([$shareOrderId, $token, $expires]);
            $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
            $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
            if ($scriptDir === '/') $scriptDir = '';
            $shareUrl = $baseUrl . $scriptDir . '/index.php?page=print_result&share_token=' . urlencode($token);
            $_SESSION['result_share_url'] = $shareUrl;
        } catch (Throwable $e) {}
    }
    header('Location: index.php?page=results' . ($shareOrderId ? '&order_id=' . $shareOrderId : ''));
    exit;
}

// اعتماد نهائي للطباعة
if ($action === 'approve' && $_SERVER['REQUEST_METHOD'] === 'POST' && $auth->can('results.validate')) {
    $approveOrderId = (int)($_POST['order_id'] ?? 0);
    if ($approveOrderId > 0) {
        try {
            $db->query('SELECT tenant_id FROM lab_orders LIMIT 1');
            $stmt = $db->prepare('SELECT id FROM lab_orders WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$approveOrderId, $tenantId]);
            if (!$stmt->fetch()) {
                header('Location: index.php?page=results' . ($approveOrderId ? '&order_id=' . $approveOrderId : ''));
                exit;
            }
        } catch (Throwable $e) {}
        $stmt = $db->prepare('SELECT COUNT(*) AS total, SUM(CASE WHEN status = "validated" THEN 1 ELSE 0 END) AS done FROM order_items WHERE order_id = ?');
        $stmt->execute([$approveOrderId]);
        $agg = $stmt->fetch();
        if ($agg && (int)$agg['total'] > 0 && (int)$agg['total'] === (int)$agg['done']) {
            try {
                $db->query('SELECT approved_at FROM lab_orders LIMIT 1');
                $oNum = '';
                $orderTenantAndPos = '';
                $orderParams = [$approveOrderId];
                try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $orderTenantAndPos = ' AND tenant_id = ?'; $orderParams[] = $tenantId; } catch (Throwable $e) {}
                $s2 = $db->prepare('SELECT order_number FROM lab_orders WHERE id = ?' . $orderTenantAndPos);
                $s2->execute($orderParams);
                if ($r = $s2->fetch()) $oNum = $r['order_number'] ?? '';
                $reportId = strtoupper(substr(md5($approveOrderId . $oNum . time()), 0, 12));
                $signature = ($_SESSION['user_name'] ?? 'مدير') . ' — ' . date('Y-m-d H:i:s');
                try {
                    $db->query('SELECT approved_signature FROM lab_orders LIMIT 1');
                    $stmt = $db->prepare('UPDATE lab_orders SET approved_at = NOW(), approved_by = ?, approved_signature = ?, report_id = ? WHERE id = ?' . $orderTenantAndPos);
                    $stmt->execute(array_merge([$_SESSION['user_id'] ?? null, $signature, $reportId, $approveOrderId], $orderTenantAndPos ? [$tenantId] : []));
                } catch (Throwable $ex) {
                    $stmt = $db->prepare('UPDATE lab_orders SET approved_at = NOW(), approved_by = ?, report_id = ? WHERE id = ?' . $orderTenantAndPos);
                    $stmt->execute(array_merge([$_SESSION['user_id'] ?? null, $reportId, $approveOrderId], $orderTenantAndPos ? [$tenantId] : []));
                }
                if (isset($auditLog)) $auditLog->log('order_approved', 'lab_order', $approveOrderId, null, json_encode(['report_id' => $reportId], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
            } catch (Throwable $e) {}
        }
    }
    header('Location: index.php?page=results' . ($approveOrderId ? '&order_id=' . $approveOrderId : ''));
    exit;
}

$resultTenantAnd = '';
try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $resultTenantAnd = ' AND o.tenant_id = ' . (int)$resultTenantId; } catch (Throwable $e) {}

// إحصائيات
$statsPending = $statsValidated = $statsTotal = 0;
try {
    $cntSql = 'SELECT
        COUNT(*) AS total,
        SUM(CASE WHEN oi.status IN ("pending","in_progress","result_entered") THEN 1 ELSE 0 END) AS pending,
        SUM(CASE WHEN oi.status = "validated" THEN 1 ELSE 0 END) AS validated
        FROM order_items oi JOIN lab_orders o ON o.id = oi.order_id WHERE 1=1' . $resultTenantAnd;
    if ($userBranchId !== null) $cntSql .= ' AND o.branch_id = ' . (int)$userBranchId;
    $stmt = $db->query($cntSql);
    $sr = $stmt->fetch();
    $statsTotal = (int)($sr['total'] ?? 0);
    $statsPending = (int)($sr['pending'] ?? 0);
    $statsValidated = (int)($sr['validated'] ?? 0);
} catch (Throwable $e) {}

$sql = "SELECT oi.id, o.id AS order_db_id, o.order_number, o.order_date, p.full_name AS patient_name,
               t.name AS test_name, oi.status, b.name AS branch_name, r.flag
        FROM order_items oi
        JOIN lab_orders o ON o.id = oi.order_id
        JOIN patients p ON p.id = o.patient_id
        JOIN tests t ON t.id = oi.test_id
        LEFT JOIN branches b ON b.id = o.branch_id
        LEFT JOIN results r ON r.order_item_id = oi.id
        WHERE oi.status IN ('pending','in_progress','validated')" . $resultTenantAnd;

$params = [];

if (!empty($_GET['order_id'])) {
    $sql .= " AND o.id = :order_id";
    $params['order_id'] = (int)$_GET['order_id'];
}
if ($userBranchId !== null) {
    $sql .= " AND o.branch_id = :user_branch";
    $params['user_branch'] = $userBranchId;
}
if ($resultSearch !== '') {
    $sql .= " AND (o.order_number LIKE :q OR p.full_name LIKE :q2 OR t.name LIKE :q3)";
    $params['q'] = '%' . $resultSearch . '%';
    $params['q2'] = '%' . $resultSearch . '%';
    $params['q3'] = '%' . $resultSearch . '%';
}
if ($resultStatusFilter !== '') {
    $sql .= " AND oi.status = :status_filter";
    $params['status_filter'] = $resultStatusFilter;
}
if ($testTenantAnd) {
    $sql .= $testTenantAnd;
    $params['ttid'] = $resultTenantId;
}

$resultPerPage = 30;
$resultPage = max(1, (int)($_GET['p'] ?? 1));
$resultOffset = ($resultPage - 1) * $resultPerPage;

$countSql = "SELECT COUNT(*) FROM order_items oi
    JOIN lab_orders o ON o.id = oi.order_id
    JOIN patients p ON p.id = o.patient_id
    JOIN tests t ON t.id = oi.test_id
    LEFT JOIN branches b ON b.id = o.branch_id
    WHERE oi.status IN ('pending','in_progress','validated')" . $resultTenantAnd;
if (!empty($_GET['order_id'])) $countSql .= " AND o.id = " . (int)$_GET['order_id'];
if ($userBranchId !== null) $countSql .= " AND o.branch_id = " . (int)$userBranchId;
if ($resultSearch !== '') {
    $countSql .= " AND (o.order_number LIKE " . $db->quote('%' . $resultSearch . '%') . " OR p.full_name LIKE " . $db->quote('%' . $resultSearch . '%') . " OR t.name LIKE " . $db->quote('%' . $resultSearch . '%') . ")";
}
if ($resultStatusFilter !== '') $countSql .= " AND oi.status = " . $db->quote($resultStatusFilter);
if ($testTenantAnd) $countSql .= " AND t.tenant_id = " . (int)$resultTenantId;
try {
    $resultTotal = (int)($db->query($countSql)->fetchColumn() ?? 0);
} catch (Throwable $e) {
    $resultTotal = 0;
}
$resultTotalPages = $resultTotal > 0 ? (int)ceil($resultTotal / $resultPerPage) : 1;

$sql .= " ORDER BY oi.id DESC LIMIT " . (int)$resultPerPage . " OFFSET " . (int)$resultOffset;

$stmt = $db->prepare($sql);
$stmt->execute($params);
$items = $stmt->fetchAll();

$statusLabels = ['pending' => 'معلق', 'in_progress' => 'قيد التنفيذ', 'validated' => 'معتمد', 'result_entered' => 'تم الإدخال'];

// هل يوجد طلب محدد وجاهز للاعتماد؟
$approveOrder = null;
$orderSummary = null;
if (!empty($_GET['order_id'])) {
    $oid = (int)$_GET['order_id'];
    $extraCols = '';
    try { $db->query('SELECT approved_at FROM lab_orders LIMIT 1'); $extraCols = ', o.approved_at, o.report_id'; } catch (Throwable $e) {}
    $stmt = $db->prepare('SELECT o.id, o.order_number, o.order_date, o.status' . $extraCols . ',
        (SELECT COUNT(*) FROM order_items WHERE order_id = o.id) AS total,
        (SELECT SUM(CASE WHEN status = "validated" THEN 1 ELSE 0 END) FROM order_items WHERE order_id = o.id) AS done
        FROM lab_orders o WHERE o.id = ?' . ($tenantOrderAnd ? ' AND o.tenant_id = ?' : ''));
    $stmt->execute($tenantOrderAnd ? [$oid, $tenantId] : [$oid]);
    $ao = $stmt->fetch();
    $orderSummary = $ao;
    $isAlreadyApproved = $extraCols && !empty($ao['approved_at'] ?? null);
    if ($ao && (int)$ao['total'] > 0 && (int)$ao['total'] === (int)$ao['done'] && !$isAlreadyApproved) {
        $approveOrder = $ao;
    }
}

$baseListUrl = 'index.php?page=results';
$navParams = [];
if ($resultSearch) $navParams['q'] = $resultSearch;
if ($resultStatusFilter) $navParams['status'] = $resultStatusFilter;
if (!empty($_GET['order_id'])) $navParams['order_id'] = (int)$_GET['order_id'];
$baseListUrl .= $navParams ? '&' . http_build_query($navParams) : '';
?>
<div class="results-page">
    <header class="patients-header">
        <h1>نتائج الفحوصات</h1>
        <div class="patients-actions">
            <form method="get" class="patients-search-form">
                <input type="hidden" name="page" value="results">
                <?php if (!empty($_GET['order_id'])): ?><input type="hidden" name="order_id" value="<?php echo (int)$_GET['order_id']; ?>"><?php endif; ?>
                <input type="search" name="q" placeholder="بحث برقم طلب، مريض، أو فحص..." value="<?php echo htmlspecialchars($resultSearch, ENT_QUOTES, 'UTF-8'); ?>" class="patients-search-input">
                <select name="status" onchange="this.form.submit()" style="padding:10px 14px;border-radius:var(--radius);border:1px solid var(--border);min-width:140px;">
                    <option value="">كل الحالات</option>
                    <option value="pending" <?php echo $resultStatusFilter === 'pending' ? 'selected' : ''; ?>>معلق</option>
                    <option value="in_progress" <?php echo $resultStatusFilter === 'in_progress' ? 'selected' : ''; ?>>قيد التنفيذ</option>
                    <option value="validated" <?php echo $resultStatusFilter === 'validated' ? 'selected' : ''; ?>>معتمد</option>
                </select>
                <button type="submit" class="btn-secondary">بحث</button>
                <?php if ($resultSearch || $resultStatusFilter): ?><a href="index.php?page=results<?php echo !empty($_GET['order_id']) ? '&order_id='.(int)$_GET['order_id'] : ''; ?>" class="btn-secondary">مسح</a><?php endif; ?>
            </form>
            <?php if (!empty($_GET['order_id'])): ?><a href="index.php?page=results" class="btn-secondary">عرض الكل</a><?php endif; ?>
        </div>
    </header>

    <section class="patients-stats results-stats">
        <div class="patients-stat-card">
            <span class="patients-stat-value"><?php echo number_format($resultTotal); ?></span>
            <span class="patients-stat-label">نتائج في القائمة</span>
        </div>
        <div class="patients-stat-card stat-warning">
            <span class="patients-stat-value"><?php echo $statsPending; ?></span>
            <span class="patients-stat-label">معلّق / قيد التنفيذ</span>
        </div>
        <div class="patients-stat-card" style="border-right-color:var(--status-completed);">
            <span class="patients-stat-value"><?php echo $statsValidated; ?></span>
            <span class="patients-stat-label">معتمد</span>
        </div>
    </section>

    <?php if ($orderSummary): ?>
    <div class="section-card results-order-summary">
        <h3>الطلب <?php echo htmlspecialchars($orderSummary['order_number'], ENT_QUOTES, 'UTF-8'); ?></h3>
        <p style="margin:8px 0 0;color:var(--text-secondary);">
            التاريخ: <?php echo htmlspecialchars($orderSummary['order_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>
            — <?php echo (int)($orderSummary['done'] ?? 0); ?> / <?php echo (int)($orderSummary['total'] ?? 0); ?> فحوصات معتمدة
        </p>
        <div style="margin-top:12px;display:flex;gap:12px;flex-wrap:wrap;">
            <a href="index.php?page=orders&q=<?php echo urlencode($orderSummary['order_number'] ?? ''); ?>" class="btn-secondary">عرض الطلب</a>
            <?php if (($auth->can('results.print') || $auth->can('results.view')) && !$auth->maskResults()): ?><a href="index.php?page=print_result&order_id=<?php echo (int)$orderSummary['id']; ?>" target="_blank" class="btn-secondary">طباعة التقرير</a><?php endif; ?>
            <?php if (($auth->can('results.print') || $auth->can('results.view')) && !$auth->maskResults()): ?><a href="index.php?page=results&action=create_share&order_id=<?php echo (int)$orderSummary['id']; ?>" class="btn-secondary">مشاركة رابط للطبيب</a><?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($_SESSION['result_save_ok'])): ?>
    <div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['result_save_ok'], ENT_QUOTES, 'UTF-8'); ?></div>
    <?php unset($_SESSION['result_save_ok']); endif; ?>
    <?php if (!empty($_SESSION['result_share_url'])): ?>
    <div class="alert alert-success" style="display:flex;flex-wrap:wrap;align-items:center;gap:8px;">
        <span>رابط المشاركة (صالح 7 أيام):</span>
        <input type="text" id="shareUrlInput" value="<?php echo htmlspecialchars($_SESSION['result_share_url'], ENT_QUOTES, 'UTF-8'); ?>" readonly style="flex:1;min-width:200px;">
        <button type="button" onclick="navigator.clipboard&&navigator.clipboard.writeText(document.getElementById('shareUrlInput').value).then(function(){alert('تم النسخ');});">نسخ</button>
    </div>
    <?php unset($_SESSION['result_share_url']); endif; ?>
    <?php if (!empty($_SESSION['result_save_error'])): ?>
    <div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['result_save_error'], ENT_QUOTES, 'UTF-8'); ?></div>
    <?php unset($_SESSION['result_save_error']); endif; ?>
    <?php if ($approveOrder): ?>
    <div class="alert alert-success" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
        <span>جميع نتائج الطلب <strong><?php echo htmlspecialchars($approveOrder['order_number'], ENT_QUOTES, 'UTF-8'); ?></strong> معتمدة. يمكنك الاعتماد النهائي للسماح بالطباعة.</span>
        <form method="post" action="index.php?page=results&action=approve" style="margin:0;">
            <input type="hidden" name="order_id" value="<?php echo (int)$approveOrder['id']; ?>">
            <button type="submit" class="btn-primary">اعتماد نهائي للطباعة</button>
        </form>
    </div>
    <?php endif; ?>

    <div class="section-card">
        <div class="table-wrapper">
        <table class="table patients-table results-table">
            <thead>
                <tr>
                    <th>رقم الطلب</th>
                    <th>التاريخ</th>
                    <th>المريض</th>
                    <th>الفحص</th>
                    <th>الفرع</th>
                    <th>الحالة</th>
                    <th style="width:220px;">إجراءات</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($items as $row): $flag = $row['flag'] ?? ''; $outRange = in_array($flag, ['L','H','C']); $isCritical = $flag === 'C'; ?>
                <tr class="<?php echo $isCritical ? 'result-critical' : ($outRange ? 'result-out-of-range' : ''); ?>">
                    <td><code class="patient-code"><?php echo htmlspecialchars($row['order_number'], ENT_QUOTES, 'UTF-8'); ?></code></td>
                    <td><?php echo htmlspecialchars($row['order_date'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><strong><?php echo htmlspecialchars($row['patient_name'], ENT_QUOTES, 'UTF-8'); ?></strong></td>
                    <td><?php echo htmlspecialchars($row['test_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($row['branch_name'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><span class="badge badge-<?php echo htmlspecialchars($row['status'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($statusLabels[$row['status']] ?? $row['status'], ENT_QUOTES, 'UTF-8'); ?></span></td>
                    <td class="patients-row-actions">
                        <?php if ($auth->can('results.edit') || $auth->can('results.validate')): ?>
                        <a href="index.php?page=results&action=enter&item_id=<?php echo (int)$row['id']; ?>" class="btn-action btn-action--edit" title="إدخال/تعديل النتيجة">إدخال نتيجة</a>
                        <?php endif; ?>
                        <?php if (($auth->can('results.print') || $auth->can('results.view')) && !$auth->maskResults()): ?>
                        <a href="index.php?page=print_result&order_id=<?php echo (int)$row['order_db_id']; ?>" target="_blank" class="btn-action btn-action--view" title="طباعة">طباعة</a>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php if (empty($items)): ?>
        <p class="patients-empty">
            لا توجد نتائج.
            <?php if ($resultSearch || $resultStatusFilter || !empty($_GET['order_id'])): ?>
            <a href="index.php?page=results">عرض الكل</a>
            <?php else: ?>
            <a href="index.php?page=orders">اذهب للطلبات</a>
            <?php endif; ?>
        </p>
        <?php endif; ?>
    </div>

    <?php if ($resultTotalPages > 1): ?>
    <nav class="patients-pagination">
        <?php if ($resultPage > 1): ?><a href="<?php echo $baseListUrl; ?>&p=<?php echo $resultPage - 1; ?>" class="btn-secondary">← السابق</a><?php endif; ?>
        <span class="patients-pagination-info">صفحة <?php echo $resultPage; ?> من <?php echo $resultTotalPages; ?></span>
        <?php if ($resultPage < $resultTotalPages): ?><a href="<?php echo $baseListUrl; ?>&p=<?php echo $resultPage + 1; ?>" class="btn-secondary">التالي →</a><?php endif; ?>
    </nav>
    <?php endif; ?>
</div>