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

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

$msg = '';
$error = '';

// ==============================================================================
// 1. DYNAMICALLY FETCH SAMPLE SOURCES FROM DICTIONARY
// ==============================================================================
$sample_sources = [];
$qSources = "SELECT DISTINCT default_source FROM lab_sample_types WHERE is_active = 1 AND default_source IS NOT NULL AND default_source != '' ORDER BY default_source ASC";
$resSources = $conn->query($qSources);
if ($resSources) {
    while ($row = $resSources->fetch_assoc()) {
        $sample_sources[] = $row['default_source'];
    }
}
if (empty($sample_sources)) {
    $sample_sources = ['Venous Blood', 'Urine', 'Swab', 'Stool', 'CSF', 'Aspirate'];
}

// ==============================================================================
// 2. FETCH THE NEXT PATIENT IN THE QUEUE (Strictly 'Awaiting Sample' Status)
// ==============================================================================
$collection_queue = [];
$target_patient_no = $_GET['patient_no'] ?? null;

// Look for 'Awaiting Sample' because processLabQueue.php sets it to that upon acceptance
if (!$target_patient_no) {
    $qFirst = "SELECT patient_no FROM clinical_lab_requests WHERE status = 'Awaiting Sample' ORDER BY priority ASC, request_date ASC LIMIT 1";
    $resFirst = $conn->query($qFirst);
    if ($resFirst && $resFirst->num_rows > 0) {
        $target_patient_no = $resFirst->fetch_assoc()['patient_no'];
    }
}

if ($target_patient_no) {
    // A. Fetch Patient Clinical Context (Directly linking requested_by to staff table)
    $qContext = "
        SELECT 
            p.first_name, p.last_name, 
            clr.notes AS diagnosis_notes, clr.priority,
            CONCAT('Dr. ', COALESCE(s.first_name, 'Unknown'), ' ', COALESCE(s.last_name, '')) AS doctor
        FROM clinical_lab_requests clr
        JOIN patient p ON clr.patient_no = p.patient_no
        LEFT JOIN staff s ON clr.requested_by = s.staff_id
        WHERE clr.patient_no = ? AND clr.status = 'Awaiting Sample'
        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) {
        $collection_queue['clinical_context'] = [
            'doctor' => $ctxRes['doctor'] ?? 'Unassigned',
            'diagnosis_notes' => $ctxRes['diagnosis_notes'] ?? 'No clinical notes provided.',
            'priority' => $ctxRes['priority']
        ];
    }

    // B. High-Performance Query: Fetch tests AND their mapped samples in ONE query
    $qSamples = "
        SELECT 
            clr.id AS request_id,
            clr.service_id,
            COALESCE(sc.service_name, CONCAT('Unmapped Service ID: ', clr.service_id)) AS test_name,
            COALESCE(lsd.sub_dept_name, d.department_name, 'Laboratory') AS department,
            lst.id AS sample_id,
            lst.sample_name,
            lst.container_type,
            lst.container_color,
            lst.required_volume,
            lst.default_source
        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 lab_test_samples lts ON clr.service_id = lts.service_id
        LEFT JOIN lab_sample_types lst ON lts.sample_id = lst.id AND lst.is_active = 1
        WHERE clr.patient_no = ? AND clr.status = 'Awaiting Sample'
        ORDER BY clr.id ASC
    ";
    
    $stmtSamples = $conn->prepare($qSamples);
    $stmtSamples->bind_param("s", $target_patient_no);
    $stmtSamples->execute();
    $resSamples = $stmtSamples->get_result();
    
    $collection_queue['pending_samples'] = [];
    
    while ($row = $resSamples->fetch_assoc()) {
        $req_id = $row['request_id'];
        
        if (!isset($collection_queue['pending_samples'][$req_id])) {
            $collection_queue['pending_samples'][$req_id] = [
                'request_id' => $req_id,
                'service_id' => $row['service_id'],
                'test_name' => $row['test_name'],
                'department' => $row['department'],
                'mapped_samples' => []
            ];
        }
        
        if (!empty($row['sample_id'])) {
            $collection_queue['pending_samples'][$req_id]['mapped_samples'][] = [
                'sample_id' => $row['sample_id'],
                'sample_name' => $row['sample_name'],
                'container_type' => $row['container_type'],
                'container_color' => $row['container_color'],
                'required_volume' => $row['required_volume'],
                'default_source' => $row['default_source']
            ];
        }
    }
    $stmtSamples->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample Collection | 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">

