<?php 
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../dripend/includes/db.php';

// ==============================================================================
// 1. ADVANCED QUEUE FILTERING (DATE RANGE & PATIENT SEARCH)
// ==============================================================================
$date_from_raw = $_GET['date_from'] ?? date('Y-m-d');
$date_to_raw = $_GET['date_to'] ?? date('Y-m-d');
$is_all_backlog = ($date_from_raw === 'ALL');

$date_from_sql = $conn->real_escape_string($date_from_raw . ' 00:00:00');
$date_to_sql = $conn->real_escape_string($date_to_raw . ' 23:59:59');

$target_patient_no = $_GET['patient_no'] ?? null;
$testing_queue = [];
$pending_patients = [];

// A. Fetch all patients with 'Sample Collected' status AND a valid mapped service
$qPatients = "
    SELECT DISTINCT p.patient_no, p.first_name, p.last_name 
    FROM clinical_lab_requests clr
    JOIN patient p ON clr.patient_no = p.patient_no
    LEFT JOIN clinical_sample_collections csc ON clr.id = csc.request_id
    WHERE clr.status = 'Sample Collected' AND clr.service_id IS NOT NULL
";

if (!$is_all_backlog) {
    $qPatients .= " AND csc.collected_at >= '$date_from_sql' AND csc.collected_at <= '$date_to_sql'";
}
$qPatients .= " ORDER BY clr.request_date ASC";

$resPts = $conn->query($qPatients);
if ($resPts) {
    while($row = $resPts->fetch_assoc()) {
        $pending_patients[] = [
            'patient_no' => $row['patient_no'],
            'patient_name' => trim($row['first_name'] . ' ' . $row['last_name'])
        ];
    }
}

if (!$target_patient_no && !empty($pending_patients)) {
    $target_patient_no = $pending_patients[0]['patient_no'];
}

