<?php
use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DoctorNotification;
use App\Core\ClinicWebhookDispatcher;
use App\Core\ResultValidator;
use App\Core\Tenant;
use App\Core\WhatsApp;

if (!($auth instanceof Auth) || !$auth->can('results.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى النتائج.';
    return;
}

$tenantId = Tenant::id();
$canEditResults = $auth->can('results.edit') || $auth->can('results.validate');
$orderId = (int)($_GET['order_id'] ?? $_POST['order_id'] ?? 0);
$search = trim($_GET['q'] ?? '');
$statusFilter = trim($_GET['status'] ?? '');
/** @var string $sourceFilter all|doctor|lab — تصفية مصدر الطلب */
$sourceFilter = trim($_GET['source'] ?? '');
if (!in_array($sourceFilter, ['', 'doctor', 'lab'], true)) {
    $sourceFilter = '';
}

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

/**
 * تحميل بيانات الطلب + الفحوصات
 * @return array{order:?array,items:array<int,array<string,mixed>>}
 */
$loadOrderData = function (int $oid) use ($db, $tenantFilterSql, $tenantId): array {
    $order = null;
    $items = [];

    $orderSql = 'SELECT o.*, COALESCE(p.full_name, CONCAT("مريض #", o.patient_id)) AS patient_name
                 FROM lab_orders o
                 LEFT JOIN patients p ON p.id = o.patient_id
                 WHERE o.id = :order_id' . $tenantFilterSql . ' LIMIT 1';
    $stmt = $db->prepare($orderSql);
    $params = ['order_id' => $oid];
    if ($tenantFilterSql !== '') {
        $params['tenant_id'] = $tenantId;
    }
    $stmt->execute($params);
    $order = $stmt->fetch() ?: null;

    if ($order) {
        $order['doctor_name'] = '';
        try {
            $db->query('SELECT 1 FROM doctors LIMIT 1');
            $did = (int)($order['doctor_id'] ?? 0);
            if ($did > 0) {
                $st = $db->prepare('SELECT full_name FROM doctors WHERE id = ? LIMIT 1');
                $st->execute([$did]);
                $order['doctor_name'] = (string)($st->fetchColumn() ?: '');
            }
        } catch (Throwable $e) {
        }
        $stmt = $db->prepare(
            'SELECT oi.id AS item_id, oi.status AS item_status, oi.test_id,
                    t.name AS test_name, t.test_code, t.unit AS default_unit, t.reference_range,
                    r.result_value, r.unit, 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([$oid]);
        $items = $stmt->fetchAll();
    }

    return ['order' => $order, 'items' => $items];
};

/**
 * هل يوجد نتيجة محفوظة في السجل (للعرض والتقدّم)
 */
$resultsItemHasValue = static function (array $it): bool {
    return trim((string)($it['result_value'] ?? '')) !== '';
};

// حذف نتيجة فحص واحد
if ($canEditResults && $_SERVER['REQUEST_METHOD'] === 'POST' && (($_POST['action'] ?? '') === 'delete_result_item')) {
    Csrf::enforce($_POST['_csrf'] ?? null);
    $delOrderId = (int)($_POST['order_id'] ?? 0);
    $delItemId = (int)($_POST['item_id'] ?? 0);
    if ($delOrderId > 0 && $delItemId > 0) {
        try {
            $chkSql = 'SELECT oi.id FROM order_items oi JOIN lab_orders o ON o.id = oi.order_id WHERE oi.id = ? AND oi.order_id = ?';
            $chkParams = [$delItemId, $delOrderId];
            if ($tenantFilterSql !== '') {
                $chkSql .= ' AND o.tenant_id = ?';
                $chkParams[] = $tenantId;
            }
            $chk = $db->prepare($chkSql);
            $chk->execute($chkParams);
            if ($chk->fetch()) {
                $db->prepare('DELETE FROM results WHERE order_item_id = ?')->execute([$delItemId]);
                $db->prepare("UPDATE order_items SET status = 'pending' WHERE id = ?")->execute([$delItemId]);
                $stmt = $db->prepare("SELECT COUNT(*) FROM order_items WHERE order_id = ? AND status IN ('pending','in_progress')");
                $stmt->execute([$delOrderId]);
                $pendingCount = (int)$stmt->fetchColumn();
                $newSt = $pendingCount === 0 ? 'completed' : 'in_progress';
                $db->prepare('UPDATE lab_orders SET status = ? WHERE id = ?')->execute([$newSt, $delOrderId]);
                $_SESSION['results_msg'] = 'تم حذف نتيجة الفحص.';
            }
        } catch (Throwable $e) {
            $_SESSION['results_error'] = 'تعذر الحذف: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=results' . ($delOrderId > 0 ? '&order_id=' . $delOrderId : ''));
    exit;
}

// حفظ نتيجة سطر واحد (من وضع التعديل)
if ($canEditResults && $_SERVER['REQUEST_METHOD'] === 'POST' && (($_POST['action'] ?? '') === 'save_result_item')) {
    Csrf::enforce($_POST['_csrf'] ?? null);
    $oneOrderId = (int)($_POST['order_id'] ?? 0);
    $oneItemId = (int)($_POST['item_id'] ?? 0);
    if ($oneOrderId > 0 && $oneItemId > 0) {
        try {
            $data = $loadOrderData($oneOrderId);
            $order = $data['order'];
            $items = $data['items'];
            if (!$order) {
                throw new Exception('الطلب غير موجود.');
            }
            $target = null;
            foreach ($items as $row) {
                if ((int)$row['item_id'] === $oneItemId) {
                    $target = $row;
                    break;
                }
            }
            if (!$target) {
                throw new Exception('الفحص غير ضمن الطلب.');
            }

            $hasCriticalCols = false;
            try {
                $db->query('SELECT critical_value_min, critical_value_max FROM tests LIMIT 1');
                $hasCriticalCols = true;
            } catch (Throwable $e) {
            }
            $criticalMeta = [];
            if ($hasCriticalCols) {
                $tid = (int)$target['test_id'];
                $stmt = $db->prepare('SELECT id, critical_value_min, critical_value_max, reference_range, name FROM tests WHERE id = ?');
                $stmt->execute([$tid]);
                $tr = $stmt->fetch();
                if ($tr) {
                    $criticalMeta[$tid] = $tr;
                }
            }
            $hasUpdatedAt = false;
            try {
                $db->query('SELECT updated_at FROM results LIMIT 1');
                $hasUpdatedAt = true;
            } catch (Throwable $e) {
            }

            $value = trim((string)($_POST['result_value'] ?? ''));
            $unit = trim((string)($_POST['unit'] ?? ''));
            $notes = trim((string)($_POST['notes'] ?? ''));
            $flagInput = trim((string)($_POST['flag'] ?? ''));

            $db->beginTransaction();
            $criticalToNotify = [];
            if ($value === '') {
                $db->prepare('DELETE FROM results WHERE order_item_id = ?')->execute([$oneItemId]);
                $db->prepare("UPDATE order_items SET status = 'pending' WHERE id = ?")->execute([$oneItemId]);
            } else {
                $testId = (int)$target['test_id'];
                $flag = in_array($flagInput, ['N', 'L', 'H', 'C'], true) ? $flagInput : '';
                if ($flag === '') {
                    $meta = $criticalMeta[$testId] ?? null;
                    $flag = ResultValidator::checkValue(
                        $value,
                        $meta['reference_range'] ?? $target['reference_range'] ?? null,
                        $meta['critical_value_min'] ?? null,
                        $meta['critical_value_max'] ?? null
                    );
                }
                $stmt = $db->prepare('SELECT id FROM results WHERE order_item_id = ?');
                $stmt->execute([$oneItemId]);
                $existing = $stmt->fetch();
                if ($existing) {
                    $sql = 'UPDATE results SET result_value=?, unit=?, flag=?, notes=?, result_date=NOW()'
                        . ($hasUpdatedAt ? ', updated_at=NOW()' : '')
                        . ' WHERE order_item_id=?';
                    $db->prepare($sql)->execute([
                        $value,
                        $unit !== '' ? $unit : null,
                        $flag !== '' ? $flag : null,
                        $notes !== '' ? $notes : null,
                        $oneItemId,
                    ]);
                } else {
                    $db->prepare('INSERT INTO results (order_item_id, result_value, unit, flag, notes, result_date, created_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())')
                        ->execute([
                            $oneItemId,
                            $value,
                            $unit !== '' ? $unit : null,
                            $flag !== '' ? $flag : null,
                            $notes !== '' ? $notes : null,
                        ]);
                }
                $db->prepare("UPDATE order_items SET status = 'completed' WHERE id = ?")->execute([$oneItemId]);
                if ($flag === 'C') {
                    $criticalToNotify[] = ['name' => (string)($target['test_name'] ?? ''), 'value' => $value];
                }
            }

            $stmt = $db->prepare("SELECT COUNT(*) FROM order_items WHERE order_id = ? AND status IN ('pending','in_progress')");
            $stmt->execute([$oneOrderId]);
            $pendingCount = (int)$stmt->fetchColumn();
            $newStatus = $pendingCount === 0 ? 'completed' : 'in_progress';
            $oldOrderStatus = (string)($order['status'] ?? '');
            $db->prepare('UPDATE lab_orders SET status = ? WHERE id = ?')->execute([$newStatus, $oneOrderId]);

            $db->commit();

            if ($newStatus === 'completed' && $oldOrderStatus !== 'completed') {
                try {
                    $notifier = new DoctorNotification($db, $config ?? []);
                    $notifier->notifyOrderResultsReady(
                        (int)($order['doctor_id'] ?? 0),
                        (int)$tenantId,
                        $oneOrderId,
                        isset($order['order_number']) ? (string)$order['order_number'] : null,
                        !empty($order['patient_id']) ? (int)$order['patient_id'] : null
                    );
                } catch (Throwable $e) {
                }
                if (!empty($order['patient_id'])) {
                    try {
                        $wa = new WhatsApp($db, $config['whatsapp'] ?? []);
                        $wa->createNotificationForOrder($oneOrderId, (int)$order['patient_id']);
                    } catch (Throwable $e) {
                    }
                }
                try {
                    ClinicWebhookDispatcher::dispatchOrderCompleted($db, (int)$tenantId, $oneOrderId, $config ?? []);
                } catch (Throwable $e) {
                }
            }
            if (!empty($criticalToNotify) && !empty($order['doctor_id']) && !empty($order['patient_id'])) {
                try {
                    $notifier = new DoctorNotification($db, $config ?? []);
                    foreach ($criticalToNotify as $row) {
                        $notifier->notifyCriticalResult(
                            (int)$order['id'],
                            (int)$order['patient_id'],
                            (int)$order['doctor_id'],
                            (int)$tenantId,
                            $row['name'],
                            $row['value'],
                            (string)($order['order_number'] ?? null),
                            'doctor.php'
                        );
                    }
                } catch (Throwable $e) {
                }
            }

            $_SESSION['results_msg'] = 'تم حفظ نتيجة الفحص.';
        } catch (Throwable $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            $_SESSION['results_error'] = $e->getMessage();
        }
    }
    header('Location: index.php?page=results&order_id=' . $oneOrderId);
    exit;
}

// حفظ النتائج
if ($canEditResults && $_SERVER['REQUEST_METHOD'] === 'POST' && (($_POST['action'] ?? '') === 'save_results')) {
    Csrf::enforce($_POST['_csrf'] ?? null);

    if ($orderId <= 0) {
        $_SESSION['results_error'] = 'معرف الطلب غير صالح.';
        header('Location: index.php?page=results');
        exit;
    }

    try {
        $data = $loadOrderData($orderId);
        $order = $data['order'];
        $items = $data['items'];
        if (!$order) {
            throw new Exception('الطلب غير موجود أو لا يخص هذا المختبر.');
        }
        if (empty($items)) {
            throw new Exception('لا توجد فحوصات ضمن الطلب.');
        }

        $oldOrderStatus = (string)($order['status'] ?? '');

        $hasCriticalCols = false;
        try {
            $db->query('SELECT critical_value_min, critical_value_max FROM tests LIMIT 1');
            $hasCriticalCols = true;
        } catch (Throwable $e) {
        }

        $criticalMeta = [];
        if ($hasCriticalCols) {
            $stmt = $db->prepare('SELECT id, critical_value_min, critical_value_max, reference_range, name FROM tests WHERE id IN (' . implode(',', array_map('intval', array_column($items, 'test_id'))) . ')');
            $stmt->execute();
            foreach ($stmt->fetchAll() as $tr) {
                $criticalMeta[(int)$tr['id']] = $tr;
            }
        }

        $hasUpdatedAt = false;
        try {
            $db->query('SELECT updated_at FROM results LIMIT 1');
            $hasUpdatedAt = true;
        } catch (Throwable $e) {
        }

        $db->beginTransaction();
        $savedCount = 0;
        $criticalToNotify = [];

        $postedValues = $_POST['result_value'] ?? [];
        if (!is_array($postedValues)) {
            $postedValues = [];
        }
        $postedUnits = isset($_POST['unit']) && is_array($_POST['unit']) ? $_POST['unit'] : [];
        $postedNotes = isset($_POST['notes']) && is_array($_POST['notes']) ? $_POST['notes'] : [];
        $postedFlags = isset($_POST['flag']) && is_array($_POST['flag']) ? $_POST['flag'] : [];

        foreach ($items as $item) {
            $itemId = (int)$item['item_id'];
            $testId = (int)$item['test_id'];
            if (!array_key_exists((string)$itemId, $postedValues) && !array_key_exists($itemId, $postedValues)) {
                continue;
            }
            $value = trim((string)($postedValues[$itemId] ?? $postedValues[(string)$itemId] ?? ''));
            $unit = trim((string)($postedUnits[$itemId] ?? $postedUnits[(string)$itemId] ?? ''));
            $notes = trim((string)($postedNotes[$itemId] ?? $postedNotes[(string)$itemId] ?? ''));
            $flagInput = trim((string)($postedFlags[$itemId] ?? $postedFlags[(string)$itemId] ?? ''));

            if ($value === '') {
                $db->prepare("UPDATE order_items SET status = 'pending' WHERE id = ?")->execute([$itemId]);
                $db->prepare('DELETE FROM results WHERE order_item_id = ?')->execute([$itemId]);
                continue;
            }

            $flag = in_array($flagInput, ['N', 'L', 'H', 'C'], true) ? $flagInput : '';
            if ($flag === '') {
                $meta = $criticalMeta[$testId] ?? null;
                $flag = ResultValidator::checkValue(
                    $value,
                    $meta['reference_range'] ?? $item['reference_range'] ?? null,
                    $meta['critical_value_min'] ?? null,
                    $meta['critical_value_max'] ?? null
                );
            }

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

            if ($existing) {
                $sql = 'UPDATE results SET result_value=?, unit=?, flag=?, notes=?, result_date=NOW()'
                    . ($hasUpdatedAt ? ', updated_at=NOW()' : '')
                    . ' WHERE order_item_id=?';
                $db->prepare($sql)->execute([
                    $value,
                    $unit !== '' ? $unit : null,
                    $flag !== '' ? $flag : null,
                    $notes !== '' ? $notes : null,
                    $itemId
                ]);
            } else {
                $db->prepare('INSERT INTO results (order_item_id, result_value, unit, flag, notes, result_date, created_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())')
                    ->execute([
                        $itemId,
                        $value,
                        $unit !== '' ? $unit : null,
                        $flag !== '' ? $flag : null,
                        $notes !== '' ? $notes : null
                    ]);
            }

            $db->prepare("UPDATE order_items SET status = 'completed' WHERE id = ?")->execute([$itemId]);
            $savedCount++;
            if ($flag === 'C') {
                $criticalToNotify[] = ['name' => (string)($item['test_name'] ?? ''), 'value' => $value];
            }
        }

        $stmt = $db->prepare("SELECT COUNT(*) FROM order_items WHERE order_id = ? AND status IN ('pending','in_progress')");
        $stmt->execute([$orderId]);
        $pendingCount = (int)$stmt->fetchColumn();
        $newStatus = $pendingCount === 0 ? 'completed' : 'in_progress';
        $db->prepare('UPDATE lab_orders SET status = ? WHERE id = ?')->execute([$newStatus, $orderId]);

        $db->commit();

        if (isset($auditLog)) {
            try {
                $auditLog->log(
                    'results_saved',
                    'lab_order',
                    $orderId,
                    null,
                    json_encode(
                        ['saved_count' => $savedCount, 'order_status' => $newStatus],
                        JSON_UNESCAPED_UNICODE
                    ),
                    isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null,
                    (int)$tenantId
                );
            } catch (Throwable $e) {
            }
        }

        // إشعار الطبيب عند اكتمال كل النتائج (مركزي + منع تكرار التنبيه)
        if ($newStatus === 'completed' && $oldOrderStatus !== 'completed') {
            try {
                $notifier = new DoctorNotification($db, $config ?? []);
                $notifier->notifyOrderResultsReady(
                    (int)($order['doctor_id'] ?? 0),
                    (int)$tenantId,
                    $orderId,
                    isset($order['order_number']) ? (string)$order['order_number'] : null,
                    !empty($order['patient_id']) ? (int)$order['patient_id'] : null
                );
            } catch (Throwable $e) {
            }
        }

        if (!empty($criticalToNotify) && !empty($order['doctor_id']) && !empty($order['patient_id'])) {
            try {
                $notifier = new DoctorNotification($db, $config ?? []);
                foreach ($criticalToNotify as $row) {
                    $notifier->notifyCriticalResult(
                        (int)$order['id'],
                        (int)$order['patient_id'],
                        (int)$order['doctor_id'],
                        (int)$tenantId,
                        $row['name'],
                        $row['value'],
                        (string)($order['order_number'] ?? null),
                        'doctor.php'
                    );
                }
            } catch (Throwable $e) {
            }
        }

        // واتساب المريض عند اكتمال الطلب (إن وُجدت إعدادات / جدول الإشعارات)
        if ($newStatus === 'completed' && $oldOrderStatus !== 'completed' && !empty($order['patient_id'])) {
            try {
                $wa = new WhatsApp($db, $config['whatsapp'] ?? []);
                $wa->createNotificationForOrder($orderId, (int)$order['patient_id']);
            } catch (Throwable $e) {
            }
        }
        if ($newStatus === 'completed' && $oldOrderStatus !== 'completed') {
            try {
                ClinicWebhookDispatcher::dispatchOrderCompleted($db, (int)$tenantId, $orderId, $config ?? []);
            } catch (Throwable $e) {
            }
        }

        $_SESSION['results_msg'] = $savedCount > 0 ? 'تم حفظ النتائج بنجاح (' . $savedCount . ' فحص).' : 'لم يتم إدخال أي قيمة.';
        header('Location: index.php?page=results&order_id=' . $orderId);
        exit;
    } catch (Throwable $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        $_SESSION['results_error'] = 'تعذر حفظ النتائج: ' . $e->getMessage();
        header('Location: index.php?page=results' . ($orderId > 0 ? '&order_id=' . $orderId : ''));
        exit;
    }
}

$msg = $_SESSION['results_msg'] ?? '';
$err = $_SESSION['results_error'] ?? '';
unset($_SESSION['results_msg'], $_SESSION['results_error']);

if ($orderId > 0) {
    $data = ['order' => null, 'items' => []];
    try {
        $data = $loadOrderData($orderId);
    } catch (Throwable $e) {
    }
    $order = $data['order'];
    $items = $data['items'];
    if (!$order) {
        echo '<div class="alert alert-danger">الطلب غير موجود أو غير مسموح.</div><a href="index.php?page=results" class="btn-secondary">رجوع</a>';
        return;
    }
    $editItemId = (int)($_GET['edit_item'] ?? 0);
    $fullFormEdit = ($_GET['edit'] ?? '') === '1';

    $resultsFlagLabel = static function (?string $f): string {
        $m = ['N' => 'طبيعي', 'L' => 'منخفض', 'H' => 'مرتفع', 'C' => 'حرج'];
        return $m[$f] ?? '—';
    };

    $hasPendingInput = false;
    $anySaved = false;
    foreach ($items as $_it) {
        if (!$resultsItemHasValue($_it)) {
            $hasPendingInput = true;
        } else {
            $anySaved = true;
        }
    }
    $pageTitle = (!$fullFormEdit && !$hasPendingInput && $editItemId === 0) ? 'نتائج الفحوصات' : 'إدخال نتائج الفحوصات';
    if ($editItemId > 0) {
        $pageTitle = 'تعديل نتيجة فحص';
    }
    ?>
    <div class="page-header page-header--stack">
        <div class="page-header-top">
            <h1><?php echo htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8'); ?></h1>
            <div class="actions-bar" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
                <a href="index.php?page=results" class="btn-secondary">← رجوع للقائمة</a>
                <?php if ($canEditResults && !$fullFormEdit && $anySaved): ?>
                    <a href="index.php?page=results&order_id=<?php echo (int)$orderId; ?>&edit=1" class="btn-secondary">تعديل الكل</a>
                <?php elseif ($canEditResults && $fullFormEdit): ?>
                    <a href="index.php?page=results&order_id=<?php echo (int)$orderId; ?>" class="btn-secondary">عرض النتائج</a>
                <?php endif; ?>
            </div>
        </div>
        <p class="page-header-desc">تفاصيل الطلب والمريض وشريط التقدّم أدناه. بعد اكتمال النتائج يمكن طباعة التقرير أو العودة لقائمة الطلبات المعلقة.</p>
    </div>
    <?php if ($msg): ?><div class="alert alert-success" style="margin-bottom:12px;"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
    <?php if ($err): ?><div class="alert alert-danger" style="margin-bottom:12px;"><?php echo htmlspecialchars($err, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
    <?php
    $totalItems = count($items);
    $doneItems = 0;
    foreach ($items as $_it) {
        if ($resultsItemHasValue($_it) || ($_it['item_status'] ?? '') === 'completed') {
            $doneItems++;
        }
    }
    $pct = $totalItems > 0 ? (int)round(($doneItems / $totalItems) * 100) : 0;
    $priority = isset($order['priority']) ? (string)$order['priority'] : '';
    $hasPriorityCol = $priority !== '';
    $branchLabel = trim((string)($order['branch_name'] ?? ''));
    ?>
    <div class="card" style="margin-bottom:12px;">
        <div class="form-grid">
            <div><label>رقم الطلب</label><div style="padding:8px;background:var(--bg-secondary);border-radius:6px;"><?php echo htmlspecialchars((string)$order['order_number'], ENT_QUOTES, 'UTF-8'); ?></div></div>
            <div><label>المريض</label><div style="padding:8px;background:var(--bg-secondary);border-radius:6px;"><?php echo htmlspecialchars((string)$order['patient_name'], ENT_QUOTES, 'UTF-8'); ?></div></div>
            <div><label>التاريخ</label><div style="padding:8px;background:var(--bg-secondary);border-radius:6px;"><?php echo htmlspecialchars((string)$order['order_date'], ENT_QUOTES, 'UTF-8'); ?></div></div>
            <div><label>الحالة</label><div style="padding:8px;background:var(--bg-secondary);border-radius:6px;"><?php echo htmlspecialchars((string)$order['status'], ENT_QUOTES, 'UTF-8'); ?></div></div>
            <?php if ((int)($order['doctor_id'] ?? 0) > 0): ?>
            <div><label>الطبيب المحوّل</label><div style="padding:8px;background:var(--bg-secondary);border-radius:6px;"><?php echo '<span style="color:#0d9488;font-weight:600;">🩺</span> '; echo htmlspecialchars(trim((string)($order['doctor_name'] ?? '')) !== '' ? (string)$order['doctor_name'] : ('#' . (int)$order['doctor_id']), ENT_QUOTES, 'UTF-8'); ?></div></div>
            <?php endif; ?>
            <?php if ($hasPriorityCol && in_array($priority, ['urgent', 'high', 'normal'], true)): ?>
            <div><label>الأولوية</label><div style="padding:8px;background:var(--bg-secondary);border-radius:6px;"><?php
                $pl = ['urgent' => 'عاجل', 'high' => 'عالي', 'normal' => 'عادي'];
                $pc = ['urgent' => '#dc2626', 'high' => '#f59e0b', 'normal' => '#6b7280'];
                echo '<span style="padding:2px 8px;border-radius:4px;color:white;background:' . htmlspecialchars($pc[$priority] ?? '#6b7280', ENT_QUOTES, 'UTF-8') . ';">' . htmlspecialchars($pl[$priority] ?? $priority, ENT_QUOTES, 'UTF-8') . '</span>';
            ?></div></div>
            <?php endif; ?>
            <?php if ($branchLabel !== ''): ?>
            <div><label>الفرع</label><div style="padding:8px;background:var(--bg-secondary);border-radius:6px;"><?php echo htmlspecialchars($branchLabel, ENT_QUOTES, 'UTF-8'); ?></div></div>
            <?php endif; ?>
            <div style="grid-column:1/-1;">
                <label>تقدّم إدخال النتائج</label>
                <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
                    <div style="flex:1;min-width:160px;height:10px;background:var(--bg-secondary);border-radius:6px;overflow:hidden;">
                        <div style="height:100%;width:<?php echo $pct; ?>%;background:#0d9488;transition:width .2s;"></div>
                    </div>
                    <strong><?php echo $doneItems; ?> / <?php echo $totalItems; ?></strong> (<?php echo $pct; ?>%)
                </div>
            </div>
        </div>
        <div style="margin-top:12px;display:flex;gap:8px;flex-wrap:wrap;">
            <a href="index.php?page=orders&action=view&id=<?php echo (int)$orderId; ?>" class="btn-secondary">عرض الطلب</a>
            <?php if ($doneItems > 0): ?>
            <a href="index.php?page=print_result&order_id=<?php echo (int)$orderId; ?>" class="btn-secondary" target="_blank" rel="noopener">طباعة تقرير</a>
            <?php endif; ?>
        </div>
    </div>

    <?php if (empty($items)): ?>
        <div class="alert alert-info">لا توجد فحوصات لهذا الطلب.</div>
    <?php elseif ($fullFormEdit): ?>
        <form method="post">
            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="action" value="save_results">
            <input type="hidden" name="order_id" value="<?php echo (int)$orderId; ?>">
            <div class="card" style="margin-bottom:12px;">
                <p style="margin:0 0 8px;color:var(--text-muted);font-size:0.9rem;">وضع تعديل شامل — جميع الفحوصات في نموذج واحد.</p>
                <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px;">
                    <button type="button" class="btn-secondary" onclick="fillVisibleFlags('N')">كلها طبيعي</button>
                    <button type="button" class="btn-secondary" onclick="clearVisibleValues()">تفريغ القيم</button>
                </div>
                <div class="table-wrapper">
                    <table class="table">
                        <thead>
                        <tr>
                            <th>الفحص</th>
                            <th>النتيجة</th>
                            <th>الوحدة</th>
                            <th>المدى المرجعي</th>
                            <th>الراية</th>
                            <th>ملاحظات</th>
                            <th>الحالة</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($items as $it): $itemId = (int)$it['item_id']; ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars((string)$it['test_name'], ENT_QUOTES, 'UTF-8'); ?></strong><div style="color:var(--text-muted);font-size:12px;"><?php echo htmlspecialchars((string)($it['test_code'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></div></td>
                                <td><input type="text" class="result-value-input" name="result_value[<?php echo $itemId; ?>]" value="<?php echo htmlspecialchars((string)($it['result_value'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: 12.4"></td>
                                <td><input type="text" name="unit[<?php echo $itemId; ?>]" value="<?php echo htmlspecialchars((string)($it['unit'] ?? $it['default_unit'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"></td>
                                <td><?php echo htmlspecialchars((string)($it['reference_range'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
                                <td>
                                    <select class="result-flag-select" name="flag[<?php echo $itemId; ?>]">
                                        <option value="" <?php echo empty($it['flag']) ? 'selected' : ''; ?>>تلقائي</option>
                                        <option value="N" <?php echo ($it['flag'] ?? '') === 'N' ? 'selected' : ''; ?>>طبيعي</option>
                                        <option value="L" <?php echo ($it['flag'] ?? '') === 'L' ? 'selected' : ''; ?>>منخفض</option>
                                        <option value="H" <?php echo ($it['flag'] ?? '') === 'H' ? 'selected' : ''; ?>>مرتفع</option>
                                        <option value="C" <?php echo ($it['flag'] ?? '') === 'C' ? 'selected' : ''; ?>>حرج</option>
                                    </select>
                                </td>
                                <td><input type="text" name="notes[<?php echo $itemId; ?>]" value="<?php echo htmlspecialchars((string)($it['notes'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"></td>
                                <td><span class="badge badge-<?php echo ($it['item_status'] ?? '') === 'completed' ? 'completed' : 'pending'; ?>"><?php echo ($it['item_status'] ?? '') === 'completed' ? 'مكتمل' : 'معلق'; ?></span></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div style="margin-top:14px;display:flex;gap:8px;">
                    <?php if ($canEditResults): ?><button type="submit" class="btn-primary">حفظ النتائج</button><?php endif; ?>
                    <a href="index.php?page=results&order_id=<?php echo (int)$orderId; ?>" class="btn-secondary">إلغاء</a>
                </div>
            </div>
        </form>
        <script>
            function fillVisibleFlags(flag) {
                document.querySelectorAll('.result-flag-select').forEach(function (s) { s.value = flag; });
            }
            function clearVisibleValues() {
                document.querySelectorAll('.result-value-input').forEach(function (i) { i.value = ''; });
            }
        </script>
    <?php else: ?>
        <?php if ($anySaved): ?>
        <div class="card" style="margin-bottom:16px;">
            <h3 style="margin-top:0;">النتائج المدخلة</h3>
            <p style="color:var(--text-muted);font-size:0.9rem;margin-top:0;">تم حفظ القيم التالية. يمكنك الطباعة أو التعديل أو الحذف لكل فحص.</p>
            <div class="table-wrapper">
                <table class="table">
                    <thead>
                    <tr>
                        <th>الفحص</th>
                        <th>النتيجة</th>
                        <th>الوحدة</th>
                        <th>المدى المرجعي</th>
                        <th>الراية</th>
                        <th>ملاحظات</th>
                        <th>الحالة</th>
                        <?php if ($canEditResults): ?><th style="min-width:140px;">إجراءات</th><?php endif; ?>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($items as $it):
                        $itemId = (int)$it['item_id'];
                        if (!$resultsItemHasValue($it)) {
                            continue;
                        }
                        if ($editItemId === $itemId && $canEditResults): ?>
                        <tr style="background:var(--bg-secondary);">
                            <td colspan="<?php echo $canEditResults ? '8' : '7'; ?>">
                                <form method="post" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:10px;align-items:end;padding:8px 0;">
                                    <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                                    <input type="hidden" name="action" value="save_result_item">
                                    <input type="hidden" name="order_id" value="<?php echo (int)$orderId; ?>">
                                    <input type="hidden" name="item_id" value="<?php echo $itemId; ?>">
                                    <div style="grid-column:1/-1;"><strong><?php echo htmlspecialchars((string)$it['test_name'], ENT_QUOTES, 'UTF-8'); ?></strong> <span style="color:var(--text-muted);font-size:12px;"><?php echo htmlspecialchars((string)($it['test_code'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></span></div>
                                    <div><label>النتيجة</label><input type="text" name="result_value" value="<?php echo htmlspecialchars((string)($it['result_value'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>" class="result-value-input" style="width:100%;"></div>
                                    <div><label>الوحدة</label><input type="text" name="unit" value="<?php echo htmlspecialchars((string)($it['unit'] ?? $it['default_unit'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>" style="width:100%;"></div>
                                    <div><label>الراية</label>
                                        <select name="flag" style="width:100%;">
                                            <option value="" <?php echo empty($it['flag']) ? 'selected' : ''; ?>>تلقائي</option>
                                            <option value="N" <?php echo ($it['flag'] ?? '') === 'N' ? 'selected' : ''; ?>>طبيعي</option>
                                            <option value="L" <?php echo ($it['flag'] ?? '') === 'L' ? 'selected' : ''; ?>>منخفض</option>
                                            <option value="H" <?php echo ($it['flag'] ?? '') === 'H' ? 'selected' : ''; ?>>مرتفع</option>
                                            <option value="C" <?php echo ($it['flag'] ?? '') === 'C' ? 'selected' : ''; ?>>حرج</option>
                                        </select>
                                    </div>
                                    <div style="grid-column:1/-1;"><label>ملاحظات</label><input type="text" name="notes" value="<?php echo htmlspecialchars((string)($it['notes'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>" style="width:100%;"></div>
                                    <div style="grid-column:1/-1;display:flex;gap:8px;flex-wrap:wrap;">
                                        <button type="submit" class="btn-primary">حفظ</button>
                                        <a href="index.php?page=results&order_id=<?php echo (int)$orderId; ?>" class="btn-secondary">إلغاء</a>
                                    </div>
                                </form>
                            </td>
                        </tr>
                        <?php else: ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars((string)$it['test_name'], ENT_QUOTES, 'UTF-8'); ?></strong><div style="color:var(--text-muted);font-size:12px;"><?php echo htmlspecialchars((string)($it['test_code'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></div></td>
                            <td><strong><?php echo htmlspecialchars((string)($it['result_value'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></strong></td>
                            <td><?php echo htmlspecialchars((string)($it['unit'] ?? $it['default_unit'] ?? '—'), ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars((string)($it['reference_range'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars($resultsFlagLabel(isset($it['flag']) ? (string)$it['flag'] : ''), ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars((string)($it['notes'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><span class="badge badge-completed">مدخل</span></td>
                            <?php if ($canEditResults): ?>
                            <td style="white-space:nowrap;">
                                <a href="index.php?page=results&order_id=<?php echo (int)$orderId; ?>&edit_item=<?php echo $itemId; ?>" class="btn-secondary btn-sm" style="padding:4px 10px;font-size:0.85rem;">تعديل</a>
                                <form method="post" style="display:inline;" onsubmit="return confirm('حذف نتيجة هذا الفحص؟ سيعود للمعلق.');">
                                    <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                                    <input type="hidden" name="action" value="delete_result_item">
                                    <input type="hidden" name="order_id" value="<?php echo (int)$orderId; ?>">
                                    <input type="hidden" name="item_id" value="<?php echo $itemId; ?>">
                                    <button type="submit" class="btn-secondary btn-sm" style="padding:4px 10px;font-size:0.85rem;color:#b91c1c;border-color:#fecaca;">حذف</button>
                                </form>
                            </td>
                            <?php endif; ?>
                        </tr>
                        <?php endif; ?>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($hasPendingInput && $canEditResults): ?>
        <div class="card" style="margin-bottom:16px;">
            <h3 style="margin-top:0;">فحوصات بانتظار الإدخال</h3>
            <form method="post">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="action" value="save_results">
                <input type="hidden" name="order_id" value="<?php echo (int)$orderId; ?>">
                <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px;">
                    <button type="button" class="btn-secondary" onclick="fillPendingFlags('N')">كلها طبيعي</button>
                    <button type="button" class="btn-secondary" onclick="clearPendingValues()">تفريغ القيم</button>
                </div>
                <div class="table-wrapper">
                    <table class="table">
                        <thead>
                        <tr>
                            <th>الفحص</th>
                            <th>النتيجة</th>
                            <th>الوحدة</th>
                            <th>المدى المرجعي</th>
                            <th>الراية</th>
                            <th>ملاحظات</th>
                            <th>الحالة</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($items as $it):
                            $itemId = (int)$it['item_id'];
                            if ($resultsItemHasValue($it)) {
                                continue;
                            }
                            ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars((string)$it['test_name'], ENT_QUOTES, 'UTF-8'); ?></strong><div style="color:var(--text-muted);font-size:12px;"><?php echo htmlspecialchars((string)($it['test_code'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></div></td>
                                <td><input type="text" class="pending-result-input" name="result_value[<?php echo $itemId; ?>]" value="" placeholder="أدخل النتيجة"></td>
                                <td><input type="text" name="unit[<?php echo $itemId; ?>]" value="<?php echo htmlspecialchars((string)($it['default_unit'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"></td>
                                <td><?php echo htmlspecialchars((string)($it['reference_range'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
                                <td>
                                    <select class="pending-flag-select" name="flag[<?php echo $itemId; ?>]">
                                        <option value="" selected>تلقائي</option>
                                        <option value="N">طبيعي</option>
                                        <option value="L">منخفض</option>
                                        <option value="H">مرتفع</option>
                                        <option value="C">حرج</option>
                                    </select>
                                </td>
                                <td><input type="text" name="notes[<?php echo $itemId; ?>]" value=""></td>
                                <td><span class="badge badge-pending">معلق</span></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div style="margin-top:14px;display:flex;gap:8px;">
                    <button type="submit" class="btn-primary">حفظ النتائج</button>
                    <a href="index.php?page=results" class="btn-secondary">رجوع للقائمة</a>
                </div>
            </form>
        </div>
        <script>
            function fillPendingFlags(flag) {
                document.querySelectorAll('.pending-flag-select').forEach(function (s) { s.value = flag; });
            }
            function clearPendingValues() {
                document.querySelectorAll('.pending-result-input').forEach(function (i) { i.value = ''; });
            }
        </script>
        <?php elseif ($hasPendingInput && !$canEditResults): ?>
        <div class="alert alert-info">يوجد فحوصات بلا نتيجة — ليس لديك صلاحية الإدخال.</div>
        <?php else: ?>
        <div style="margin-top:12px;display:flex;gap:8px;flex-wrap:wrap;">
            <a href="index.php?page=results" class="btn-secondary">رجوع للقائمة</a>
        </div>
        <?php endif; ?>
    <?php endif; ?>
    <?php
    return;
}

// قائمة الطلبات المعلقة
$orders = [];
$hasDoctorsTbl = false;
try {
    $db->query('SELECT 1 FROM doctors LIMIT 1');
    $hasDoctorsTbl = true;
} catch (Throwable $e) {
}
$doctorNameSelect = $hasDoctorsTbl
    ? '(SELECT d.full_name FROM doctors d WHERE d.id = o.doctor_id LIMIT 1) AS doctor_name'
    : 'NULL AS doctor_name';
try {
    $sql = "SELECT o.id, o.order_number, o.order_date, o.status, o.patient_id, o.doctor_id,
                   COALESCE(p.full_name, CONCAT('مريض #', o.patient_id)) AS patient_name,
                   $doctorNameSelect,
                   (SELECT COUNT(*) FROM order_items oi WHERE oi.order_id = o.id AND oi.status IN ('pending','in_progress')) AS pending_items
            FROM lab_orders o
            LEFT JOIN patients p ON p.id = o.patient_id
            WHERE o.status != 'cancelled' $tenantFilterSql";
    $params = [];
    if ($tenantFilterSql !== '') {
        $params['tenant_id'] = $tenantId;
    }
    if ($statusFilter !== '' && in_array($statusFilter, ['new', 'in_progress', 'completed'], true)) {
        $sql .= ' AND o.status = :status';
        $params['status'] = $statusFilter;
    }
    if ($sourceFilter === 'doctor') {
        $sql .= ' AND COALESCE(o.doctor_id, 0) > 0';
    } elseif ($sourceFilter === 'lab') {
        $sql .= ' AND COALESCE(o.doctor_id, 0) = 0';
    }
    if ($search !== '') {
        $sql .= ' AND (o.order_number LIKE :q OR COALESCE(p.full_name, "") LIKE :q2)';
        $params['q'] = '%' . $search . '%';
        $params['q2'] = '%' . $search . '%';
    }
    $sql .= ' HAVING pending_items > 0 ORDER BY (CASE WHEN COALESCE(o.doctor_id, 0) > 0 THEN 0 ELSE 1 END), o.order_date DESC LIMIT 300';
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $orders = $stmt->fetchAll();
} catch (Throwable $e) {
    $err = $err !== '' ? $err : 'تعذر تحميل الطلبات المعلقة.';
}
?>
<div class="page-header page-header--stack">
    <div class="page-header-top">
        <h1>نتائج الفحوصات</h1>
        <div class="actions-bar">
            <?php if ($canEditResults): ?><a href="index.php?page=import_results" class="btn-secondary">📥 استيراد من ملف</a><?php endif; ?>
        </div>
    </div>
    <p class="page-header-desc">قائمة الطلبات التي بها فحوصات بانتظار إدخال النتائج. بعد اختيار الطلب يمكن الإدخال لكل فحص، الطباعة، والربط مع التحقق والاعتماد.</p>
    <nav class="lab-quick-nav" aria-label="اختصارات ذات صلة">
        <?php if ($auth->can('orders.view')): ?><a href="index.php?page=orders">طلبات الفحوصات</a><?php endif; ?>
        <?php if ($auth->can('worklist.view')): ?><a href="index.php?page=worklist">قائمة العمل</a><?php endif; ?>
        <?php if ($canEditResults): ?><a href="index.php?page=import_results">إدخال جماعي (CSV)</a><?php endif; ?>
        <?php if ($auth->can('billing.view')): ?><a href="index.php?page=billing">الفواتير</a><?php endif; ?>
        <?php if ($auth->can('results.view')): ?><a href="index.php?page=samples">إدارة العينات</a><?php endif; ?>
    </nav>
</div>
<?php if ($msg): ?><div class="alert alert-success" style="margin-bottom:12px;"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger" style="margin-bottom:12px;"><?php echo htmlspecialchars($err, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>

<div class="card" style="margin-bottom:12px;">
    <h3 style="margin-top:0;">بحث</h3>
    <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;">
        <input type="hidden" name="page" value="results">
        <input type="search" name="q" value="<?php echo htmlspecialchars($search, ENT_QUOTES, 'UTF-8'); ?>" placeholder="رقم الطلب أو اسم المريض" style="min-width:240px;">
        <select name="status">
            <option value="">كل الحالات</option>
            <option value="new" <?php echo $statusFilter === 'new' ? 'selected' : ''; ?>>جديد</option>
            <option value="in_progress" <?php echo $statusFilter === 'in_progress' ? 'selected' : ''; ?>>قيد التنفيذ</option>
            <option value="completed" <?php echo $statusFilter === 'completed' ? 'selected' : ''; ?>>مكتمل</option>
        </select>
        <select name="source" title="مصدر الطلب">
            <option value="">كل المصادر</option>
            <option value="doctor" <?php echo $sourceFilter === 'doctor' ? 'selected' : ''; ?>>طلبات أطباء</option>
            <option value="lab" <?php echo $sourceFilter === 'lab' ? 'selected' : ''; ?>>طلبات المختبر</option>
        </select>
        <button type="submit">تطبيق</button>
        <?php if ($search !== '' || $statusFilter !== '' || $sourceFilter !== ''): ?><a href="index.php?page=results" class="btn-secondary">إلغاء</a><?php endif; ?>
    </form>
</div>

<div class="card">
    <h3 style="margin-top:0;">طلبات بانتظار الإدخال</h3>
    <?php if (empty($orders)): ?>
        <p style="color:var(--text-muted);padding:16px 0;">لا توجد طلبات بانتظار إدخال النتائج.</p>
    <?php else: ?>
        <div class="table-wrapper">
            <table class="table">
                <thead>
                <tr>
                    <th>رقم الطلب</th>
                    <th>المريض</th>
                    <th>المصدر</th>
                    <th>التاريخ</th>
                    <th>الحالة</th>
                    <th>عدد الفحوصات المعلقة</th>
                    <th>إجراء</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($orders as $o): ?>
                    <tr>
                        <td><?php echo htmlspecialchars((string)($o['order_number'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php echo htmlspecialchars((string)($o['patient_name'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php
                            $did = (int)($o['doctor_id'] ?? 0);
                            if ($did > 0) {
                                $dn = trim((string)($o['doctor_name'] ?? ''));
                                echo '<span class="badge" style="background:#0d9488;color:#fff;" title="طلب من طبيب">طبيب</span> ';
                                echo $dn !== '' ? htmlspecialchars($dn, ENT_QUOTES, 'UTF-8') : ('#' . $did);
                            } else {
                                echo '<span class="badge" style="background:var(--bg-secondary);color:var(--text-muted);">مختبر</span>';
                            }
                        ?></td>
                        <td><?php echo htmlspecialchars((string)($o['order_date'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php echo htmlspecialchars((string)($o['status'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><strong><?php echo (int)($o['pending_items'] ?? 0); ?></strong></td>
                        <td><a href="index.php?page=results&order_id=<?php echo (int)$o['id']; ?>" class="btn-primary">إدخال النتائج</a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>