<style>
:root {
  --sidebar-width: 300px;
  --bg-app: #f4f7f9;
  --bg-card: #ffffff;
  --brand-secondary: #2563eb;
  --success: #10b981;
  --danger: #ef4444;
  --warning: #f59e0b;
  --warning-light: #fefce8;
  --warning-border: #fef08a;
  --border-light: #e2e8f0;
  --text-main: #0f172a;
  --text-muted: #64748b;
  --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; }

.main-content { margin-left: var(--sidebar-width); padding: 30px; min-height: 100vh; display: flex; flex-direction: column; }
@media (max-width: 1024px) { .main-content { margin-left: 0; padding: 20px; } }
.container { max-width: 1400px; margin: 0 auto; width: 100%; display: flex; flex-direction: column; flex: 1; }

.workflow-tracker { display: flex; align-items: center; gap: 15px; margin-bottom: 20px; background: var(--bg-card); padding: 12px 25px; border-radius: 8px; box-shadow: var(--shadow-sm); border: 1px solid var(--border-light); }
.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); font-size: 12px; }

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

.card.table-card { background: var(--bg-card); border-radius: 8px; border: 1px solid var(--border-light); box-shadow: var(--shadow-sm); overflow: hidden; margin-bottom: 20px; }
.card-header { padding: 15px 20px; border-bottom: 1px solid var(--border-light); background: #f8fafc; font-weight: 600; display: flex; justify-content: space-between; align-items: center; color: var(--text-main); }

.table-wrapper { overflow-x: auto; width: 100%; }
table { width: 100%; border-collapse: collapse; text-align: left; }
th, td { padding: 15px; border-bottom: 1px solid var(--border-light); vertical-align: top; }
th { font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-muted); background: #ffffff; }
td { font-size: 13px; font-weight: 500; }
tr:last-child td { border-bottom: none; }
tr:hover { background: #f8fafc; }

.custom-checkbox { width: 16px; height: 16px; cursor: pointer; accent-color: var(--brand-secondary); margin-top: 4px; }
.input-control { width: 100%; padding: 8px 10px; border: 1px solid var(--border-light); border-radius: 6px; font-size: 13px; outline: none; transition: all 0.2s; background: #f8fafc; font-family: inherit; }
.input-control:focus { border-color: var(--brand-secondary); background: #ffffff; box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1); }
.input-control.error-border { border-color: var(--danger); background: #fef2f2; }
textarea.input-control { resize: vertical; min-height: 40px; }
.status-select.failed { color: var(--danger); font-weight: 700; border-color: var(--danger); }

.unmapped-test { color: #dc2626; font-weight: 700; background: #fef2f2; padding: 4px 8px; border-radius: 4px; border: 1px dashed #fecaca; font-size:12px;}

.color-dot { width: 12px; height: 12px; border-radius: 50%; border: 2px solid #fff; box-shadow: 0 0 0 1px var(--border-light); }

.card.remarks-card { background: var(--bg-card); border-radius: 8px; border: 1px solid var(--border-light); box-shadow: var(--shadow-sm); margin-bottom: 20px; }

.actions-bar { 
    display: flex; justify-content: space-between; align-items: center; background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(8px); padding: 15px 25px; border-radius: 12px; border: 1px solid var(--border-light); 
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.08); position: sticky; bottom: 20px; z-index: 100; margin-bottom: 20px;
}
.btn { padding: 10px 20px; border-radius: 6px; font-size: 13px; 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-outline { background: #fff; border: 1px solid var(--border-light); color: var(--text-main); }
.btn-outline:hover { background: #f1f5f9; }
.btn-print { background: var(--text-main); color: #fff; padding: 6px 14px; font-size: 12px; border-radius: 4px; border: none;}
.btn-print:hover { background: #334155; }

.alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; font-weight: 600; display:flex; align-items:center; gap:10px;}
.alert-error { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

#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: var(--shadow-md); 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);}

.strict-mapping-box { border: 1px solid var(--border-light); border-radius: 6px; padding: 8px; background: #f8fafc; font-size: 12px; }
.mapped-item { display: flex; align-items: flex-start; gap: 10px; padding: 6px 0; border-bottom: 1px solid #e2e8f0; }
.mapped-item:last-child { border-bottom: none; padding-bottom: 0; }
</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 & Acceptance</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step active"><i class="fa-solid fa-vial"></i> Sample Collection</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step"><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>

    <?php if(!empty($error)): ?><div class="alert alert-error"><i class="fa-solid fa-triangle-exclamation"></i> <?= $error ?></div><?php endif; ?>

    <?php if(empty($collection_queue['pending_samples'])): ?>
        <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 sample collection.</p>
          <a href="lab_request_and_recommendations.php" class="btn btn-outline" style="margin-top:20px;">Return to Reception</a>
        </div>
    <?php else: ?>

        <?php if(!empty($collection_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($collection_queue['clinical_context']['diagnosis_notes']) ?>"</p>
            <div class="meta">
              <span><i class="fa-solid fa-user-doctor"></i> Requested by: <?= htmlspecialchars($collection_queue['clinical_context']['doctor']) ?></span>
              <span><i class="fa-solid fa-circle-exclamation"></i> Priority: <?= htmlspecialchars($collection_queue['clinical_context']['priority']) ?></span>
            </div>
          </div>
        </div>
        <?php endif; ?>

        <div class="card table-card">
          <div class="card-header">
            <span><i class="fa-solid fa-flask" style="color: var(--brand-secondary); margin-right: 8px;"></i> Collection for Patient: <?= htmlspecialchars($target_patient_no) ?></span>
            <button class="btn-print" onclick="window.print()"><i class="fa-solid fa-barcode"></i> Print Barcodes</button>
          </div>
          
          <div class="table-wrapper">
            <table id="collectionTable">
              <thead>
                <tr>
                  <th style="width: 4%; text-align: center;">
                    <input type="checkbox" class="custom-checkbox" id="masterCheckbox" onchange="toggleAllRows(this)" checked title="Select All Filtered">
                  </th>
                  <th style="width: 25%">Test Details</th>
                  <th style="width: 30%">Required Sample(s) - Strict Mapping</th>
                  <th style="width: 12%">Status</th>
                  <th style="width: 12%">System Barcode</th>
                  <th style="width: 17%">Collection Notes</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach($collection_queue['pending_samples'] as $sample): ?>
                <?php 
                    $test_name_html = htmlspecialchars($sample['test_name']);
                    if (strpos($sample['test_name'], 'Unmapped Service ID') !== false) {
                        $test_name_html = "<span class='unmapped-test'><i class='fa-solid fa-triangle-exclamation'></i> " . $test_name_html . "</span>";
                    }
                ?>
                <tr class="sample-row" data-reqid="<?= $sample['request_id'] ?>">
                  <td style="text-align: center;">
                    <input type="checkbox" class="custom-checkbox row-checkbox" checked onchange="toggleSingleRow(this)">
                  </td>

                  <td>
                    <div style="font-weight: 600; color: var(--text-main);"><?= $test_name_html ?></div>
                    <div style="font-size: 11px; font-weight: 600; color: var(--text-muted); margin-top: 4px; text-transform: uppercase;"><?= htmlspecialchars($sample['department']) ?></div>
                  </td>
                  
                  <td>
                    <?php if(empty($sample['mapped_samples'])): ?>
                        <div class="strict-mapping-box" style="border-color:#fecaca; background:#fef2f2;">
                            <span style="color:#dc2626; font-weight:700;"><i class="fa-solid fa-triangle-exclamation"></i> No Sample Mapped</span>
                            <br>Please configure in LIS Mapping Engine.
                            <input type="hidden" class="mapped-sample-id-input" value="0" data-source="">
                        </div>
                    <?php else: ?>
                        <div class="strict-mapping-box">
                            <?php foreach($sample['mapped_samples'] as $index => $mapped): ?>
                                <div class="mapped-item">
                                    <input type="radio" name="selected_sample_<?= $sample['request_id'] ?>" value="<?= $mapped['sample_id'] ?>" data-source="<?= htmlspecialchars($mapped['default_source']) ?>" class="mapped-sample-id-input" <?= $index === 0 ? 'checked' : '' ?> style="accent-color:var(--brand-secondary); cursor:pointer; margin-top:2px;">
                                    <div class="color-dot" style="background-color: <?= htmlspecialchars($mapped['container_color']) ?>; margin-top:3px;"></div>
                                    <div>
                                        <span style="font-weight: 600; color: var(--text-main);"><?= htmlspecialchars($mapped['sample_name']) ?> <span style="font-weight: 400;">(<?= htmlspecialchars($mapped['container_type']) ?>)</span></span>
                                        <div style="color:var(--text-muted); font-size:11px; margin-top: 2px;">
                                            Volume: <strong><?= htmlspecialchars($mapped['required_volume']) ?></strong> &nbsp;|&nbsp; Source: <strong><?= htmlspecialchars($mapped['default_source']) ?></strong>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                  </td>
                  
                  <td>
                    <select class="input-control status-select" onchange="handleStatusDropdown(this)">
                      <option value="Collected">✅ Collected</option>
                      <option value="Failed">❌ Failed / Skipped</option>
                    </select>
                  </td>
                  
                  <td>
                    <input type="text" class="input-control barcode-input" value="<?= htmlspecialchars('SMP-'.date('Ymd').'-'.$sample['request_id']) ?>" readonly style="background: #f1f5f9; cursor: not-allowed; font-family: monospace; font-weight: 700; color: var(--brand-primary); text-align: center; padding-left: 5px; padding-right: 5px;">
                  </td>

                  <td>
                    <textarea class="input-control notes-input" rows="2" placeholder="Sample remarks..."></textarea>
                    <div class="error-msg" style="display: none; color: var(--danger); font-size: 11px; margin-top: 4px; font-weight: 600;">Required if failed.</div>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>

        <div class="card remarks-card">
          <div style="padding: 15px 20px; border-bottom: 1px solid var(--border-light); background: #f8fafc;">
            <span style="font-size: 13px; font-weight: 600; color: var(--text-muted); text-transform: uppercase;"><i class="fa-solid fa-comment-medical" style="color: var(--brand-secondary); margin-right: 6px;"></i> Overall Personnel Remarks & Recommendations</span>
          </div>
          <div style="padding: 15px;">
            <textarea id="globalRecommendation" class="input-control" rows="2" placeholder="Enter overall observations regarding the patient's condition during the draw, fasting status, or specific instructions for the testing scientist..."></textarea>
          </div>
        </div>

        <div class="actions-bar">
          <a href="lab_request_and_recommendations.php" class="btn btn-outline"><i class="fa-solid fa-arrow-left"></i> Back to Reception</a>
          <button class="btn btn-primary" id="btnSubmitCollection" onclick="submitCollection()"><i class="fa-solid fa-check-double"></i> Confirm & Save Collection</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>

<script>
function showToast(message, type = 'success') {
  const container = document.getElementById('toast-container');
  const toast = document.createElement('div');
  toast.className = `toast ${type}`;
  const iconClass = type === 'success' ? 'fa-check-circle' : 'fa-circle-exclamation';
  toast.innerHTML = `<i class="fa-solid ${iconClass} toast-icon"></i><span class="toast-msg">${message}</span>`;
  container.appendChild(toast);
  setTimeout(() => toast.classList.add('show'), 10);
  setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 3500);
}

function toggleAllRows(masterCheckbox) {
  const visibleCheckboxes = document.querySelectorAll('.sample-row .row-checkbox');
  visibleCheckboxes.forEach(cb => {
    cb.checked = masterCheckbox.checked;
    applyRowState(cb.closest('tr'), cb.checked);
  });
}

function toggleSingleRow(checkbox) {
  applyRowState(checkbox.closest('tr'), checkbox.checked);
  evaluateMasterCheckbox();
}

function handleStatusDropdown(selectElement) {
  const row = selectElement.closest('tr');
  const checkbox = row.querySelector('.row-checkbox');
  const isCollected = (selectElement.value === 'Collected');
  
  checkbox.checked = isCollected;
  applyRowState(row, isCollected);
  evaluateMasterCheckbox();
}

function applyRowState(row, isCollected) {
  const statusSelect = row.querySelector('.status-select');
  const barcodeInput = row.querySelector('.barcode-input');
  
  if (isCollected) {
    statusSelect.value = 'Collected';
    statusSelect.classList.remove('failed');
    barcodeInput.style.textDecoration = 'none';
    barcodeInput.style.color = 'inherit';
  } else {
    statusSelect.value = 'Failed';
    statusSelect.classList.add('failed');
    barcodeInput.style.textDecoration = 'line-through';
    barcodeInput.style.color = 'var(--text-muted)';
  }
}

function evaluateMasterCheckbox() {
  const visibleRows = document.querySelectorAll('.sample-row .row-checkbox');
  const visibleChecked = document.querySelectorAll('.sample-row .row-checkbox:checked');
  const master = document.getElementById('masterCheckbox');
  
  if(visibleRows.length === 0) return;
  master.checked = (visibleRows.length === visibleChecked.length);
  master.indeterminate = (visibleChecked.length > 0 && visibleChecked.length < visibleRows.length);
}

function submitCollection() {
  const btn = document.getElementById('btnSubmitCollection');
  const rows = document.querySelectorAll('.sample-row');
  const globalRemarks = document.getElementById('globalRecommendation') ? document.getElementById('globalRecommendation').value.trim() : '';
  
  let collectionData = [];
  let hasErrors = false;
  
  document.querySelectorAll('.error-border').forEach(el => el.classList.remove('error-border'));
  document.querySelectorAll('.error-msg').forEach(el => el.style.display = 'none');

  rows.forEach(row => {
    const status = row.querySelector('.status-select').value;
    const notesInput = row.querySelector('.notes-input');
    const notes = notesInput.value.trim();
    
    let selectedSampleId = 0;
    let selectedSource = '';
    const radioInputs = row.querySelectorAll('.mapped-sample-id-input');
    radioInputs.forEach(radio => {
        if(radio.checked || radio.type === 'hidden') {
            selectedSampleId = radio.value;
            selectedSource = radio.getAttribute('data-source') || '';
        }
    });
    
    if(status === 'Failed' && notes === '') {
      hasErrors = true;
      notesInput.classList.add('error-border');
      row.querySelector('.error-msg').style.display = 'block';
    }

    collectionData.push({
      request_id: row.getAttribute('data-reqid'),
      sample_id: selectedSampleId,
      status: status,
      source: selectedSource,
      barcode: row.querySelector('.barcode-input').value,
      specific_notes: notes
    });
  });

  if(hasErrors) {
    showToast('Please provide specific notes for all failed or skipped collections.', 'error');
    return;
  }

  const finalPayload = {
      samples: collectionData,
      overall_recommendation: globalRemarks
  };

  btn.disabled = true;
  btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin"></i> Saving...';

  fetch('../../dripend/includes/lab/processSampleCollection.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(finalPayload)
  })
  .then(async res => {
      if(!res.ok) throw new Error('HTTP error ' + res.status);
      return res.json();
  })
  .then(data => {
      if(data.status === 'success') {
          showToast('Collection data saved successfully. Routing...', 'success');
          setTimeout(() => window.location.href = 'add_lab_result.php', 1500);
      } else {
          showToast(data.message, 'error');
          btn.disabled = false;
          btn.innerHTML = '<i class="fa-solid fa-check-double"></i> Confirm & Save Collection';
      }
  })
  .catch(err => {
      showToast('Network error: Ensure processSampleCollection.php exists at the correct path.', 'error');
      btn.disabled = false;
      btn.innerHTML = '<i class="fa-solid fa-check-double"></i> Confirm & Save Collection';
      console.error(err);
  });
}
</script>
</body>
</html>