// ==============================================================================
// 2. FETCH SPECIFIC PATIENT DATA & STRICTLY MAPPED TESTS
// ==============================================================================
if ($target_patient_no) {
    
    $qContext = "
        SELECT 
            p.patient_no, p.first_name, p.last_name, p.blood_group,
            TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) AS age,
            g.gender_name AS gender,
            clr.notes AS diagnosis_notes, clr.priority,
            CONCAT('Dr. ', COALESCE(s.first_name, 'Unknown'), ' ', COALESCE(s.last_name, '')) AS doctor,
            COALESCE(dat.attendance_name, 'OPD Walk-in') AS ward_type
        FROM clinical_lab_requests clr
        JOIN patient p ON clr.patient_no = p.patient_no
        LEFT JOIN gender g ON p.gender_id = g.id
        LEFT JOIN staff s ON clr.requested_by = s.staff_id
        LEFT JOIN visit_master vm ON clr.visit_id = vm.id
        LEFT JOIN dict_attendance_type dat ON vm.attendance_type = dat.attendance_code
        LEFT JOIN clinical_sample_collections csc ON clr.id = csc.request_id
        WHERE clr.patient_no = ? AND clr.status = 'Sample Collected' AND clr.service_id IS NOT NULL
    ";
    
    if (!$is_all_backlog) {
        $qContext .= " AND csc.collected_at >= '$date_from_sql' AND csc.collected_at <= '$date_to_sql'";
    }
    $qContext .= " ORDER BY clr.priority ASC LIMIT 1";
    
    $stmtContext = $conn->prepare($qContext);
    $stmtContext->bind_param("s", $target_patient_no);
    $stmtContext->execute();
    $ctxRes = $stmtContext->get_result()->fetch_assoc();
    $stmtContext->close();

    if ($ctxRes) {
        $testing_queue['patient_details'] = [
            'hospital_id' => $ctxRes['patient_no'],
            'patient_name' => trim($ctxRes['first_name'] . ' ' . $ctxRes['last_name']),
            'age' => $ctxRes['age'] ?? 0,
            'gender' => $ctxRes['gender'] ?? 'Unknown',
            'blood_group' => $ctxRes['blood_group'] ?? 'Unknown',
            'ward_type' => $ctxRes['ward_type']
        ];
        
        $testing_queue['clinical_context'] = [
            'doctor' => $ctxRes['doctor'],
            'diagnosis_notes' => !empty($ctxRes['diagnosis_notes']) ? $ctxRes['diagnosis_notes'] : 'No clinical notes provided.',
            'priority' => $ctxRes['priority']
        ];
    }

    $qTests = "
        SELECT 
            clr.id AS request_id, clr.service_id, 
            COALESCE(sc.service_name, clr.test_name) AS test_name,
            COALESCE(lsd.sub_dept_name, d.department_name, 'Laboratory') AS department,
            csc.barcode, csc.collected_at, csc.source AS sample_type
        FROM clinical_lab_requests clr
        LEFT JOIN service_catalog sc ON clr.service_id = sc.id
        LEFT JOIN departments d ON sc.department_id = d.id
        LEFT JOIN lab_sub_departments lsd ON sc.lab_sub_dept_id = lsd.id
        LEFT JOIN clinical_sample_collections csc ON clr.id = csc.request_id
        WHERE clr.patient_no = ? AND clr.status = 'Sample Collected' AND clr.service_id IS NOT NULL
    ";
    
    if (!$is_all_backlog) {
        $qTests .= " AND csc.collected_at >= '$date_from_sql' AND csc.collected_at <= '$date_to_sql'";
    }
    
    $stmtTests = $conn->prepare($qTests);
    $stmtTests->bind_param("s", $target_patient_no);
    $stmtTests->execute();
    $resTests = $stmtTests->get_result();
    
    $testing_queue['tests'] = [];
    
    $qParams = "
        SELECT 
            lp.id AS parameter_id, lp.parameter_name, lp.unit_of_measure, 
            lp.min_male, lp.max_male, lp.min_female, lp.max_female, lp.min_child, lp.max_child,
            lp.result_type, lp.options_list, lp.expected_value
        FROM lab_test_parameter_mapping ltpm
        JOIN lab_parameters lp ON ltpm.parameter_id = lp.id
        WHERE ltpm.service_id = ? AND lp.is_active = 1
        ORDER BY ltpm.display_order ASC
    ";
    $stmtParams = $conn->prepare($qParams);

    while ($row = $resTests->fetch_assoc()) {
        $test_data = [
            'item_id' => $row['request_id'],
            'service_id' => $row['service_id'],
            'test_name' => $row['test_name'],
            'department' => $row['department'],
            'barcode' => $row['barcode'] ?? 'N/A',
            'collected_at' => !empty($row['collected_at']) ? date('d-M-Y h:i A', strtotime($row['collected_at'])) : 'N/A',
            'sample_type' => $row['sample_type'] ?? 'Unknown Source',
            'machine_linked' => null, 
            'parameters' => []
        ];

        if (!empty($row['service_id'])) {
            $stmtParams->bind_param("i", $row['service_id']);
            $stmtParams->execute();
            $resParams = $stmtParams->get_result();
            
            while ($param = $resParams->fetch_assoc()) {
                $ref_min = null; $ref_max = null;
                $age = $testing_queue['patient_details']['age'] ?? 0;
                $gender = strtolower($testing_queue['patient_details']['gender'] ?? '');
                
                if ($age < 13 && $param['min_child'] !== null) {
                    $ref_min = $param['min_child']; $ref_max = $param['max_child'];
                } elseif ($gender == 'male' && $param['min_male'] !== null) {
                    $ref_min = $param['min_male']; $ref_max = $param['max_male'];
                } else {
                    $ref_min = $param['min_female']; $ref_max = $param['max_female'];
                }

                $options = [];
                if ($param['result_type'] === 'Options' && !empty($param['options_list'])) {
                    $options = array_map('trim', explode(',', $param['options_list']));
                }

                $test_data['parameters'][] = [
                    'parameter_id' => $param['parameter_id'],
                    'label' => $param['parameter_name'],
                    'unit' => $param['unit_of_measure'],
                    'ref_min' => $ref_min,
                    'ref_max' => $ref_max,
                    'type' => strtolower($param['result_type']),
                    'options' => $options,
                    'expected' => $param['expected_value']
                ];
            }
        }
        $testing_queue['tests'][] = $test_data;
    }
    $stmtParams->close();
    $stmtTests->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Testing & Results | Tier 1 Laboratory System</title>

