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

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

if (!isset($conn) || !$conn) {
    die("<div style='padding:20px; background:#fee2e2; color:#991b1b;'>Fatal Error: Database connection failed.</div>");
}

$doctor_id = $_SESSION['staff_id'] ?? null;
$doc_name = "Unknown Doctor";

if (!$doctor_id) {
    $stmtFallback = $conn->prepare("SELECT staff_id, CONCAT(first_name, ' ', last_name) AS d_name FROM staff WHERE is_doctor_id = 1 AND status_id = 1 LIMIT 1");
    if ($stmtFallback) {
        $stmtFallback->execute();
        $resFallback = $stmtFallback->get_result();
        if ($row = $resFallback->fetch_assoc()) {
            $doctor_id = $row['staff_id'];
            $doc_name = "Dr. " . $row['d_name'];
        }
        $stmtFallback->close();
    }
    if (!$doctor_id) $doctor_id = 0; 
} else {
    $stmtMe = $conn->prepare("SELECT CONCAT(first_name, ' ', last_name) AS d_name FROM staff WHERE staff_id = ?");
    $stmtMe->bind_param("i", $doctor_id);
    $stmtMe->execute();
    if ($row = $stmtMe->get_result()->fetch_assoc()) $doc_name = "Dr. " . $row['d_name'];
    $stmtMe->close();
}

function fetchDict($conn, $query) {
    $data = [];
    $res = $conn->query($query);
    if ($res) while($row = $res->fetch_assoc()) $data[] = $row;
    return $data;
}

// ==============================================================================
// 1. DYNAMIC CATALOG FETCHING
// ==============================================================================
$wards = fetchDict($conn, "SELECT id, ward_name, physical_bed_capacity, current_active_census FROM ipd_wards WHERE is_active=1");
$depts = fetchDict($conn, "SELECT id, department_name FROM departments WHERE is_active=1");
$forms = fetchDict($conn, "SELECT formulation_name FROM drug_formulations WHERE is_active=1");

$freq_query = "SELECT freq_code, description";
$checkCol = $conn->query("SHOW COLUMNS FROM drug_frequency LIKE 'multiplier'");
if($checkCol && $checkCol->num_rows > 0) $freq_query .= ", multiplier";
$freq_query .= " FROM drug_frequency";
$freqs = fetchDict($conn, $freq_query);

$dispensaries = fetchDict($conn, "SELECT location_name FROM inventory_locations WHERE location_type = 'Dispensary' AND is_active = 1 ORDER BY location_name ASC");

$qDrugs = "SELECT sc.id AS service_id, sc.service_name, COALESCE(df.formulation_name, sc.drug_formulation) AS drug_formulation, COALESCE(p.strength_value, sc.drug_strength) AS drug_strength, COALESCE(u.unit_symbol, sc.strength_unit) AS strength_unit FROM service_catalog sc LEFT JOIN products p ON sc.service_name LIKE CONCAT('%', p.generic_name, '%') LEFT JOIN drug_formulations df ON p.formulation_id = df.id LEFT JOIN units_of_measure u ON p.strength_unit_id = u.id WHERE sc.service_type = 'Drug' AND sc.is_active = 1";
$drugs = fetchDict($conn, $qDrugs);
$labs  = fetchDict($conn, "SELECT id, service_name, department_id, (SELECT department_name FROM departments WHERE id = service_catalog.department_id) as department_name FROM service_catalog WHERE service_type IN ('Investigation', 'Procedure', 'Imaging') AND is_active=1");
$staff_list = fetchDict($conn, "SELECT staff_id, CONCAT(first_name, ' ', last_name) AS staff_name FROM staff WHERE status_id = 1");
$icd10_list = fetchDict($conn, "SELECT code, description FROM icd10_dictionary");
$outcomes_list = fetchDict($conn, "SELECT outcome_name, requires_admission FROM dict_clinical_outcome WHERE is_active=1");
$diag_status_list = fetchDict($conn, "SELECT status_name FROM dict_diagnosis_status WHERE is_active=1");

$visit_id = $_GET['visit_id'] ?? 0;
$qVisit = "SELECT v.*, (SELECT sc.department_id FROM visit_details vd JOIN service_catalog sc ON vd.service_id = sc.id WHERE vd.visit_master_id = v.id LIMIT 1) AS department_id FROM visit_master v WHERE v.id = ?";
$stmt = $conn->prepare($qVisit);
$stmt->bind_param("i", $visit_id);
$stmt->execute();
$visit = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$visit) die("<div style='padding:40px; text-align:center;'><h2>Encounter Not Found</h2></div>");
$patient_no = $visit['patient_no'];
$department_id = $visit['department_id'] ?? 0;

// ==============================================================================
// 2. STATE RESUME ENGINE (Pre-Load Data for Update)
// ==============================================================================
$existing_responses = [];
$resDyn = $conn->query("SELECT field_name, field_value FROM clinical_dynamic_responses WHERE visit_id = $visit_id");
if($resDyn) while($r = $resDyn->fetch_assoc()) $existing_responses[$r['field_name']] = $r['field_value'];

