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

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

// ==============================================================================
// 1. QUEUE FILTERING (AWAITING VERIFICATION)
// ==============================================================================
$filter_date_raw = $_GET['filter_date'] ?? date('Y-m-d');
$is_all_backlog = ($filter_date_raw === 'ALL');

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

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

// A. Fetch distinct patients with 'Awaiting Verification' tests
$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 = 'Awaiting Verification' AND clr.service_id IS NOT NULL
";

if (!$is_all_backlog) {
    $qPatients .= " AND clr.completed_at >= '$date_from_sql' AND clr.completed_at <= '$date_to_sql'";
}
$qPatients .= " ORDER BY clr.completed_at DESC";

$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 TEST RESULTS & AUDIT LOGS
// ==============================================================================
if ($target_patient_no) {
    
    // Fetch Tests mapped to this patient
    $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,
            clr.notes AS doctor_notes, clr.scientist_remarks, clr.completed_at,
            CONCAT('Dr. ', COALESCE(req_s.first_name, 'Unknown'), ' ', COALESCE(req_s.last_name, '')) AS requested_by,
            CONCAT(COALESCE(comp_s.first_name, 'Scientist'), ' ', COALESCE(comp_s.last_name, '')) AS tested_by,
            p.first_name, p.last_name, p.patient_no, TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) AS age,
            g.gender_name AS gender
        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 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
        LEFT JOIN staff req_s ON clr.requested_by = req_s.staff_id
        LEFT JOIN staff comp_s ON clr.completed_by = comp_s.staff_id
        WHERE clr.patient_no = ? AND clr.status = 'Awaiting Verification' AND clr.service_id IS NOT NULL
    ";
    
    if (!$is_all_backlog) {
        $qTests .= " AND clr.completed_at >= '$date_from_sql' AND clr.completed_at <= '$date_to_sql'";
    }
    $qTests .= " ORDER BY clr.completed_at DESC";
    
    $stmtTests = $conn->prepare($qTests);
    $stmtTests->bind_param("s", $target_patient_no);
    $stmtTests->execute();
    $resTests = $stmtTests->get_result();
    
    // Fetch Results for each test[cite: 3]
    $qParams = "
        SELECT 
            lp.parameter_name, lp.unit_of_measure, 
            res.result_value, res.reference_range_used, res.result_flag
        FROM clinical_lab_results res
        JOIN lab_parameters lp ON res.parameter_id = lp.id
        WHERE res.request_id = ?
        ORDER BY lp.id ASC
    ";
    $stmtParams = $conn->prepare($qParams);

    while ($row = $resTests->fetch_assoc()) {
        $test_data = [
            'item_id' => $row['request_id'],
            'patient_name' => trim($row['first_name'] . ' ' . $row['last_name']),
            'hospital_id' => $row['patient_no'],
            'age' => $row['age'] ?? 0,
            'gender' => $row['gender'] ?? 'Unknown',
            'test_name' => $row['test_name'],
            'department' => $row['department'],
            'barcode' => $row['barcode'] ?? 'N/A',
            'date_tested' => !empty($row['completed_at']) ? date('Y-m-d', strtotime($row['completed_at'])) : 'N/A',
            'audit' => [
                'requested_by' => $row['requested_by'],
                'request_notes' => $row['doctor_notes'] ?? 'No clinical notes provided.',
                'collected_by' => 'Phlebotomy Unit',
                'collected_at' => !empty($row['collected_at']) ? date('d-M-Y h:i A', strtotime($row['collected_at'])) : 'N/A',
                'tested_by' => $row['tested_by'],
                'tested_at' => !empty($row['completed_at']) ? date('d-M-Y h:i A', strtotime($row['completed_at'])) : 'N/A',
                'machine' => 'LIS Connected Interface',
                'tester_remarks' => $row['scientist_remarks'] ?? 'No remarks provided by testing scientist.'
            ],
            'results' => []
        ];

        // Fetch actual entered results[cite: 3]
        $stmtParams->bind_param("i", $row['request_id']);
        $stmtParams->execute();
        $resParams = $stmtParams->get_result();
        
        while ($param = $resParams->fetch_assoc()) {
            $test_data['results'][] = [
                'parameter' => $param['parameter_name'],
                'value' => $param['result_value'],
                'unit' => $param['unit_of_measure'],
                'ref' => $param['reference_range_used'],
                'flag' => $param['result_flag'] ?? 'Normal',
                'previous' => null 
            ];
        }
        $verification_queue[] = $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>Verify Results | Tier 1 Laboratory System</title>
<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">
<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;
  --bg-app: #f4f7f9;
  --bg-card: #ffffff;
  --brand-secondary: #2563eb;
  --success: #10b981;
  --danger: #ef4444;
  --warning: #f59e0b;
  --low-flag: #3b82f6; 
  --border-light: #e2e8f0;
  --text-main: #0f172a;
  --text-muted: #64748b;
  --transition-speed: 0.35s;
  --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

* { 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; }
.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); }