<!-- Fonts & Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<!-- Select2 CSS for Smart Patient Search -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<style>
:root {
  --sidebar-width: 300px;
  --transition-speed: 0.35s;
  --bg-app: #f4f7f9;
  --bg-card: #ffffff;
  --brand-secondary: #2563eb;
  --success: #10b981;
  --danger: #ef4444;
  --warning: #f59e0b;
  --warning-light: #fefce8;
  --warning-border: #fef08a;
  --low-flag: #3b82f6; 
  --border-light: #e2e8f0;
  --text-main: #0f172a;
  --text-muted: #64748b;
  --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Inter', sans-serif; background: var(--bg-app); color: var(--text-main); -webkit-font-smoothing: antialiased; }

::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #94a3b8; }

.main-content { margin-left: var(--sidebar-width); padding: 25px 30px; display: flex; flex-direction: column; min-height: 100vh; transition: margin-left var(--transition-speed) cubic-bezier(0.4, 0, 0.2, 1); }
.main-content.expanded { margin-left: 0; }
@media (max-width: 1024px) { .main-content { margin-left: 0; } }

.container { max-width: 1400px; margin: 0 auto; width: 100%; flex: 1; display: flex; flex-direction: column; }

.workflow-tracker { display: flex; align-items: center; gap: 15px; margin-bottom: 15px; background: var(--bg-card); padding: 12px 25px; border-radius: 8px; box-shadow: var(--shadow-sm); border: 1px solid var(--border-light); flex-shrink: 0; }
.step { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 600; color: var(--text-muted); }
.step.completed { color: var(--success); }
.step.active { color: var(--brand-secondary); }
.step-divider { color: var(--border-light); }

.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; flex-shrink: 0; }
.page-header h1 { font-size: 22px; color: var(--text-main); font-weight: 700; display: flex; align-items: center; gap: 10px; }