$qNotes = "SELECT * FROM clinical_notes WHERE visit_id = ?";
$stmtN = $conn->prepare($qNotes);
$stmtN->bind_param("i", $visit_id);
$stmtN->execute();
$legacy_notes = $stmtN->get_result()->fetch_assoc();
$stmtN->close();

$qAdmit = "SELECT * FROM clinical_admission_requests WHERE visit_master_id = ?";
$stmtA = $conn->prepare($qAdmit);
$stmtA->bind_param("i", $visit_id);
$stmtA->execute();
$admit_request = $stmtA->get_result()->fetch_assoc();
$stmtA->close();

$existing_admit_ward = $admit_request['requested_ward'] ?? '';
$existing_admit_diag = $admit_request['admission_diagnosis'] ?? '';
$existing_admit_plan = $admit_request['treatment_plan'] ?? '';

$existing_diagnoses = fetchDict($conn, "SELECT * FROM clinical_diagnoses WHERE visit_id = $visit_id ORDER BY is_principal DESC, id ASC");
$existing_rx = fetchDict($conn, "SELECT * FROM clinical_prescriptions WHERE visit_id = $visit_id");
$existing_labs = fetchDict($conn, "SELECT * FROM clinical_lab_requests WHERE visit_id = $visit_id");

$existing_helpers = [];
$resH = $conn->query("SELECT staff_name FROM clinical_encounter_helpers WHERE visit_id = $visit_id");
if($resH) while($r = $resH->fetch_assoc()) $existing_helpers[] = $r['staff_name'];

// Vitals
$last_vitals = null;
$vitals_missing = true;
$stmtLastV = $conn->prepare("SELECT * FROM patient_vitals WHERE visit_id = ? OR (patient_no = ? AND DATE(recorded_at) = CURDATE()) ORDER BY recorded_at DESC LIMIT 1");
$stmtLastV->bind_param("is", $visit_id, $patient_no);
$stmtLastV->execute();
$resLastV = $stmtLastV->get_result();
if ($resLastV->num_rows > 0) { $last_vitals = $resLastV->fetch_assoc(); $vitals_missing = false; }
$stmtLastV->close();