.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; }

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

.test-navigation { width: 380px; 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; background: #fff;}
.search-box input:focus { border-color: var(--brand-secondary); box-shadow: 0 0 0 3px rgba(37,99,235,0.1); }

.batch-bar { padding: 12px 20px; border-bottom: 1px solid var(--border-light); background: #fff; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; }
.custom-checkbox { width: 16px; height: 16px; cursor: pointer; accent-color: var(--brand-secondary); }
.master-label { display: flex; align-items: center; gap: 10px; font-size: 13px; font-weight: 700; color: var(--text-main); cursor: pointer; }
.btn-batch-verify { background: var(--success); color: #fff; border: none; padding: 6px 12px; border-radius: 4px; font-size: 12px; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; transition: 0.2s;}
.btn-batch-verify:hover { background: #059669; }
.btn-batch-verify:disabled { background: #94a3b8; cursor: not-allowed; }

.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; gap: 12px; align-items: flex-start; }
.test-tab:hover { background: #f8fafc; }
.test-tab.active { background: #eff6ff; border-left-color: var(--brand-secondary); }
.tab-content { flex: 1; }
.tab-content h4 { font-size: 14px; color: var(--text-main); margin-bottom: 4px; font-weight: 600; }
.tab-content .meta { font-size: 12px; color: var(--text-muted); margin-bottom: 2px;}
.critical-dot { display: inline-block; width: 8px; height: 8px; background: var(--danger); border-radius: 50%; animation: pulse 2s infinite;}

@keyframes pulse { 0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7); } 70% { transform: scale(1); box-shadow: 0 0 0 6px rgba(239, 68, 68, 0); } 100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); } }

.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); } }

.audit-strip { background: #f8fafc; border-bottom: 1px solid var(--border-light); padding: 15px 25px; display: flex; justify-content: space-between; border-radius: 8px 8px 0 0; flex-shrink: 0; }
.audit-node { display: flex; flex-direction: column; gap: 4px; position: relative; flex: 1; padding-left: 20px;}
.audit-node::before { content: ''; position: absolute; left: 0; top: 5px; width: 8px; height: 8px; border-radius: 50%; background: var(--success); }
.audit-node:not(:last-child)::after { content: ''; position: absolute; left: 3px; top: 15px; width: 2px; height: 30px; background: var(--border-light); }
.node-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-muted); font-weight: 700; }
.node-person { font-size: 13px; font-weight: 600; color: var(--text-main); }
.node-time { font-size: 11px; color: var(--text-muted); }

.test-header-meta { padding: 20px 25px; border-bottom: 1px solid var(--border-light); flex-shrink: 0; }
.test-header-meta h2 { font-size: 20px; color: var(--text-main); margin-bottom: 4px; }