/* Filter Bar */
.filter-bar { display: flex; gap: 20px; background: #fff; padding: 15px 25px; border-radius: 8px; border: 1px solid var(--border-light); box-shadow: var(--shadow-sm); margin-bottom: 20px; align-items: center; flex-shrink: 0; }
.filter-bar .form-group { flex: 1; }
.filter-bar .form-group.large { flex: 2; }
.filter-bar label { display: block; font-size: 11px; font-weight: 700; color: var(--text-muted); margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.5px; }

/* Select2 Custom overrides to match Enterprise Theme */
.select2-container--default .select2-selection--single { height: 40px; border: 1px solid var(--border-light); border-radius: 6px; display: flex; align-items: center; background: #fff; }
.select2-container--default .select2-selection--single:focus, .select2-container--default.select2-container--focus .select2-selection--single { border-color: var(--brand-secondary); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1); }
.select2-container--default .select2-selection--single .select2-selection__rendered { font-size: 13px; font-weight: 600; color: var(--text-main); padding-left: 12px; }
.select2-container--default .select2-selection--single .select2-selection__arrow { height: 38px; }

.clinical-alert { background: var(--warning-light); border: 1px solid var(--warning-border); border-left: 4px solid var(--warning); padding: 15px 25px; border-radius: 8px; margin-bottom: 15px; display: flex; gap: 18px; align-items: flex-start; box-shadow: var(--shadow-sm); flex-shrink: 0;}
.clinical-alert i.icon-main { color: var(--warning); font-size: 24px; margin-top: 2px; }
.clinical-alert-content h4 { color: #854d0e; font-size: 13px; margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.5px; }
.clinical-alert-content p { font-size: 14px; color: var(--text-main); line-height: 1.5; font-weight: 500; }
.clinical-alert-content .meta { font-size: 12px; color: #a16207; margin-top: 8px; font-weight: 600; display: flex; gap: 15px; }

.workspace { display: flex; gap: 20px; align-items: stretch; flex: 1; min-height: 600px; margin-bottom: 15px; }

.test-navigation { width: 320px; background: var(--bg-card); border-radius: 8px; border: 1px solid var(--border-light); box-shadow: var(--shadow-sm); display: flex; flex-direction: column; flex-shrink: 0; }
.nav-filters { padding: 15px 20px; border-bottom: 1px solid var(--border-light); background: #f8fafc; border-radius: 8px 8px 0 0; flex-shrink: 0; }
.search-box { position: relative; margin-bottom: 12px; }
.search-box i { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: var(--text-muted); }
.search-box input { width: 100%; padding: 10px 10px 10px 35px; border: 1px solid var(--border-light); border-radius: 6px; font-size: 13px; outline: none; transition: 0.2s; background: #fff;}
.search-box input:focus { border-color: var(--brand-secondary); box-shadow: 0 0 0 3px rgba(37,99,235,0.1); }

.nav-tabs { flex: 1; overflow-y: auto; }
.test-tab { padding: 15px 20px; border-bottom: 1px solid var(--border-light); cursor: pointer; transition: 0.2s; border-left: 4px solid transparent; display: flex; justify-content: space-between; align-items: center; }
.test-tab:hover { background: #f8fafc; }
.test-tab.active { background: #eff6ff; border-left-color: var(--brand-secondary); }
.test-tab h4 { font-size: 14px; color: var(--text-main); margin-bottom: 4px; font-weight: 600; }
.test-tab .meta { font-size: 12px; color: var(--text-muted); font-weight: 600;}
.status-icon { color: var(--border-light); font-size: 16px; transition: 0.3s; }
.test-tab.completed .status-icon { color: var(--success); }

.test-entry-area { flex: 1; display: flex; flex-direction: column; }
.test-card { background: var(--bg-card); border-radius: 8px; border: 1px solid var(--border-light); box-shadow: var(--shadow-sm); display: none; flex-direction: column; height: 100%; animation: fadeIn 0.3s ease; }
.test-card.active { display: flex; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

.test-header { background: #f8fafc; padding: 20px 25px; border-bottom: 1px solid var(--border-light); display: flex; justify-content: space-between; align-items: center; border-radius: 8px 8px 0 0; flex-shrink: 0; }
.test-title { font-size: 18px; font-weight: 700; color: var(--text-main); display: flex; align-items: center; gap: 10px; }
.test-meta-info { display: flex; gap: 20px; font-size: 13px; color: var(--text-muted); font-weight: 500; margin-top: 8px; }
.specimen-badge { background: #e0f2fe; color: #0284c7; padding: 4px 10px; border-radius: 4px; font-weight: 600; font-size: 12px; border: 1px solid #bae6fd; }

.form-scroll-area { flex: 1; overflow-y: auto; background: #fff; }
.params-table { width: 100%; border-collapse: collapse; }
.params-table th, .params-table td { padding: 15px 25px; border-bottom: 1px dashed var(--border-light); vertical-align: middle; }
.params-table th { font-size: 12px; text-transform: uppercase; color: var(--text-muted); background: #ffffff; border-bottom: 2px solid var(--border-light); text-align: left; position: sticky; top: 0; z-index: 10; }
.params-table tr:hover { background: #f8fafc; }

.input-control { width: 100%; padding: 10px 12px; border: 1px solid var(--border-light); border-radius: 6px; font-size: 14px; font-weight: 600; outline: none; transition: 0.2s; background: #fff; }
.input-control:focus { border-color: var(--brand-secondary); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1); }
.input-control.error { border-color: var(--danger); background: #fef2f2; }
select.input-control { cursor: pointer; appearance: none; background-image: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%2364748b%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E"); background-repeat: no-repeat; background-position: right 12px top 50%; background-size: 10px auto; padding-right: 30px; }

.flag-badge { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border-radius: 50%; font-weight: 700; font-size: 13px; margin-left: 15px; opacity: 0; transition: 0.3s; }
.flag-high { background: #fee2e2; color: var(--danger); border: 1px solid #fecaca; opacity: 1; }
.flag-low { background: #e0f2fe; color: var(--low-flag); border: 1px solid #bae6fd; opacity: 1; }
.input-high { color: var(--danger); border-color: var(--danger); background: #fef2f2; }
.input-low { color: var(--low-flag); border-color: var(--low-flag); background: #f0f9ff; }
.ref-range { font-size: 13px; color: var(--text-muted); font-family: monospace; }
.unit-label { font-size: 14px; color: var(--text-muted); font-weight: 500; margin-left: 10px; }

.remarks-area { width: 100%; padding: 15px 25px; border: none; font-size: 14px; outline: none; resize: vertical; min-height: 80px; font-family: inherit; background: transparent; border-top: 1px solid var(--border-light); margin-top: 15px;}
.remarks-area:focus { background: #f8fafc; }

.inner-actions { padding: 15px 25px; border-top: 1px solid var(--border-light); background: #f8fafc; text-align: right; border-radius: 0 0 8px 8px; flex-shrink: 0; }

.global-actions-bar { display: flex; justify-content: space-between; align-items: center; background: #fff; padding: 15px 25px; border-radius: 8px; border: 1px solid var(--border-light); box-shadow: var(--shadow-md); flex-shrink: 0; }
.btn { padding: 12px 24px; border-radius: 6px; font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.2s; border: none; display: inline-flex; align-items: center; gap: 8px; }
.btn-primary { background: var(--brand-secondary); color: #fff; }
.btn-primary:hover { background: #1d4ed8; }
.btn-success { background: var(--success); color: #fff; }
.btn-success:hover { background: #059669; }
.btn-outline { background: transparent; border: 1px solid var(--border-light); color: var(--text-main); }

#toast-container { position: fixed; top: 30px; right: 30px; z-index: 9999; display: flex; flex-direction: column; gap: 10px; }
.toast { background: #fff; border-left: 4px solid var(--brand-secondary); padding: 16px 20px; border-radius: 4px; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); display: flex; align-items: center; gap: 12px; min-width: 300px; transform: translateX(120%); transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
.toast.show { transform: translateX(0); }
.toast.success { border-left-color: var(--success); }
.toast.error { border-left-color: var(--danger); }
.toast-icon { font-size: 20px; color: var(--brand-secondary);}

.no-params-alert { padding: 20px; text-align: center; color: var(--danger); background: #fef2f2; border: 1px dashed #fca5a5; border-radius: 6px; margin: 20px; }
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="main-content" id="mainContent">
  <div class="container">
    
    <div class="workflow-tracker">
      <div class="step completed"><i class="fa-solid fa-check-circle"></i> Reception</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step completed"><i class="fa-solid fa-check-circle"></i> Sample Collection</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step active"><i class="fa-solid fa-microscope"></i> Testing & Results</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step"><i class="fa-solid fa-user-check"></i> Verification</div>
    </div>

    <div class="page-header">
      <h1><i class="fa-solid fa-vials" style="color: var(--brand-secondary);"></i> Results Entry Data Interface</h1>
    </div>

    <!-- Advanced Filter Bar -->
    <div class="filter-bar">
        <div class="form-group">
            <label>Collected From Date</label>
            <input type="date" id="filterDateFrom" class="input-control" value="<?= $is_all_backlog ? '' : htmlspecialchars($date_from_raw) ?>">
        </div>
        <div class="form-group">
            <label>Collected To Date</label>
            <input type="date" id="filterDateTo" class="input-control" value="<?= $is_all_backlog ? '' : htmlspecialchars($date_to_raw) ?>">
        </div>
        <div class="form-group large">
            <label>Select Patient (Pending Results)</label>
            <select id="patientSelect" class="input-control" style="width: 100%;">
                <option value="">-- View All Pending or Select Specific Patient --</option>
                <?php foreach($pending_patients as $pt): ?>
                    <option value="<?= $pt['patient_no'] ?>" <?= ($pt['patient_no'] === $target_patient_no) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($pt['patient_name'] . ' (' . $pt['patient_no'] . ')') ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div style="margin-top: 15px; display: flex; gap: 10px;">
            <button class="btn btn-primary" onclick="applyFilters()" style="padding: 10px 15px; font-size: 12px;">Apply Filter</button>
            <button class="btn btn-outline" onclick="clearFilters()" style="padding: 10px 15px; font-size: 12px;">View All Backlog</button>
        </div>
    </div>

    <?php if(empty($testing_queue['tests'])): ?>
        <div style="text-align: center; padding: 60px; background: #fff; border-radius: 8px; border: 1px dashed var(--border-light);">
          <i class="fa-solid fa-check-double" style="font-size: 40px; color: var(--success); margin-bottom: 15px;"></i>
          <h3 style="color: var(--text-main);">Queue is Empty</h3>
          <p style="color: var(--text-muted);">There are no pending lab requests waiting for result entry for this selection.</p>
        </div>
    <?php else: ?>

        <?php if(!empty($testing_queue['clinical_context'])): ?>
        <div class="clinical-alert">
          <i class="fa-solid fa-stethoscope icon-main"></i>
          <div class="clinical-alert-content">
            <h4>Clinical Context & Doctor's Notes</h4>
            <p>"<?= htmlspecialchars($testing_queue['clinical_context']['diagnosis_notes']) ?>"</p>
            <div class="meta">
              <span><i class="fa-solid fa-user-doctor"></i> Requested by: <?= htmlspecialchars($testing_queue['clinical_context']['doctor']) ?></span>
              <span><i class="fa-solid fa-circle-exclamation"></i> Priority: <?= htmlspecialchars($testing_queue['clinical_context']['priority']) ?></span>
            </div>
          </div>
        </div>
        <?php endif; ?>

        <div class="workspace">
          
          <div class="test-navigation">
            <div class="nav-filters">
              <div class="search-box">
                <i class="fa-solid fa-search"></i>
                <input type="text" id="tabSearch" placeholder="Search tests..." onkeyup="filterTabs()">
              </div>
            </div>
            
            <div class="nav-tabs" id="tabContainer">
              <?php foreach($testing_queue['tests'] as $index => $test): ?>
                <div class="test-tab <?= $index === 0 ? 'active' : '' ?>" 
                     id="tab-<?= $test['item_id'] ?>" 
                     data-testname="<?= strtolower($test['test_name']) ?>" 
                     data-dept="<?= $test['department'] ?>"
                     onclick="switchTest('<?= $test['item_id'] ?>')">
                  <div>
                    <h4><?= htmlspecialchars($test['test_name']) ?></h4>
                    <div class="meta"><?= htmlspecialchars($test['department']) ?></div>
                  </div>
                  <i class="fa-solid fa-circle-check status-icon" id="status-icon-<?= $test['item_id'] ?>"></i>
                </div>
              <?php endforeach; ?>
            </div>
          </div>

          <div class="test-entry-area">
            <form id="globalResultsForm" style="display: flex; flex-direction: column; height: 100%;">
              <input type="hidden" id="patient_no" value="<?= htmlspecialchars($target_patient_no) ?>">
              
              <?php foreach($testing_queue['tests'] as $index => $test): ?>
              <div class="test-card <?= $index === 0 ? 'active' : '' ?>" id="card-<?= $test['item_id'] ?>" data-reqid="<?= $test['item_id'] ?>">
                
                <div class="test-header">
                  <div>
                    <div class="test-title">
                      <?= htmlspecialchars($test['test_name']) ?>
                      <span class="specimen-badge"><?= htmlspecialchars($test['sample_type']) ?></span>
                    </div>
                    <div class="test-meta-info">
                      <span><i class="fa-solid fa-barcode"></i> <?= htmlspecialchars($test['barcode']) ?></span>
                      <span><i class="fa-solid fa-clock"></i> Collected: <?= htmlspecialchars($test['collected_at']) ?></span>
                    </div>
                  </div>
                </div>

                <div class="form-scroll-area">
                  <?php if(empty($test['parameters'])): ?>
                      <div class="no-params-alert">
                          <i class="fa-solid fa-triangle-exclamation" style="font-size: 24px; margin-bottom:10px;"></i>
                          <h4>No Parameters Mapped</h4>
                          <p>There are no test parameters mapped to this service in the database. Please configure the LIS parameter mapping.</p>
                      </div>
                  <?php else: ?>
                      <table class="params-table">
                        <thead>
                          <tr>
                            <th style="width: 35%">Parameter</th>
                            <th style="width: 35%">Result Value</th>
                            <th style="width: 20%">Reference Range</th>
                            <th style="width: 10%">Flag</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php foreach($test['parameters'] as $param): ?>
                          <tr class="param-row" data-paramid="<?= $param['parameter_id'] ?>">
                            <td style="font-weight: 600; color: var(--text-main);">
                              <?= htmlspecialchars($param['label']) ?>
                            </td>
                            <td>
                              <div style="display: flex; align-items: center;">
                                <?php if($param['type'] == 'numeric'): ?>
                                  <input type="number" step="0.01" 
                                         class="input-control result-val" 
                                         data-min="<?= $param['ref_min'] ?>" 
                                         data-max="<?= $param['ref_max'] ?>"
                                         onkeyup="evaluateRange(this)"
                                         onchange="evaluateRange(this)"
                                         placeholder="0.00" required style="max-width:140px;">
                                  <span class="unit-label"><?= htmlspecialchars($param['unit']) ?></span>
                                  <input type="hidden" class="ref-used-val" value="<?= $param['ref_min'] ?> - <?= $param['ref_max'] ?>">
                                
                                <?php elseif($param['type'] == 'options'): ?>
                                  <select class="input-control result-val" onchange="evaluateQualitative(this, '<?= htmlspecialchars($param['expected']) ?>')" required>
                                    <option value="">-- Select Result --</option>
                                    <?php foreach($param['options'] as $opt): ?>
                                      <option value="<?= htmlspecialchars($opt) ?>"><?= htmlspecialchars($opt) ?></option>
                                    <?php endforeach; ?>
                                  </select>
                                  <input type="hidden" class="ref-used-val" value="<?= htmlspecialchars($param['expected']) ?>">
                                
                                <?php else: ?>
                                    <input type="text" class="input-control result-val" required>
                                    <input type="hidden" class="ref-used-val" value="N/A">
                                <?php endif; ?>
                              </div>
                            </td>
                            <td class="ref-range">
                              <?php if($param['type'] == 'numeric'): ?>
                                <?= $param['ref_min'] ?> - <?= $param['ref_max'] ?> <?= htmlspecialchars($param['unit']) ?>
                              <?php elseif($param['type'] == 'options'): ?>
                                <?= htmlspecialchars($param['expected']) ?>
                              <?php endif; ?>
                            </td>
                            <td>
                              <span class="flag-badge"></span>
                              <input type="hidden" class="flag-val" value="Normal">
                            </td>
                          </tr>
                          <?php endforeach; ?>
                        </tbody>
                      </table>
                  <?php endif; ?>
                  
                  <textarea class="remarks-area test-remarks" placeholder="Add specific scientist remarks, methodology notes, or film review comments for <?= htmlspecialchars($test['test_name']) ?>..."></textarea>
                </div>
                
                <div class="inner-actions">
                   <button type="button" class="btn btn-primary" onclick="saveAndNext('<?= $test['item_id'] ?>')">
                     Save & Next Test <i class="fa-solid fa-arrow-right"></i>
                   </button>
                </div>
              </div>
              <?php endforeach; ?>
            </form>
          </div>
        </div>

        <div class="global-actions-bar">
          <button class="btn btn-outline" onclick="window.history.back()"><i class="fa-solid fa-arrow-left"></i> Exit to Dashboard</button>
          <button class="btn btn-success" id="btnSubmitAll" onclick="submitAllResults()">
            <i class="fa-solid fa-paper-plane"></i> Submit All Finished Results for Verification
          </button>
        </div>
    <?php endif; ?>

    <div class="enterprise-footer">
      Laboratory Management System v2.4.1 | Powered by Afritechs Gh Ltd
    </div>

  </div>
</div>

<div id="toast-container"></div>

<!-- Required Scripts -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="../../assets/js/lab_results.js"></script>

</body>
</html>