// Deduplicate Dynamic Tabs
$dynamic_tabs = [];
$unique_fields = []; 
$qFields = "SELECT * FROM consultation_form_setup WHERE is_active = 1 AND (department_id = ? OR department_id IS NULL) ORDER BY department_id DESC, display_order ASC";
$stmtDyn = $conn->prepare($qFields);
$stmtDyn->bind_param("i", $department_id);
$stmtDyn->execute();
$resFields = $stmtDyn->get_result();
while($row = $resFields->fetch_assoc()) {
    if ($row['section_name'] === 'Triage & Vitals') continue;
    $field_key = strtolower(trim($row['field_name']));
    if (!in_array($field_key, $unique_fields)) {
        $dynamic_tabs[$row['section_name']][] = $row;
        $unique_fields[] = $field_key; 
    }
}
$stmtDyn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Update Encounter | RiMax Health</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" 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:260px; --bg:#f8fafc; --accent-dark:#0f172a; --accent-mid:#0284c7; --green:#10b981; --border:#e2e8f0; --muted:#64748b; }
*{box-sizing:border-box;margin:0;padding:0;font-family:'Inter',system-ui,sans-serif;}
body{background:var(--bg);color:#1e293b; overflow-x:hidden;}

/* STRICT SIDEBAR SPACING */
.page-wrapper { margin-left: var(--sidebar-width) !important; padding: 2.5rem; width: calc(100% - var(--sidebar-width)); min-height: 100vh; box-sizing: border-box; }
@media (max-width: 992px) { .page-wrapper { margin-left: 0 !important; width: 100% !important; padding: 1.5rem; } }

.appointment-container{ width:100%; max-width:1300px; margin:0 auto; background:#fff; border-radius:16px; padding:30px; box-shadow:0 10px 25px rgba(0,0,0,0.03); border:1px solid var(--border); }
.page-title{ font-size:22px; font-weight:800; color:var(--accent-dark); margin-bottom:25px; display:flex; justify-content:space-between; align-items:center; }
.patient-tabs{ display:flex; gap:10px; margin-bottom:25px; background:#f8fafc; padding:12px; border-radius:12px; overflow-x:auto; border: 1px solid var(--border); }
.patient-tab{ padding:10px 22px; border-radius:8px; background:#fff; color:var(--muted); font-weight:700; font-size:13px; cursor:pointer; transition:all .2s ease; border:1px solid var(--border); white-space:nowrap; display:flex; align-items:center; gap:8px; }
.patient-tab.active{ background:var(--accent-dark); color:#fff; border-color:var(--accent-dark); box-shadow:0 4px 10px rgba(15, 23, 42, 0.2); }
.tab-content { display: none; animation: fadeIn 0.3s ease; }
.tab-content.active { display: block; }
@keyframes fadeIn { from{opacity:0; transform:translateY(5px);} to{opacity:1; transform:translateY(0);} }
.section{ background:#fff; border-radius:12px; margin-bottom:25px; border:1px solid var(--border); box-shadow: 0 2px 6px rgba(0,0,0,0.02);}
.section-header{ padding:15px 20px; background:#f8fafc; color:var(--accent-dark); font-weight:800; border-bottom:1px solid var(--border); font-size:14px; border-radius:12px 12px 0 0; display:flex; justify-content:space-between; align-items:center; text-transform:uppercase; letter-spacing:0.5px;}
.section-body{ padding:25px; }
.form-row { display:flex; gap:20px; margin-bottom:20px; flex-wrap:wrap; align-items:flex-start; }
.form-col { flex:1; display:flex; flex-direction:column; gap:8px; min-width:150px; }
.form-col label { font-size:11px; font-weight:800; color:var(--muted); text-transform:uppercase; letter-spacing: 0.5px;}
.input-control { padding:12px 15px; border-radius:8px; border:1px solid #cbd5e1; font-size:14px; outline:none; width:100%; transition:0.2s; background:#fff; color:#1e293b; font-weight:500;}
.input-control:focus { border-color:var(--accent-mid); box-shadow:0 0 0 3px #e0f2fe; }
.input-readonly { background: #f8fafc; color: #64748b; font-weight: 700; cursor: not-allowed; border-color: #e2e8f0; pointer-events: none;}
.big-text { min-height:100px; resize:vertical; line-height:1.6;}
.select2-container--default .select2-selection--single, .select2-container--default .select2-selection--multiple { background-color: #fff; border: 1px solid #cbd5e1; border-radius: 8px; min-height: 44px; display: flex; align-items: center; }
.select2-container--default .select2-selection--single:focus, .select2-container--default.select2-container--open .select2-selection--single { border-color: var(--accent-mid); box-shadow:0 0 0 3px #e0f2fe;}
.select2-container--default .select2-selection--single .select2-selection__rendered { font-size: 14px; font-weight: 500; color: #1e293b; line-height: 44px; padding-left: 15px; }
.btn-small{ background:var(--accent-mid); color:#fff; padding:8px 18px; border:none; border-radius:20px; font-weight:700; cursor:pointer; font-size:13px; display:inline-flex; align-items:center; gap:6px; transition:0.2s; text-decoration:none;}
.btn-red { background:#fee2e2; color:#dc2626; border:none; border-radius:8px; padding:12px 18px; cursor:pointer; font-weight:800; transition:0.2s;}
.btn-save{ background:var(--green); color:#fff; padding:14px 30px; border:none; border-radius:8px; font-weight:800; font-size:15px; cursor:pointer; box-shadow:0 4px 10px rgba(16, 185, 129, 0.3); transition:0.2s; }
.last-recorded-banner { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 15px 20px; display: flex; flex-wrap: wrap; gap: 20px; align-items: center; margin-bottom: 20px;}
.lr-item { display: flex; flex-direction: column; gap: 4px; }
.lr-lbl { font-size: 11px; font-weight: 800; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
.lr-val { font-size: 16px; font-weight: 900; color: #0f172a; }
.history-table { width:100%; border-collapse:collapse; font-size:13px; text-align:left; margin-bottom:25px; border:1px solid #cbd5e1; border-radius:8px; overflow:hidden;}
.history-table th { padding:10px 15px; background:#f1f5f9; color:#0f172a; border-bottom:1px solid #cbd5e1;}
.history-table td { padding:10px 15px; border-bottom:1px solid #e2e8f0; color:#475569;}
</style>
</head>
<body>
   
<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper">
  <div class="appointment-container">
    
    <div class="page-title">
        <span><i class="fa-solid fa-user-pen text-primary"></i> Update Clinical Encounter</span>
        <div>
            <span style="font-size:13px; color:var(--muted); background:#f1f5f9; padding:8px 16px; border-radius:20px; border:1px solid #cbd5e1; font-weight:600;">
                <i class="fa-solid fa-layer-group text-primary me-1"></i> ID: <?php echo htmlspecialchars($visit['appointment_no']); ?>
            </span>
        </div>
    </div>

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

    <?php if ($vitals_missing): ?>
        <div style="padding: 60px 20px; text-align: center; background: #fef2f2; border-radius: 12px; border: 2px dashed #ef4444; margin-top: 20px;">
            <i class="fa-solid fa-lock" style="font-size: 60px; color: #dc2626; margin-bottom: 20px;"></i>
            <h2 style="color: #991b1b; margin-bottom: 10px;">Encounter Locked: Triage Required</h2>
            <button type="button" class="btn-save" style="background: #dc2626; box-shadow: none;" onclick="window.location.href='/rimax/application/views/consultation/consultationQueue.php'">
                <i class="fa-solid fa-arrow-left"></i> Return to Queue
            </button>
        </div>
    <?php else: ?>
        
        <div class="patient-tabs">
            <div class="patient-tab active" onclick="switchTab('tab-triage', this)"><i class="fa-solid fa-heart-pulse"></i> Triage & Vitals</div>
            <?php 
            $tab_count = 1;
            foreach ($dynamic_tabs as $section_name => $fields): 
                $tab_id = 'tab-dyn-' . md5($section_name);
            ?>
                <div class="patient-tab" onclick="switchTab('<?php echo $tab_id; ?>', this)"><i class="fa-solid fa-file-medical"></i> <?php echo htmlspecialchars($section_name); ?></div>
            <?php $tab_count++; endforeach; ?>
            <div class="patient-tab" onclick="switchTab('tab-diag', this)"><i class="fa-solid fa-microscope"></i> Diagnoses</div>
            <div class="patient-tab" onclick="switchTab('tab-orders', this)"><i class="fa-solid fa-capsules"></i> Orders & Rx</div>
            <div class="patient-tab" onclick="switchTab('tab-outcome', this)"><i class="fa-solid fa-door-open"></i> Clinical Outcome</div>
        </div>

        <form id="consultForm" method="POST" action="/rimax/application/dripend/includes/consultation/processUpdateConsultation.php">
          <input type="hidden" name="update_encounter" value="1">
          <input type="hidden" name="visit_id" value="<?php echo $visit_id; ?>">
          <input type="hidden" name="patient_no" value="<?php echo htmlspecialchars($visit['patient_no']); ?>">
          <input type="hidden" name="doctor_id" value="<?php echo $doctor_id; ?>">

          <!-- TAB 0: VITALS -->
          <div id="tab-triage" class="tab-content active">
            <div class="section">
              <div class="section-header"><span>Triage Assessment Data</span></div>
              <div class="section-body">
                  <div class="last-recorded-banner">
                      <div class="lr-item" style="border-right: 1px solid #cbd5e1; padding-right: 20px;"><span class="lr-lbl">Recorded At</span><span class="lr-val"><i class="fa-regular fa-clock"></i> <?php echo date('d M Y, h:i A', strtotime($last_vitals['recorded_at'])); ?></span></div>
                      <div class="lr-item"><span class="lr-lbl">BP</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['bp_systolic'] ?? '--') . '/' . htmlspecialchars($last_vitals['bp_diastolic'] ?? '--'); ?></span></div>
                      <div class="lr-item"><span class="lr-lbl">Pulse</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['pulse_rate'] ?? '--'); ?></span></div>
                      <div class="lr-item"><span class="lr-lbl">Temp</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['temperature'] ?? '--'); ?></span></div>
                      <div class="lr-item"><span class="lr-lbl">SpO₂</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['spo2'] ?? '--'); ?></span></div>
                      <div class="lr-item"><span class="lr-lbl">Weight</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['weight_kg'] ?? '--'); ?></span></div>
                  </div>
              </div>
            </div>
            <div style="text-align:right;"><button type="button" class="btn-small" onclick="document.querySelectorAll('.patient-tab')[1].click()">Proceed <i class="fa-solid fa-arrow-right"></i></button></div>
          </div>

          <!-- DYNAMIC CLINICAL TABS -->
          <?php 
          $current_tab_index = 1;
          foreach ($dynamic_tabs as $section_name => $fields): 
              $tab_id = 'tab-dyn-' . md5($section_name);
          ?>
          <div id="<?php echo $tab_id; ?>" class="tab-content">
            <div class="section">
              <div class="section-header"><?php echo htmlspecialchars($section_name); ?></div>
              <div class="section-body">
                  <?php foreach ($fields as $f): 
                      $required = $f['is_required'] ? 'required' : '';
                      $req_star = $f['is_required'] ? '<span style="color:#dc2626;">*</span>' : '';
                      $input_name = "dynamic_fields[" . htmlspecialchars($f['field_name']) . "]";
                      
                      // Pull existing values
                      $val = $existing_responses[$f['field_name']] ?? '';
                      if (empty($val) && $legacy_notes) {
                          $fn = strtolower(trim($f['field_name']));
                          if ($fn == 'chief_complaint' || strpos($fn, 'complaint') !== false) $val = $legacy_notes['chief_complaint'];
                          elseif ($fn == 'hpi_notes' || strpos($fn, 'history') !== false) $val = $legacy_notes['clinical_history'];
                          elseif ($fn == 'general_examination' || strpos($fn, 'exam') !== false) $val = $legacy_notes['examination_notes'];
                          elseif ($fn == 'treatment_plan' || strpos($fn, 'plan') !== false) $val = $legacy_notes['treatment_plan_notes'];
                      }
                      if($f['field_name'] === 'next_review_date' && empty($val)) $val = $visit['next_review_date'] ?? '';
                  ?>
                      <div class="form-col" style="margin-bottom:20px;">
                          <label><?php echo htmlspecialchars($f['field_label']) . ' ' . $req_star; ?></label>
                          <?php if ($f['field_type'] === 'textarea'): ?>
                              <textarea name="<?php echo $input_name; ?>" class="input-control big-text" <?php echo $required; ?>><?php echo htmlspecialchars($val); ?></textarea>
                          <?php elseif ($f['field_type'] === 'select'): 
                              $options = explode(',', $f['field_options']);
                          ?>
                              <select name="<?php echo $input_name; ?>" class="input-control select2-generic" <?php echo $required; ?> style="width:100%;">
                                  <option value="">-- Select --</option>
                                  <?php foreach($options as $opt): 
                                      $opt_clean = trim($opt);
                                      $sel = ($opt_clean !== '' && $val === $opt_clean) ? 'selected' : '';
                                  ?>
                                      <option value="<?php echo htmlspecialchars($opt_clean); ?>" <?php echo $sel; ?>><?php echo htmlspecialchars($opt_clean); ?></option>
                                  <?php endforeach; ?>
                              </select>
                          <?php else: ?>
                              <input type="<?php echo htmlspecialchars($f['field_type']); ?>" name="<?php echo $input_name; ?>" class="input-control" value="<?php echo htmlspecialchars($val); ?>" <?php echo $required; ?>>
                          <?php endif; ?>
                      </div>
                  <?php endforeach; ?>
              </div>
            </div>
            <div style="text-align:right;"><button type="button" class="btn-small" onclick="document.querySelectorAll('.patient-tab')[<?php echo $current_tab_index + 1; ?>].click()">Proceed <i class="fa-solid fa-arrow-right"></i></button></div>
          </div>
          <?php $current_tab_index++; endforeach; ?>

          <!-- TAB: DIAGNOSES MATRIX -->
          <div id="tab-diag" class="tab-content">
            <div class="section">
              <div class="section-header">Diagnoses & Indexing <span style="color:#dc2626; font-size:12px; margin-left:10px;"><i class="fa-solid fa-asterisk"></i> Select one Principal Diagnosis</span></div>
              <div class="section-body" id="diag_container">
                  <?php if(!empty($existing_diagnoses)): ?>
                      <?php foreach($existing_diagnoses as $index => $diag): ?>
                          <div class="form-row align-items-center">
                              <input type="hidden" name="diag_row_id[]" value="<?php echo $index; ?>">
                              <div class="form-col" style="flex:0.3; text-align:center;">
                                  <label>Principal</label>
                                  <input type="radio" name="is_principal" value="<?php echo $index; ?>" <?php echo $diag['is_principal'] ? 'checked' : ''; ?> required style="transform: scale(1.4); cursor:pointer;">
                              </div>
                              <div class="form-col" style="flex:0.5;">
                                  <label>Code Type</label>
                                  <select name="diag_type[]" class="input-control select2-generic" style="width:100%;">
                                      <option value="ICD-10" <?php if($diag['code_type']=='ICD-10') echo 'selected'; ?>>ICD-10</option>
                                      <option value="G-DRG" <?php if($diag['code_type']=='G-DRG') echo 'selected'; ?>>G-DRG</option>
                                  </select>
                              </div>
                              <div class="form-col" style="flex:2.5;">
                                  <label>Search Diagnosis Code</label>
                                  <select name="diag_code[]" class="input-control select2-diag diag-code-input" style="width: 100%;">
                                      <option value=""></option>
                                      <?php foreach($icd10_list as $i): 
                                          $valStr = htmlspecialchars($i['code'] . ' - ' . $i['description']);
                                          $sel = ($i['code'] === $diag['code']) ? 'selected' : '';
                                      ?>
                                          <option value="<?php echo $valStr; ?>" <?php echo $sel; ?>><?php echo $valStr; ?></option>
                                      <?php endforeach; ?>
                                  </select>
                              </div>
                              <div class="form-col" style="flex:2;"><label>Doctor's Description</label><input type="text" name="diag_desc[]" class="input-control" value="<?php echo htmlspecialchars($diag['description'] ?? ''); ?>"></div>
                              <div class="form-col" style="flex:0.8;"><label>Status</label>
                                  <select name="diag_status[]" class="input-control select2-generic" style="width:100%;">
                                      <?php foreach($diag_status_list as $ds): 
                                          $sel = ($ds['status_name'] == $diag['diagnosis_type']) ? 'selected' : '';
                                      ?>
                                      <option value="<?php echo htmlspecialchars($ds['status_name']); ?>" <?php echo $sel; ?>><?php echo htmlspecialchars($ds['status_name']); ?></option>
                                      <?php endforeach; ?>
                                  </select>
                              </div>
                              <?php if($index != 0): ?>
                                  <button type="button" class="btn-red" onclick="this.parentElement.remove()" style="margin-top:22px;"><i class="fa-solid fa-trash"></i></button>
                              <?php else: ?>
                                  <div style="width: 48px; margin-top:22px;"></div>
                              <?php endif; ?>
                          </div>
                      <?php endforeach; ?>
                  <?php else: ?>
                      <div class="form-row align-items-center">
                          <input type="hidden" name="diag_row_id[]" value="0">
                          <div class="form-col" style="flex:0.3; text-align:center;">
                              <label>Principal</label>
                              <input type="radio" name="is_principal" value="0" checked required style="transform: scale(1.4); cursor:pointer;">
                          </div>
                          <div class="form-col" style="flex:0.5;"><label>Code Type</label><select name="diag_type[]" class="input-control select2-generic" style="width:100%;"><option value="ICD-10">ICD-10</option><option value="G-DRG">G-DRG</option></select></div>
                          <div class="form-col" style="flex:2.5;"><label>Search Diagnosis Code</label><select name="diag_code[]" class="input-control select2-diag diag-code-input" style="width: 100%;"><option value=""></option><?php foreach($icd10_list as $i): ?><option value="<?php echo htmlspecialchars($i['code'] . ' - ' . $i['description']); ?>"><?php echo htmlspecialchars($i['code'] . ' - ' . $i['description']); ?></option><?php endforeach; ?></select></div>
                          <div class="form-col" style="flex:2;"><label>Doctor's Description</label><input type="text" name="diag_desc[]" class="input-control"></div>
                          <div class="form-col" style="flex:0.8;"><label>Status</label><select name="diag_status[]" class="input-control select2-generic" style="width:100%;"><?php foreach($diag_status_list as $ds): ?><option value="<?php echo htmlspecialchars($ds['status_name']); ?>"><?php echo htmlspecialchars($ds['status_name']); ?></option><?php endforeach; ?></select></div>
                          <div style="width: 48px; margin-top:22px;"></div>
                      </div>
                  <?php endif; ?>
                  <button type="button" class="btn-small mt-3" onclick="addDiagRow()"><i class="fa-solid fa-plus"></i> Add Secondary Diagnosis</button>
              </div>
            </div>

            <div class="section">
              <div class="section-header">Clinical Team</div>
              <div class="section-body">
                  <div class="form-row">
                      <div class="form-col" style="flex:1;">
                          <label>Assisting Staff / Specialist Consults</label>
                          <select name="procedure_helpers[]" class="input-control select2-helpers" multiple="multiple" style="width: 100%;">
                              <?php foreach($staff_list as $staff): 
                                  $sel = in_array($staff['staff_name'], $existing_helpers) ? 'selected' : '';
                              ?>
                                  <option value="<?php echo htmlspecialchars($staff['staff_name']); ?>" <?php echo $sel; ?>><?php echo htmlspecialchars($staff['staff_name']); ?></option>
                              <?php endforeach; ?>
                          </select>
                      </div>
                  </div>
              </div>
            </div>
            <div style="text-align:right;"><button type="button" class="btn-small" onclick="document.querySelectorAll('.patient-tab')[<?php echo $tab_count + 1; ?>].click()">Proceed <i class="fa-solid fa-arrow-right"></i></button></div>
          </div>

          <!-- TAB: ORDERS & RX -->
          <div id="tab-orders" class="tab-content">
            <div class="section">
              <div class="section-header">e-Prescription (Pharmacy)</div>
              <div class="section-body">
                  
                  <?php if(!empty($existing_rx)): ?>
                  <table class="history-table">
                      <tr><th colspan="6"><i class="fa-solid fa-check-circle" style="color:var(--green);"></i> Previously Prescribed in this Encounter</th></tr>
                      <tr style="background:#f8fafc;">
                          <td style="font-weight:bold;">Drug</td><td>Form & Strength</td><td>Dose/Freq</td><td>Duration</td><td>Qty</td><td>Status</td>
                      </tr>
                      <?php foreach($existing_rx as $rx): ?>
                      <tr style="background:#fff;">
                          <td style="font-weight:bold; color:var(--accent-dark);"><?php echo htmlspecialchars($rx['drug_name']); ?></td>
                          <td><?php echo htmlspecialchars($rx['formulation'] . ' ' . $rx['strength']); ?></td>
                          <td><?php echo htmlspecialchars($rx['dose'] . ' / ' . $rx['frequency']); ?></td>
                          <td><?php echo htmlspecialchars($rx['duration_days']); ?> Days</td>
                          <td style="font-weight:bold;"><?php echo htmlspecialchars($rx['quantity']); ?></td>
                          <td><span style="background:#e0f2fe; color:#0284c7; padding:2px 8px; border-radius:12px; font-size:11px;"><?php echo htmlspecialchars($rx['status']); ?></span></td>
                      </tr>
                      <?php endforeach; ?>
                  </table>
                  <?php endif; ?>

                  <div style="background:#fffbeb; border:1px solid #fcd34d; padding:15px; border-radius:8px; margin-bottom:20px; display:flex; align-items:center; gap:15px;">
                      <label style="font-weight:800; color:#b45309; margin:0;"><i class="fa-solid fa-shop"></i> Route New Rx To:</label>
                      <div style="flex:1; max-width:300px;">
                          <select name="dispensing_pharmacy" id="dispensary_dept" class="input-control select2-generic" style="width:100%;" onchange="toggleRx()">
                              <option value="">-- Choose Dispensary --</option>
                              <?php foreach($dispensaries as $disp): ?><option value="<?php echo htmlspecialchars($disp['location_name']); ?>"><?php echo htmlspecialchars($disp['location_name']); ?></option><?php endforeach; ?>
                          </select>
                      </div>
                      <span style="font-size:11px; color:#b45309;">(Select destination to unlock form. Previous Rx orders cannot be modified).</span>
                  </div>

                  <div id="rx_container_wrapper">
                      <div id="rx_container"></div>
                      <button type="button" class="btn-small" onclick="addRxRow()"><i class="fa-solid fa-plus"></i> Add New Medication</button>
                  </div>
              </div>
            </div>

            <div class="section">
              <div class="section-header">Orders: Labs, Imaging & Procedures</div>
              <div class="section-body">
                  <?php if(!empty($existing_labs)): ?>
                  <div style="display:flex; justify-content:space-between; margin-bottom: 10px; align-items:center;">
                      <h6 style="color:var(--green); font-weight:700;"><i class="fa-solid fa-check-circle"></i> Previously Ordered in this Encounter</h6>
                      <button type="button" class="btn-primary" style="padding:6px 12px; font-size:11px; border-radius:20px;" onclick="viewSelectedLabs()"><i class="fa-solid fa-microscope"></i> View Selected Results</button>
                  </div>
                  
                  <table class="history-table">
                      <tr style="background:#f8fafc;">
                          <th style="width: 40px; text-align:center;"><input type="checkbox" id="checkAllLabs" onclick="toggleAllLabs(this)" style="cursor:pointer; transform: scale(1.2);"></th>
                          <td style="font-weight:bold;">Requested Service</td><td>Date</td><td>Status</td><td>Action</td>
                      </tr>
                      <?php foreach($existing_labs as $l): ?>
                      <tr style="background:#fff;">
                          <td style="text-align:center;">
                              <?php if(in_array($l['status'], ['Completed', 'Verified'])): ?>
                                  <input type="checkbox" class="lab-result-chk" value="<?php echo $l['id']; ?>" style="transform: scale(1.2); cursor:pointer;">
                              <?php endif; ?>
                          </td>
                          <td style="font-weight:bold; color:var(--accent-dark);"><?php echo htmlspecialchars($l['test_name']); ?></td>
                          <td><?php echo date('d M Y, h:i A', strtotime($l['created_at'])); ?></td>
                          <td>
                              <?php 
                                $bg = '#e2e8f0'; $col = '#475569';
                                if($l['status'] == 'Completed' || $l['status'] == 'Verified') { $bg = '#dcfce7'; $col = '#166534'; }
                                else if($l['status'] == 'Pending') { $bg = '#fef9c3'; $col = '#b45309'; }
                              ?>
                              <span style="background:<?php echo $bg; ?>; color:<?php echo $col; ?>; padding:2px 8px; border-radius:12px; font-size:11px; font-weight:700;"><?php echo htmlspecialchars($l['status']); ?></span>
                          </td>
                          <td>
                              <?php if(in_array($l['status'], ['Completed', 'Verified'])): ?>
                                  <button type="button" class="btn-small" style="padding: 6px 12px; font-size: 11px;" onclick="viewLabResults([<?php echo $l['id']; ?>])"><i class="fa-regular fa-eye"></i> View</button>
                              <?php else: ?>
                                  <span style="font-size:11px; color:#94a3b8;">Pending</span>
                              <?php endif; ?>
                          </td>
                      </tr>
                      <?php endforeach; ?>
                  </table>
                  <hr style="border: 1px dashed var(--border); margin: 25px 0;">
                  <?php endif; ?>

                  <div id="lab_container"></div>
                  <button type="button" class="btn-small" onclick="addLabRow()"><i class="fa-solid fa-plus"></i> Add New Order</button>
              </div>
            </div>
            <div style="text-align:right;"><button type="button" class="btn-small" onclick="document.querySelectorAll('.patient-tab')[<?php echo $tab_count + 2; ?>].click()">Proceed <i class="fa-solid fa-arrow-right"></i></button></div>
          </div>

          <!-- TAB: CLINICAL OUTCOME & SIGN-OFF -->
          <div id="tab-outcome" class="tab-content">
            <div class="section">
              <div class="section-header">Final Encounter Sign-off</div>
              <div class="section-body">
                  <div class="form-row">
                      <div class="form-col" style="flex:1;">
                          <label>Encounter Outcome / Disposition</label>
                          <select name="clinical_outcome" id="outcome_sel" class="input-control select2-generic" style="width:100%;" onchange="toggleAdmit()">
                              <?php foreach($outcomes_list as $out): 
                                  $sel = ($visit['clinical_outcome'] == $out['outcome_name']) ? 'selected' : '';
                              ?>
                                  <option value="<?php echo htmlspecialchars($out['outcome_name']); ?>" data-admit="<?php echo $out['requires_admission']; ?>" <?php echo $sel; ?>><?php echo htmlspecialchars($out['outcome_name']); ?></option>
                              <?php endforeach; ?>
                          </select>
                          <span style="font-size:11px; color:var(--muted); margin-top:5px;">Determines how the patient is routed next in the queue.</span>
                      </div>
                  </div>

                  <!-- REVISED ADMISSION PANEL -->
                  <div id="admit_panel" style="display:none; background:#f0f9ff; padding:20px; border-radius:8px; margin-top:20px; border:1px solid #bae6fd;">
                      <h4 style="margin:0 0 15px 0; color:#0284c7;"><i class="fa-solid fa-bed-pulse"></i> Admission Request Details</h4>
                      <div class="form-row">
                          <div class="form-col" style="flex:1;">
                              <label>Recommend Ward <span style="color:#dc2626;">*</span></label>
                              <select name="admit_ward" class="input-control select2-generic" style="width:100%;">
                                  <option value="">Select Ward</option>
                                  <?php foreach($wards as $w): 
                                      $sel = ($existing_admit_ward === $w['ward_name']) ? 'selected' : '';
                                  ?>
                                    <option value="<?php echo htmlspecialchars($w['ward_name']); ?>" <?php echo $sel; ?>>
                                        <?php echo htmlspecialchars($w['ward_name']); ?> (Capacity: <?php echo $w['physical_bed_capacity']; ?>, Admitted: <?php echo $w['current_active_census']; ?>)
                                    </option>
                                  <?php endforeach; ?>
                              </select>
                          </div>
                          <div class="form-col" style="flex:1;">
                              <label>Admission Reason Override (Optional)</label>
                              <input type="text" name="admit_diag" class="input-control" value="<?php echo htmlspecialchars($existing_admit_diag); ?>" placeholder="Defaults to Principal Diagnosis if left blank">
                          </div>
                      </div>
                      <div class="form-row" style="margin-top:10px;">
                          <div class="form-col" style="flex:1;">
                              <label>Ward Admission Instructions & Plan <span style="color:#dc2626;">*</span></label>
                              <textarea name="ward_instructions" class="input-control big-text" placeholder="Provide full details of what the ward should do on admission (Monitoring, specific positioning, stat meds, etc.)..."><?php echo htmlspecialchars($existing_admit_plan); ?></textarea>
                          </div>
                      </div>
                  </div>

                  <!-- DOCTOR AUDIT SIGNATURE -->
                  <div style="text-align: right; margin-top: 30px; padding-top: 15px; border-top: 1px dashed var(--border); color: var(--muted); font-size: 13px;">
                      <div style="margin-bottom: 5px;"><i class="fa-solid fa-user-pen"></i> Update Signature: <strong style="color:var(--accent-dark); font-size: 15px;"><?php echo $doc_name; ?></strong></div>
                      <div><i class="fa-regular fa-clock"></i> Local System Time: <span style="font-weight:600;"><?php echo date('d-M-Y H:i:s'); ?></span></div>
                  </div>
              </div>
            </div>

            <div style="display:flex; justify-content:space-between; margin-top:25px; border-top:2px solid var(--border); padding-top:25px;">
              <button type="button" class="btn-small" style="background:#cbd5e1; color:#0f172a;" onclick="window.location.href='/rimax/application/views/consultation/consultationQueue.php'"><i class="fa-solid fa-xmark"></i> Cancel & Return</button>
              <button type="button" class="btn-save" onclick="validateAndSubmit()"><i class="fa-solid fa-lock"></i> Update & Sign Encounter</button>
            </div>
          </div>
        </form>
    <?php endif; ?>
  </div>
</div>

<!-- APPLICATION NOTIFICATION MODAL -->
<div class="modal fade" id="appNotificationModal" tabindex="-1" style="z-index: 9999;">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 12px;">
            <div class="modal-body text-center p-4">
                <div id="appNotifIcon" class="mb-3"></div>
                <h6 class="fw-bold text-dark mb-2" id="appNotifTitle">Notification</h6>
                <p class="text-muted mb-4" id="appNotifMsg" style="font-size: 13px;"></p>
                <button type="button" class="btn-small" data-bs-dismiss="modal" onclick="$('#appNotificationModal').modal('hide');">Got It</button>
            </div>
        </div>
    </div>
</div>

<!-- PENDING ADMISSION MODAL (Gatekeeper) -->
<div class="modal fade" id="modalPendingAdmission" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius: 12px;">
            <div class="modal-header bg-warning text-dark border-0">
                <h5 class="modal-title fw-bold"><i class="fa-solid fa-triangle-exclamation me-2"></i> Pending Admission Found</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4 bg-light text-center">
                <p class="mb-3">This patient has a pending admission request that was never accepted by the ward:</p>
                <div class="p-3 bg-white border rounded shadow-sm mb-3">
                    <p class="mb-1"><b>Ward Requested:</b> <span id="pendingAdmWard" class="text-primary"></span></p>
                    <p class="mb-0"><b>Date Requested:</b> <span id="pendingAdmDate"></span></p>
                </div>
                <p class="small text-muted mb-0">To proceed with a new admission recommendation, you must cancel this existing request.</p>
            </div>
            <div class="modal-footer border-0 bg-white d-flex justify-content-between">
                <button type="button" class="btn-small" style="background:#cbd5e1; color:#0f172a;" data-bs-dismiss="modal">Go Back</button>
                <button type="button" class="btn-small btn-red" onclick="cancelPendingAdmission()"><i class="fa-solid fa-trash me-1"></i> Cancel Old Request</button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- Global Configuration Object for External JS -->
<script>
    window.OpdConfig = {
        diagStatusOptions: <?php echo json_encode($diag_status_list); ?>,
        formOptions: <?php echo json_encode($forms); ?>,
        freqOptions: <?php echo json_encode($freqs); ?>,
        icdOptions: <?php echo json_encode($icd10_list); ?>,
        labOptions: <?php echo json_encode($labs); ?>,
        drugOptions: <?php echo json_encode($drugs); ?>,
        tabCount: <?php echo isset($tab_count) ? $tab_count : 1; ?>,
        baseDiagCount: <?php echo count($existing_diagnoses) ?: 1; ?>,
        activeAdmission: <?php echo json_encode($active_adm); ?>,
        pendingAdmission: <?php echo json_encode($pending_adm); ?>
    };
</script>
<!-- We reuse the exact same robust JS engine -->
<script src="/rimax/application/assets/js/opdConsultation.js"></script>
</body>
</html>