.results-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; }
.val-normal { font-weight: 600; color: var(--text-main); font-size: 15px; }
.val-high { font-weight: 700; color: var(--danger); font-size: 15px; }
.val-low { font-weight: 700; color: var(--low-flag); font-size: 15px; }
.flag-badge { display: inline-flex; align-items: center; justify-content: center; padding: 2px 8px; border-radius: 4px; font-weight: 700; font-size: 12px; }
.badge-h { background: #fee2e2; color: var(--danger); border: 1px solid #fecaca; }
.badge-l { background: #e0f2fe; color: var(--low-flag); border: 1px solid #bae6fd; }
.badge-n { color: var(--text-muted); font-weight: 500; }

.reviewer-section { padding: 15px 25px; background: #fff; border-top: 1px solid var(--border-light); flex-shrink: 0; }
.sci-notes { background: #f1f5f9; padding: 12px 15px; border-radius: 6px; border-left: 4px solid var(--text-muted); margin-bottom: 15px; font-size: 13px; color: var(--text-main); }
.actions-bar { display: flex; justify-content: space-between; align-items: center; background: #f8fafc; padding: 15px 25px; border-radius: 0 0 8px 8px; border-top: 1px solid var(--border-light); flex-shrink: 0; }
.btn { padding: 10px 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-danger { background: #fff; color: var(--danger); border: 1px solid var(--danger); }
.btn-outline { background: transparent; border: 1px solid var(--border-light); color: var(--text-main); }

/* Modals */
.modal-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15, 23, 42, 0.7); backdrop-filter: blur(2px); z-index: 2000; justify-content: center; align-items: center; }
.modal-box { background: #fff; padding: 30px; border-radius: 8px; width: 90%; max-width: 420px; text-align: center; box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
.pin-input { font-size: 24px; letter-spacing: 8px; text-align: center; font-weight: 700; width: 100%; padding: 15px; border: 1px solid var(--border-light); border-radius: 6px; outline: none; margin-bottom: 20px;}
.pin-input:focus { border-color: var(--success); box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2); }
.loader { display: none; border: 3px solid #f3f3f3; border-top: 3px solid var(--success); border-radius: 50%; width: 36px; height: 36px; animation: spin 1s linear infinite; margin: 0 auto 15px auto; }
#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); }
.enterprise-footer { text-align: center; font-size: 12px; color: var(--text-muted); font-weight: 500; flex-shrink: 0; padding-top:15px; padding-bottom:15px;}
</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> Collection</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step completed"><i class="fa-solid fa-check-circle"></i> Testing</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step active"><i class="fa-solid fa-user-check"></i> Formal Verification</div>
    </div>

    <div class="page-header">
      <h1><i class="fa-solid fa-file-signature" style="color: var(--brand-secondary);"></i> Pathologist Verification</h1>
    </div>

    <!-- Advanced Filter Bar -->
    <div class="filter-bar">
        <div class="form-group">
            <label>Filter By Test Completion Date (Optional)</label>
            <input type="date" id="filterDate" class="input-control" value="<?= $is_all_backlog ? '' : htmlspecialchars($filter_date_raw) ?>" onchange="applyFilters()">
        </div>
        <div class="form-group large">
            <label>Select Patient (Pending Verification)</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>

    <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 patient or test..." onkeyup="filterTabs()">
          </div>
        </div>

        <div class="batch-bar">
          <label class="master-label">
            <input type="checkbox" id="masterVerifyCheck" class="custom-checkbox" onchange="toggleAllVerify(this)"> Select All Filtered
          </label>
          <button class="btn-batch-verify" id="btnBatchVerify" onclick="initiateBatchAuth()" disabled>
            <i class="fa-solid fa-signature"></i> Batch Verify
          </button>
        </div>
        
        <div class="nav-tabs" id="tabContainer">
          <?php if(empty($verification_queue)): ?>
              <div style="padding: 20px; text-align: center; color: var(--text-muted); font-size: 13px;">No tests awaiting verification for this criteria.</div>
          <?php endif; ?>

          <?php foreach($verification_queue as $index => $item): ?>
            <?php 
                $has_flags = false;
                foreach($item['results'] as $res) { if($res['flag'] != 'Normal') { $has_flags = true; break; } }
            ?>
            <div class="test-tab <?= $index === 0 ? 'active' : '' ?>" 
                 id="tab-<?= $item['item_id'] ?>" 
                 data-search="<?= strtolower($item['patient_name'] . ' ' . $item['test_name']) ?>"
                 data-date="<?= $item['date_tested'] ?>"
                 data-patient="<?= htmlspecialchars($item['patient_name']) ?>">
              
              <div style="padding-top: 2px;">
                <input type="checkbox" class="custom-checkbox verify-check" value="<?= $item['item_id'] ?>" onchange="syncMasterCheckbox()">
              </div>
              
              <div class="tab-content" onclick="switchTest('<?= $item['item_id'] ?>')">
                <h4><?= htmlspecialchars($item['patient_name']) ?></h4>
                <div class="meta" style="color: var(--brand-primary); font-size: 13px;">
                    <?= htmlspecialchars($item['test_name']) ?>
                </div>
                <div class="meta">
                    <?= htmlspecialchars($item['hospital_id']) ?> | <?= htmlspecialchars($item['date_tested']) ?>
                </div>
              </div>

              <?php if($has_flags): ?>
                <div style="padding-top: 2px;"><span class="critical-dot" title="Contains Abnormal Results"></span></div>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="test-entry-area">
        <?php foreach($verification_queue as $index => $item): ?>
        <div class="test-card <?= $index === 0 ? 'active' : '' ?>" id="card-<?= $item['item_id'] ?>">
          
          <div class="audit-strip">
            <div class="audit-node">
                <span class="node-title">Requested By</span>
                <span class="node-person"><i class="fa-solid fa-user-doctor" style="color: var(--text-muted); margin-right: 4px;"></i> <?= htmlspecialchars($item['audit']['requested_by']) ?></span>
                <span class="node-time" title="<?= htmlspecialchars($item['audit']['request_notes']) ?>">Hover for clinical notes</span>
            </div>
            <div class="audit-node">
                <span class="node-title">Collected By</span>
                <span class="node-person"><i class="fa-solid fa-syringe" style="color: var(--text-muted); margin-right: 4px;"></i> <?= htmlspecialchars($item['audit']['collected_by']) ?></span>
                <span class="node-time"><?= htmlspecialchars($item['audit']['collected_at']) ?></span>
            </div>
            <div class="audit-node">
                <span class="node-title">Tested By</span>
                <span class="node-person"><i class="fa-solid fa-microscope" style="color: var(--text-muted); margin-right: 4px;"></i> <?= htmlspecialchars($item['audit']['tested_by']) ?></span>
                <span class="node-time"><?= htmlspecialchars($item['audit']['tested_at']) ?></span>
            </div>
          </div>

          <div class="test-header-meta">
            <h2><?= htmlspecialchars($item['test_name']) ?></h2>
            <div>
                Patient: <?= htmlspecialchars($item['patient_name']) ?> | Barcode: <?= htmlspecialchars($item['barcode']) ?> | Interface: <?= htmlspecialchars($item['audit']['machine']) ?>
            </div>
          </div>

          <div class="results-scroll-area">
            <?php if(empty($item['results'])): ?>
                <div style="padding: 30px; text-align: center; color: var(--danger); font-weight: 600;">No parameters recorded for this test. Rejection recommended.</div>
            <?php else: ?>
                <table class="params-table">
                  <thead>
                    <tr>
                      <th style="width: 30%">Parameter</th>
                      <th style="width: 20%">Result Value</th>
                      <th style="width: 15%">Flag</th>
                      <th style="width: 35%">Reference Range Used</th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php foreach($item['results'] as $res): ?>
                    <tr>
                      <td style="font-weight: 600; color: var(--text-main);">
                        <?= htmlspecialchars($res['parameter']) ?>
                      </td>
                      <td>
                        <?php 
                          $val_class = 'val-normal';
                          $badge = '<span class="flag-badge badge-n">-</span>';
                          
                          // Handle abnormal flag styling
                          $flg = strtolower($res['flag']);
                          if($flg == 'high' || $flg == 'abnormal' || strpos($flg, 'positive') !== false) { 
                              $val_class = 'val-high'; 
                              $badge = '<span class="flag-badge badge-h">'. htmlspecialchars($res['flag']) .'</span>'; 
                          }
                          if($flg == 'low') { 
                              $val_class = 'val-low'; 
                              $badge = '<span class="flag-badge badge-l">L</span>'; 
                          }
                        ?>
                        <span class="<?= $val_class ?>"><?= htmlspecialchars($res['value']) ?></span>
                        <span style="font-size: 13px; color: var(--text-muted); margin-left: 4px;"><?= htmlspecialchars($res['unit']) ?></span>
                      </td>
                      <td><?= $badge ?></td>
                      <td class="ref-col"><?= htmlspecialchars($res['ref']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                  </tbody>
                </table>
            <?php endif; ?>
          </div>
          
          <div class="reviewer-section">
            <div class="sci-notes">
                <strong><i class="fa-solid fa-comment-dots"></i> Testing Scientist Remarks:</strong><br>
                <?= htmlspecialchars($item['audit']['tester_remarks']) ?>
            </div>
            <label style="font-size: 13px; font-weight: 600; color: var(--text-muted); display: block; margin-bottom: 8px;">Pathologist / Reviewer Conclusion (Optional):</label>
            <textarea id="review-notes-<?= $item['item_id'] ?>" class="input-control" rows="2" placeholder="Enter clinical interpretation, recommendations, or authorize release..."></textarea>
          </div>

          <div class="actions-bar">
            <button class="btn btn-danger" onclick="initiateRejection('<?= $item['item_id'] ?>')">
              <i class="fa-solid fa-rotate-left"></i> Reject & Request Re-test
            </button>
            <button class="btn btn-primary" onclick="initiateSingleAuth('<?= $item['item_id'] ?>')">
              <i class="fa-solid fa-file-signature"></i> Verify & Release
            </button>
          </div>

        </div>
        <?php endforeach; ?>
        
        <div class="test-card <?= empty($verification_queue) ? 'active' : '' ?>" id="emptyCanvas" style="<?= empty($verification_queue) ? 'display:flex;' : 'display:none;' ?> align-items: center; justify-content: center; text-align: center; padding: 50px;">
           <i class="fa-solid fa-clipboard-check" style="font-size: 60px; color: var(--border-light); margin-bottom: 20px;"></i>
           <h3 style="color: var(--text-main);">Queue is Empty</h3>
           <p style="color: var(--text-muted);">No results match your current filters, or all have been verified.</p>
        </div>

      </div>
    </div>

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

  </div>
</div>

<div class="modal-overlay" id="authModal">
  <div class="modal-box">
    <div id="authStep1">
      <i class="fa-solid fa-shield-halved" style="font-size: 40px; color: var(--success); margin-bottom: 15px;"></i>
      <h3 style="color: var(--text-main);">Verify & Release Results</h3>
      
      <div id="authContextMsg" style="background: #f8fafc; border: 1px solid var(--border-light); padding: 12px; border-radius: 6px; margin-bottom: 20px; font-size: 14px;">
         You are verifying <strong id="authTestCount" style="color: var(--brand-secondary);">1</strong> test(s) for <strong id="authPatientCount" style="color: var(--brand-secondary);">1</strong> patient(s).
      </div>

      <p style="font-size: 13px; margin-bottom: 15px;">By proceeding, you confirm these results are clinically valid and authorize their release to the EMR.</p>
      
      <input type="hidden" id="authTargetData"> 
      
      <div style="display: flex; justify-content: center; gap: 15px;">
        <button class="btn" style="background: transparent; border: 1px solid var(--border-light); color: var(--text-main);" onclick="closeModal('authModal')">Cancel</button>
        <button class="btn btn-primary" onclick="executeAuth()" style="background: var(--success);">Sign & Release</button>
      </div>
    </div>
  </div>
</div>

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

<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/verifyLabTest.js"></script>

</body>
</html>