<?php
session_start();
error_reporting(0); // Prevent PHP warnings from breaking JSON output
ob_start();

require_once '../db.php';
header('Content-Type: application/json');

// Bypass Foreign Key constraints to prevent strict mode linking errors during save
$conn->query("SET FOREIGN_KEY_CHECKS=0");

$staff_id = (int)($_SESSION['staff_id'] ?? 0);
if ($staff_id <= 0) {
    $getAnyStaff = $conn->query("SELECT staff_id FROM staff LIMIT 1");
    $staff_id = ($getAnyStaff && $getAnyStaff->num_rows > 0) ? (int)$getAnyStaff->fetch_assoc()['staff_id'] : 1;
}

$action = $_POST['action'] ?? $_GET['action'] ?? '';

$sysQ = $conn->query("SELECT date_format, time_format FROM system_workflow_rules LIMIT 1");
$sys = $sysQ ? $sysQ->fetch_assoc() : null;
$df = $sys['date_format'] ?? 'd-M-Y';
$tf = ($sys['time_format'] == '24') ? 'H:i' : 'h:i A';
$global_date_format = "$df, $tf";

function validateFormAccess($conn, $visit_id, $is_edit) {
    $qRules = $conn->query("SELECT * FROM system_workflow_rules LIMIT 1");
    $rules = $qRules ? $qRules->fetch_assoc() : null;
    if (!$rules) return;

    $qEp = $conn->query("SELECT status FROM ipd_admission_episodes WHERE visit_master_id = $visit_id LIMIT 1");
    $ep = $qEp ? $qEp->fetch_assoc() : null;
    $ep_status = $ep ? $ep['status'] : '';
    $is_discharge = in_array($ep_status, ['Pending Discharge', 'Discharged']);
    
    $qTh = $conn->query("SELECT status FROM ipd_theatre_requests WHERE visit_id = $visit_id ORDER BY id DESC LIMIT 1");
    $th = $qTh ? $qTh->fetch_assoc() : null;
    $is_theatre_pending = ($ep_status === 'In Theatre' || ($th && in_array($th['status'], ['Pending', 'Scheduled', 'In Progress'])));
    $is_theatre_revert = ($th && in_array($th['status'], ['Cancelled', 'Rejected']));

    if ($is_edit) {
        if ($is_discharge && $rules['block_edit_ipd_on_discharge']) throw new Exception("Workflow Rule: Editing is blocked because patient is recommended for discharge.");
        if ($is_theatre_pending && $rules['block_edit_ipd_on_theatre_req']) throw new Exception("Workflow Rule: Editing is blocked because patient is assigned to Theatre.");
    } else {
        if ($is_discharge && $rules['block_new_ipd_on_discharge']) throw new Exception("Workflow Rule: Adding new records is blocked because patient is recommended for discharge.");
        if ($is_theatre_pending && $rules['block_new_ipd_on_theatre_req']) throw new Exception("Workflow Rule: Adding new records is blocked because patient is assigned to Theatre.");
        if ($is_theatre_revert && !$is_theatre_pending && !$is_discharge && $rules['block_new_ipd_on_theatre_revert']) throw new Exception("Workflow Rule: Adding new records is blocked due to Theatre revert status.");
    }
}

try {
    if ($action === 'search_icd_gdrg') {
        $term = isset($_GET['q']) ? $conn->real_escape_string($_GET['q']) : '';
        $sql = "SELECT i.code as id, i.description as text, g.gdrg_code 
                FROM icd10_dictionary i 
                LEFT JOIN gdrg_icd_mapping g ON i.code = g.icd10_code 
                WHERE i.code LIKE '%$term%' OR i.description LIKE '%$term%' LIMIT 40";
        $res = $conn->query($sql);
        $results = [];
        if($res) {
            while($row = $res->fetch_assoc()) {
                $gdrg = !empty($row['gdrg_code']) ? $row['gdrg_code'] : 'Unmapped';
                $results[] = [
                    'id' => $row['id'] . '|||' . $row['text'] . '|||' . $gdrg,
                    'text' => '['.$row['id'].'] ' . $row['text'] . ' (G-DRG: '.$gdrg.')'
                ];
            }
        }
        ob_end_clean(); echo json_encode(['results' => $results]); exit;
    }

    if ($action === 'get_edit_data') {
        $form_id = (int)$_POST['form_id'];
        $visit_id = (int)$_POST['visit_id'];
        $recorded_at = $_POST['recorded_at'];
        $module_name = "form_" . $form_id;
        $data = [];

        $q = $conn->prepare("SELECT field_name, field_value FROM ipd_dynamic_responses WHERE visit_id = ? AND module_name = ? AND recorded_at = ? AND is_deleted = 0");
        $q->bind_param("iss", $visit_id, $module_name, $recorded_at);
        $q->execute();
        $res = $q->get_result();
        while($r = $res->fetch_assoc()) {
            $data[$r['field_name']] = $r['field_value'];
        }

        $qFl = $conn->prepare("SELECT * FROM ipd_fluid_charts WHERE visit_id=? AND recorded_at=? AND is_deleted=0");
        $qFl->bind_param("is", $visit_id, $recorded_at); $qFl->execute();
        $resFl = $qFl->get_result();
        while($r = $resFl->fetch_assoc()) $data['NATIVE_FLUID'][] = $r;

        $qMd = $conn->prepare("SELECT * FROM ipd_medication_charts WHERE visit_id=? AND entry_time=? AND is_deleted=0");
        $qMd->bind_param("is", $visit_id, $recorded_at); $qMd->execute();
        $resMd = $qMd->get_result();
        while($r = $resMd->fetch_assoc()) $data['NATIVE_MED'][] = $r;

        $data['NATIVE_DIAG'] = [];
        $qDiag = $conn->prepare("SELECT code as icd, description as descr, gdrg_mapped_code as gdrg, is_principal FROM clinical_diagnoses WHERE visit_id=? AND created_at=?");
        $qDiag->bind_param("is", $visit_id, $recorded_at); $qDiag->execute();
        $resDiag = $qDiag->get_result();
        while($r = $resDiag->fetch_assoc()) $data['NATIVE_DIAG'][] = $r;

        $qReq = $conn->prepare("SELECT target_ward_id, transfer_type, treatment_plan FROM clinical_admission_requests WHERE visit_master_id=? AND created_at=? AND status != 'Cancelled'");
        $qReq->bind_param("is", $visit_id, $recorded_at); $qReq->execute();
        if ($req = $qReq->get_result()->fetch_assoc()) {
            $data['NATIVE_TRANSFER'] = $req;
        }

        $qTh = $conn->prepare("SELECT room_id, procedure_name, surgeon_id, remarks FROM ipd_theatre_requests WHERE visit_id=? AND created_at=? AND status != 'Cancelled'");
        $qTh->bind_param("is", $visit_id, $recorded_at); $qTh->execute();
        if ($th = $qTh->get_result()->fetch_assoc()) {
            $qProc = $conn->prepare("SELECT id FROM ipd_setup_surgical_procedures WHERE procedure_name = ? LIMIT 1");
            $qProc->bind_param("s", $th['procedure_name']); $qProc->execute();
            $th['procedure_id'] = $qProc->get_result()->fetch_assoc()['id'] ?? '';
            $data['NATIVE_THEATRE'] = $th;
        }

        ob_end_clean(); echo json_encode(['status' => 'success', 'data' => $data]); exit;
    }

    if ($action === 'stop_prescription') {
        $rx_id = (int)$_POST['rx_id'];
        $reason = trim($conn->real_escape_string($_POST['reason'] ?? 'Discontinued by Doctor'));
        $conn->query("UPDATE clinical_prescriptions SET status='Stopped', end_date=NOW(), remarks = CONCAT(COALESCE(remarks, ''), ' [STOPPED: ', '$reason', ']') WHERE id=$rx_id");
        ob_end_clean(); echo json_encode(['status' => 'success', 'message' => 'Medication successfully discontinued.']); exit;
    }

    if ($action === 'calculate_engine_qty') {
        $svc_id = (int)$_POST['service_id'];
        $dose_val = (float)preg_replace('/[^0-9.]/', '', trim($_POST['dose'])) ?: 1;
        $freq_code = trim($_POST['frequency_code']);
        $duration = (float)$_POST['duration'];
        $ui_strength = trim($_POST['strength'] ?? ''); 

        $qD = $conn->query("SELECT drug_strength, unit_of_pricing FROM service_catalog WHERE id = $svc_id");
        $drug = $qD ? $qD->fetch_assoc() : null;
        
        $str_val = 1;
        if (!empty($ui_strength)) {
            $str_val = (float)preg_replace('/[^0-9.]/', '', $ui_strength);
        } elseif ($drug && !empty($drug['drug_strength'])) {
            $str_val = (float)preg_replace('/[^0-9.]/', '', $drug['drug_strength']);
        }
        if ($str_val <= 0) $str_val = 1;

        $uom = $drug ? trim($drug['unit_of_pricing'] ?? '') : '';

        $qF = $conn->query("SELECT multiplier FROM drug_frequency WHERE freq_code = '$freq_code'");
        $freq_mult = $qF ? (float)($qF->fetch_assoc()['multiplier'] ?? 1) : 1;

        $qR = $conn->prepare("
            SELECT f.math_expression, rnd.php_logic, 
                   (CASE r.mode_id WHEN 1 THEN 'Automatic' WHEN 2 THEN 'Semi-Automatic' ELSE 'Manual' END) as mode_name, 
                   r.rule_name
            FROM med_calc_rules r 
            JOIN med_calc_formulas f ON r.formula_id = f.id 
            JOIN med_calc_rounding_rules rnd ON r.rounding_id = rnd.id 
            WHERE r.base_inventory_unit = ? LIMIT 1
        ");
        $qR->bind_param("s", $uom);
        $qR->execute();
        $rule = $qR->get_result()->fetch_assoc();

        if (!$rule) {
            $ruleQ = $conn->query("SELECT f.math_expression, rnd.php_logic, (CASE r.mode_id WHEN 1 THEN 'Automatic' WHEN 2 THEN 'Semi-Automatic' ELSE 'Manual' END) as mode_name, r.rule_name FROM med_calc_rules r JOIN med_calc_formulas f ON r.formula_id = f.id JOIN med_calc_rounding_rules rnd ON r.rounding_id = rnd.id ORDER BY r.id ASC LIMIT 1");
            $rule = $ruleQ ? $ruleQ->fetch_assoc() : null;
        }
        
        if (!$rule) {
            $rule = ['math_expression' => '([DOSE] / [STRENGTH]) * [FREQ_MULT] * [DURATION_DAYS]', 'php_logic' => 'CEIL', 'mode_name' => 'System Fallback', 'rule_name' => 'Default Formula'];
        }

        $pack_size = (strpos(strtolower($uom), 'ml') !== false) ? 100 : 1; 

        $eval_string = str_replace(
            ['[DOSE]', '[STRENGTH]', '[FREQ_MULT]', '[DURATION_DAYS]', '[PACK_SIZE]'], 
            [$dose_val, $str_val, $freq_mult, $duration, $pack_size], 
            $rule['math_expression']
        );

        $calc_raw = 0;
        try { 
            $calc_raw = eval("return ($eval_string);"); 
        } catch(Throwable $e) {
            $calc_raw = ($dose_val / $str_val) * $freq_mult * $duration; 
        }

        $final_qty = $calc_raw;
        $logic = $rule['php_logic'] ?? 'CEIL';
        if ($logic === 'CEIL') $final_qty = ceil($calc_raw);
        elseif ($logic === 'FLOOR') $final_qty = floor($calc_raw);
        elseif ($logic === 'ROUND') $final_qty = round($calc_raw);

        if ($final_qty < 1 && $calc_raw > 0 && $logic !== 'EXACT') $final_qty = 1;

        $log = "[{$rule['mode_name']}] {$rule['rule_name']} Applied &rarr; {$eval_string} = {$calc_raw} (Rounded: {$final_qty})";

        ob_end_clean(); echo json_encode(['status'=>'success', 'final_qty' => $final_qty, 'log' => $log]); exit;
    }

    if ($action === 'get_action_interface') {
        $form_id = (int)$_POST['form_id'];
        $visit_id = (int)$_POST['visit_id'];
        $patient_no = $conn->real_escape_string($_POST['patient_no'] ?? '');
        
        $qFMeta = $conn->query("SELECT form_name FROM ipd_forms WHERE id=$form_id");
        $fName = $qFMeta ? $qFMeta->fetch_assoc()['form_name'] : 'Clinical Form';
        
        $html = "
            <input type='hidden' name='form_id' value='$form_id'>
            <input type='hidden' name='module_name' value='form_$form_id'>
            <input type='hidden' name='action' value='save_pool_action'>
            <input type='hidden' name='visit_id' value='$visit_id'>
            <input type='hidden' name='patient_no' value='$patient_no'>
        ";
        
        $fields = $conn->query("SELECT * FROM ipd_form_fields WHERE section_id IN (SELECT id FROM ipd_form_sections WHERE form_id=$form_id) ORDER BY display_order ASC");
        
        $html .= "<div class='row g-3'>";
        if($fields) {
            while($f = $fields->fetch_assoc()) {
                $req = $f['is_mandatory'] ? 'required' : '';
                $req_star = $f['is_mandatory'] ? "<span class='text-danger'>*</span>" : "";
                $lbl = htmlspecialchars($f['field_label']);
                $type = $f['field_type'];
                $safe_attr = htmlspecialchars($lbl, ENT_QUOTES);
                $name = "dynamic_fields[" . $lbl . "]";
                
                if ($type === 'Long Text') {
                    $html .= "
                    <div class='col-12 mt-3'>
                        <label class='fw-bold small text-primary mb-1'>$lbl {$req_star}</label>
                        <textarea name='$name' class='form-control rich-text-editor' {$req}></textarea>
                    </div>";
                } 
                elseif ($type === 'Native: Clinical Diagnosis') {
                    $html .= "
                    <div class='col-12 p-3 bg-white border border-secondary rounded-3 shadow-sm my-3'>
                        <h6 class='fw-bold text-secondary mb-3 text-uppercase'>
                            <i class='fa-solid fa-book-medical me-2'></i> {$lbl} (ICD-10 & G-DRG Auto-Map) <span class='text-danger'>*</span>
                        </h6>
                        <div class='row g-2 align-items-center mb-3'>
                            <div class='col-md-10'>
                                <select id='icd_search_select' class='form-select' style='width:100%;' data-placeholder='Search by diagnosis name or ICD code...'></select>
                            </div>
                            <div class='col-md-2'>
                                <button type='button' class='btn btn-secondary w-100 fw-bold' onclick='addDiagnosisRow()'><i class='fa fa-plus me-1'></i> Add to List</button>
                            </div>
                        </div>
                        <div class='table-responsive'>
                            <table class='table table-bordered table-sm align-middle' id='diag_table'>
                                <thead class='table-light'>
                                    <tr>
                                        <th class='text-center'>Principal</th>
                                        <th>ICD-10 Code & Description</th>
                                        <th>Mapped G-DRG</th>
                                        <th class='text-center'>Remove</th>
                                    </tr>
                                </thead>
                                <tbody id='diag_tbody'>
                                    <tr id='diag_empty_row'>
                                        <td colspan='4' class='text-center text-muted py-3'>Search and add diagnoses above. At least one must be marked as Principal.</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <input type='text' id='diag_validation_flag' style='opacity:0; width:0; height:0; padding:0; margin:0;' {$req}>
                    </div>";
                }
                elseif ($type === 'Native: Pharmacy') {
                    $drugOpts = "";
                    $qD = $conn->query("SELECT id, service_name, drug_formulation, drug_strength, strength_unit, unit_of_pricing FROM service_catalog WHERE service_type='Drug' AND is_active=1 ORDER BY service_name ASC");
                    if($qD) {
                        while($d = $qD->fetch_assoc()) {
                            $f_val = htmlspecialchars((string)($d['drug_formulation'] ?? ''), ENT_QUOTES);
                            $s_val = htmlspecialchars(trim((string)($d['drug_strength'] ?? '') . ' ' . (string)($d['strength_unit'] ?? '')), ENT_QUOTES);
                            $drugOpts .= "<option value='{$d['id']}||".htmlspecialchars($d['service_name'], ENT_QUOTES)."' data-form='{$f_val}' data-strength='{$s_val}' data-uom='".htmlspecialchars($d['unit_of_pricing'] ?? '')."'>".htmlspecialchars($d['service_name'])." {$s_val}</option>";
                        }
                    }

                    $dispOpts = "<option value='' disabled selected>-- Select Dispensary --</option>";
                    $qDisp = $conn->query("SELECT location_name FROM inventory_locations WHERE location_type='Dispensary' AND is_active=1");
                    if($qDisp) {
                        while($disp = $qDisp->fetch_assoc()) {
                            $dispOpts .= "<option value='".htmlspecialchars($disp['location_name'], ENT_QUOTES)."'>".htmlspecialchars($disp['location_name'])."</option>";
                        }
                    }
                    
                    $dbFreq = $conn->query("SELECT freq_code, description FROM drug_frequency");
                    $fOpts = ""; 
                    if($dbFreq) {
                        while($f = $dbFreq->fetch_assoc()) {
                            $fOpts .= "<option value='{$f['freq_code']}'>{$f['description']}</option>";
                        }
                    }
                    
                    $html .= "
                    <div id='rx_drug_options_template' style='display:none;'>{$drugOpts}</div>
                    <div id='rx_freq_options_template' style='display:none;'>{$fOpts}</div>

                    <div class='col-12 p-0 bg-white border border-warning rounded-3 shadow-sm my-3'>
                        <div class='bg-warning bg-opacity-10 p-3 border-bottom border-warning d-flex justify-content-between align-items-center'>
                            <h6 class='fw-bold text-warning mb-0 text-uppercase'><i class='fa-solid fa-pills me-2'></i> {$lbl} (Prescribing Engine)</h6>
                            <select name='dispensing_pharmacy' class='form-select form-select-sm border-warning fw-bold text-warning dispensary-select' style='width:auto; background:white;'>{$dispOpts}</select>
                        </div>
                        <div class='p-3 bg-light'>
                            <div class='alert alert-secondary py-2 small mb-2' id='dispensary_lock_notice'>
                                <i class='fa-solid fa-lock me-1'></i> Please select a Dispensary above to unlock prescription entry.
                            </div>
                            <div id='rx_dynamic_container'></div>
                            <button type='button' class='btn btn-sm btn-warning text-dark fw-bold mt-2 shadow-sm rx-add-btn' disabled onclick='addDynamicRxRow()'>
                                <i class='fa-solid fa-plus me-1'></i> Add Medication
                            </button>
                        </div>
                    </div>";
                }
                elseif ($type === 'Native: Service Order') {
                    $dept_ids = !empty($f['options_csv']) ? $conn->real_escape_string($f['options_csv']) : '0';
                    $svcOpts = "";
                    $qSvc = $conn->query("SELECT id, service_name, department_id, cash_price_adult, tariff_adult FROM service_catalog WHERE department_id IN ($dept_ids) AND is_active=1 ORDER BY service_name ASC");
                    if ($qSvc) {
                        while($sv = $qSvc->fetch_assoc()) {
                            $svcOpts .= "<option value='{$sv['id']}||".htmlspecialchars($sv['service_name'], ENT_QUOTES)."||{$sv['cash_price_adult']}||{$sv['tariff_adult']}||{$sv['department_id']}'>".htmlspecialchars($sv['service_name'])."</option>";
                        }
                    }

                    $html .= "
                    <div class='col-12 p-3 bg-white border border-success rounded-3 shadow-sm my-2'>
                        <h6 class='fw-bold text-success mb-2 text-uppercase'><i class='fa-solid fa-stethoscope me-2'></i> {$lbl}</h6>
                        <select name='order_service[]' class='form-select select2-basic' multiple='multiple' style='width:100%;' data-placeholder='Search & Order Services to Bill...'>
                            {$svcOpts}
                        </select>
                    </div>";
                }
                elseif ($type === 'Native: Clinical Outcome') {
                    $outOpts = "<option value='' disabled selected>-- Select Disposition --</option>";
                    $qOut = $conn->query("SELECT outcome_name, triggers_action FROM ipd_setup_round_outcomes WHERE is_active=1 ORDER BY id ASC");
                    if($qOut) {
                        while($out = $qOut->fetch_assoc()) {
                            $outOpts .= "<option value='".htmlspecialchars($out['outcome_name'], ENT_QUOTES)."' data-trigger='".htmlspecialchars($out['triggers_action'], ENT_QUOTES)."'>".htmlspecialchars($out['outcome_name'])."</option>";
                        }
                    }
                    
                    $wardOpts = "<option value=''>-- Select Target Ward --</option>";
                    $qWard = $conn->query("SELECT id, ward_name FROM ipd_wards WHERE is_active=1");
                    if($qWard) {
                        while($w = $qWard->fetch_assoc()) $wardOpts .= "<option value='{$w['id']}'>".htmlspecialchars($w['ward_name'])."</option>";
                    }

                    $theatreRmOpts = "<option value=''>-- Select Operating Theatre --</option>";
                    $qTRm = $conn->query("SELECT id, room_name FROM ipd_setup_theatre_rooms WHERE is_active=1");
                    if($qTRm) {
                        while($r = $qTRm->fetch_assoc()) $theatreRmOpts .= "<option value='{$r['id']}'>".htmlspecialchars($r['room_name'])."</option>";
                    }

                    $procOpts = "<option value=''>-- Select Surgical Procedure --</option>";
                    $qP = $conn->query("SELECT id, procedure_name FROM ipd_setup_surgical_procedures WHERE is_active=1");
                    if($qP) {
                        while($p = $qP->fetch_assoc()) $procOpts .= "<option value='{$p['id']}'>".htmlspecialchars($p['procedure_name'])."</option>";
                    }

                    $surgOpts = "<option value=''>-- Select Primary Surgeon --</option>";
                    $qS = $conn->query("SELECT staff_id, first_name, last_name FROM staff WHERE is_doctor_id = 1 AND is_active=1");
                    if($qS) {
                        while($s = $qS->fetch_assoc()) $surgOpts .= "<option value='{$s['staff_id']}'>Dr. ".htmlspecialchars($s['first_name']." ".$s['last_name'])."</option>";
                    }

                    $html .= "
                    <div class='col-12 p-3 bg-primary bg-opacity-10 border border-primary rounded shadow-sm my-3'>
                        <label class='small fw-bold text-primary mb-1'><i class='fa-solid fa-bed-pulse me-1'></i> {$lbl} <span class='text-danger'>*</span></label>
                        <select name='native_clinical_outcome' id='native_clinical_outcome' class='form-select fw-bold border-primary mb-2' required>
                            {$outOpts}
                        </select>
                        
                        <div id='transfer_workflow_container' style='display:none;' class='mt-3 p-3 bg-white border border-danger rounded shadow-sm'>
                            <div class='form-check form-switch mb-3 pb-3 border-bottom'>
                                <input class='form-check-input' type='checkbox' id='is_surgical_transfer' name='is_surgical_transfer' value='1' style='transform:scale(1.2); cursor:pointer;'>
                                <label class='form-check-label ms-2 fw-bold text-danger' for='is_surgical_transfer' style='cursor:pointer;'>Transfer to Operating Theatre (Surgical Case)</label>
                            </div>
                            
                            <div id='standard_transfer_box'>
                                <label class='small fw-bold text-danger mb-1'><i class='fa-solid fa-hospital-user me-1'></i> Target Ward for Transfer <span class='text-danger'>*</span></label>
                                <select name='transfer_ward_id' id='transfer_ward_id' class='form-select fw-bold border-danger mb-3'>{$wardOpts}</select>
                            </div>
                            
                            <div id='surgical_transfer_box' style='display:none;'>
                                <label class='small fw-bold text-danger mb-1'>Operating Theatre Room <span class='text-danger'>*</span></label>
                                <select name='theatre_room_id' id='theatre_room_id' class='form-select fw-bold border-danger mb-2'>{$theatreRmOpts}</select>
                                
                                <label class='small fw-bold text-danger mb-1'>Surgical Procedure <span class='text-danger'>*</span></label>
                                <select name='theatre_procedure_id' id='theatre_procedure_id' class='form-select fw-bold border-danger mb-2'>{$procOpts}</select>
                                
                                <label class='small fw-bold text-danger mb-1'>Primary Surgeon <span class='text-danger'>*</span></label>
                                <select name='theatre_surgeon_id' id='theatre_surgeon_id' class='form-select fw-bold border-danger mb-3'>{$surgOpts}</select>
                            </div>
                            
                            <label class='small fw-bold text-danger mb-1'>Transfer / Referral Clinical Notes</label>
                            <textarea name='transfer_notes' class='form-control border-danger' rows='2'></textarea>
                        </div>

                        <div id='next_review_container' style='display:none;' class='mt-3 p-3 bg-white border border-success rounded shadow-sm'>
                            <label class='small fw-bold text-success mb-1'><i class='fa-solid fa-calendar-check me-1'></i> Next Review / Follow-up Date <span id='req_rev_star' class='text-danger' style='display:none;'>*</span></label>
                            <input type='datetime-local' name='next_review_date' id='next_review_date' class='form-control fw-bold border-success' min='".date('Y-m-d\TH:i')."'>
                        </div>
                    </div>";
                }
                elseif ($type === 'Native: Fluid Chart') {
                    $fluidIn = ""; $fluidOut = "";
                    $qFl = $conn->query("SELECT fluid_name, fluid_category FROM ipd_setup_fluid_types WHERE is_active=1 ORDER BY fluid_name ASC");
                    if($qFl) {
                        while($fl = $qFl->fetch_assoc()) {
                            if ($fl['fluid_category'] == 'Intake') {
                                $fluidIn .= "<option value='".htmlspecialchars($fl['fluid_name'], ENT_QUOTES)."'>".htmlspecialchars($fl['fluid_name'])."</option>";
                            } else {
                                $fluidOut .= "<option value='".htmlspecialchars($fl['fluid_name'], ENT_QUOTES)."'>".htmlspecialchars($fl['fluid_name'])."</option>";
                            }
                        }
                    }
                    $fluidData = base64_encode(json_encode(['IN' => $fluidIn, 'OUT' => $fluidOut]));
                    
                    $html .= "
                    <div class='col-12 mt-3 p-3 bg-info bg-opacity-10 border border-info rounded shadow-sm'>
                        <h6 class='fw-bold text-info small text-uppercase mb-3'><i class='fa-solid fa-droplet me-2'></i> {$lbl}</h6>
                        <div id='fluid_dynamic_container'></div>
                        <button type='button' class='btn btn-sm btn-info text-white fw-bold mt-2 shadow-sm' onclick='addFluidRow(\"".htmlspecialchars($fluidData, ENT_QUOTES)."\")'>
                            <i class='fa-solid fa-plus me-1'></i> Add Fluid Entry
                        </button>
                    </div>";
                }
                elseif ($type === 'Native: Medication Chart' || $type === 'native_medication') {
                    $medStatusOpts = "";
                    $qMedStat = $conn->query("SELECT status_name FROM ipd_setup_med_admin_status WHERE is_active=1 ORDER BY id ASC");
                    if($qMedStat) {
                        while($ms = $qMedStat->fetch_assoc()) {
                            $sel = ($ms['status_name'] == 'Administered Successfully' || $ms['status_name'] == 'Given') ? 'selected' : '';
                            $medStatusOpts .= "<option value='".htmlspecialchars($ms['status_name'], ENT_QUOTES)."' $sel>".htmlspecialchars($ms['status_name'])."</option>";
                        }
                    }

                    $medsHtml = "<table class='table table-bordered table-sm align-middle bg-white'>
                        <thead class='table-light'><tr><th class='text-center'>Select</th><th>Medication</th><th>Dose</th><th>Time</th><th>Status</th><th>Remarks</th><th class='text-center'>Action</th></tr></thead><tbody>";
                    
                    $qRx = $conn->query("SELECT id, drug_name, strength, formulation, dose, frequency, status FROM clinical_prescriptions WHERE visit_id = $visit_id AND status NOT IN ('Rejected', 'Cancelled', 'Stopped') ORDER BY id DESC");
                    
                    if ($qRx && $qRx->num_rows > 0) {
                        while($rx = $qRx->fetch_assoc()) {
                            $is_dispensed = ($rx['status'] === 'Dispensed');
                            $disabled = $is_dispensed ? '' : 'disabled';
                            
                            $badge = "<span class='badge bg-warning text-dark shadow-sm'><i class='fa-solid fa-clock me-1'></i> Awaiting Pharmacy ({$rx['status']})</span>";
                            $rowClass = "bg-light opacity-75";
                            
                            if ($is_dispensed) {
                                $badge = "<span class='badge bg-success shadow-sm'><i class='fa-solid fa-check-circle me-1'></i> Ready to Chart</span>";
                                $rowClass = "";
                            } elseif ($rx['status'] === 'Returned') {
                                $badge = "<span class='badge bg-dark shadow-sm'><i class='fa-solid fa-rotate-left me-1'></i> Returned to Stock</span>";
                                $disabled = 'disabled';
                            }

                            $medsHtml .= "
                            <tr class='$rowClass'>
                                <td class='text-center'>
                                    <input type='checkbox' name='med_chart_id[]' value='{$rx['id']}' class='form-check-input med-chart-checkbox border-secondary' style='transform:scale(1.3); cursor:pointer;' $disabled>
                                    <input type='hidden' name='med_chart_id_hidden[]' value='{$rx['id']}' disabled class='med-input-{$rx['id']}'>
                                </td>
                                <td><b class='text-dark'>{$rx['drug_name']}</b><br><small class='text-muted'>Ordered: {$rx['dose']} {$rx['frequency']}</small><br>$badge</td>
                                <td><input type='text' name='med_chart_dose[{$rx['id']}]' class='form-control form-control-sm fw-bold med-input-{$rx['id']}' value='{$rx['dose']}' $disabled required></td>
                                <td><input type='time' name='med_chart_time[{$rx['id']}]' class='form-control form-control-sm med-input-{$rx['id']}' value='".date('H:i')."' $disabled required></td>
                                <td><select name='med_chart_status[{$rx['id']}]' class='form-select form-select-sm fw-bold med-input-{$rx['id']}' $disabled required>{$medStatusOpts}</select></td>
                                <td><input type='text' name='med_chart_remarks[{$rx['id']}]' class='form-control form-control-sm med-input-{$rx['id']}' placeholder='Notes...' $disabled></td>
                                <td class='text-center'><button type='button' class='btn btn-sm btn-outline-danger shadow-sm fw-bold py-1' onclick='stopActivePrescription({$rx['id']})' title='Stop / Discontinue Medication'><i class='fa-solid fa-ban'></i> Stop</button></td>
                            </tr>";
                        }
                    } else {
                        $medsHtml .= "<tr><td colspan='7' class='text-center text-muted py-4 fw-bold'>No active prescriptions found for this patient.</td></tr>";
                    }
                    $medsHtml .= "</tbody></table>";
                    
                    $html .= "
                    <div class='col-12 p-3 bg-warning bg-opacity-10 border border-warning rounded-3 shadow-sm my-3'>
                        <h6 class='fw-bold text-warning mb-3 text-uppercase'><i class='fa-solid fa-pills me-2'></i> {$lbl} <span class='text-danger ms-2' style='font-size:12px; text-transform:none;'>(Only fully dispensed drugs can be charted)</span></h6>
                        <div class='table-responsive'>{$medsHtml}</div>
                    </div>";
                }
                elseif (strpos($type, 'ConfigMap:') === 0) {
                    $mapType = trim(explode(':', $type)[1]);
                    $html .= "<div class='col-12 mt-3 mb-2 border-bottom pb-1'><h6 class='fw-bold text-uppercase mb-0 small' style='color:#0284c7;'><i class='fa-solid fa-link me-2'></i> Mapped Database Setup: {$lbl}</h6></div>";
                    
                    if ($mapType === 'Vitals') {
                        $html .= "<div class='col-12'><div class='row g-2 mt-1'>";
                        $qVit = $conn->query("SELECT param_name, unit_of_measure FROM ipd_setup_vital_params WHERE is_active=1 ORDER BY id ASC");
                        if($qVit) {
                            while($vit = $qVit->fetch_assoc()) {
                                $pName = htmlspecialchars($vit['param_name']);
                                $uom = !empty($vit['unit_of_measure']) ? " ({$vit['unit_of_measure']})" : "";
                                $safe_attr = htmlspecialchars($pName, ENT_QUOTES);
                                $fname = "dynamic_fields[{$pName}]";
                                $html .= "
                                <div class='col-md-4 col-6'>
                                    <label class='small fw-bold text-muted mb-1'>{$pName}{$uom}</label>
                                    <input type='number' step='any' name='{$fname}' data-field='{$safe_attr}' class='form-control border-danger fw-bold text-danger bg-danger bg-opacity-10' placeholder='Enter value...'>
                                </div>";
                            }
                        }
                        $html .= "</div></div>";
                    }
                    elseif ($mapType === 'Diets') {
                        $opts = "<option value=''>-- Select Diet Type --</option>";
                        $qDiet = $conn->query("SELECT diet_name FROM ipd_setup_diet_types WHERE is_active=1");
                        if($qDiet) {
                            while($d = $qDiet->fetch_assoc()) {
                                $opts .= "<option value='".htmlspecialchars($d['diet_name'], ENT_QUOTES)."'>".htmlspecialchars($d['diet_name'])."</option>";
                            }
                        }
                        $html .= "<div class='col-12 mt-2'><select name='{$name}' data-field='{$safe_attr}' class='form-select fw-bold border-success bg-success bg-opacity-10 text-success' {$req}>{$opts}</select></div>";
                    }
                } 
                elseif ($type === 'Dictionary Reference') {
                    $optsHtml = "<option value=''>-- Select Option --</option>";
                    if (!empty($f['dictionary_reference'])) {
                        $ref = $f['dictionary_reference'];
                        if (strpos($ref, 'reg_') === 0) {
                            $rid = (int)str_replace('reg_', '', $ref);
                            $regQ = $conn->query("SELECT target_table, display_column, value_column, filter_condition FROM system_dictionaries_registry WHERE id=$rid");
                            $reg = $regQ ? $regQ->fetch_assoc() : null;
                            if ($reg) {
                                $tbl = $reg['target_table']; $disp = $reg['display_column']; $val = $reg['value_column']; $cond = $reg['filter_condition'];
                                $whr = !empty($cond) ? "WHERE $cond" : "";
                                $qList = $conn->query("SELECT `$val`, `$disp` FROM `$tbl` $whr");
                                if($qList) {
                                    while($l = $qList->fetch_assoc()) {
                                        $optsHtml .= "<option value='".htmlspecialchars($l[$disp], ENT_QUOTES)."'>".htmlspecialchars($l[$disp])."</option>";
                                    }
                                }
                            }
                        } elseif (strpos($ref, 'custom_') === 0) {
                            $cid = (int)str_replace('custom_', '', $ref);
                            $qList = $conn->query("SELECT item_name FROM ipd_custom_dict_items WHERE dict_id=$cid AND is_active=1");
                            if($qList) {
                                while($l = $qList->fetch_assoc()) {
                                    $optsHtml .= "<option value='".htmlspecialchars($l['item_name'], ENT_QUOTES)."'>".htmlspecialchars($l['item_name'])."</option>";
                                }
                            }
                        }
                    }
                    $html .= "<div class='col-12 mt-3'><label class='small fw-bold text-muted mb-1'>{$lbl} {$req_star}</label><select name='{$name}' data-field='{$safe_attr}' class='form-select fw-bold select2-basic' style='width:100%;' {$req}>{$optsHtml}</select></div>";
                }
                else {
                    $html .= "<div class='col-12 mt-3'><label class='small fw-bold text-muted mb-1'>{$lbl} {$req_star}</label>";
                    $ltype = strtolower($type);
                    
                    if (strpos($ltype, 'text') !== false && strpos($ltype, 'long') !== false) {
                        $html .= "<textarea name='{$name}' data-field='{$safe_attr}' class='form-control rich-text-editor bg-white' rows='4' {$req} placeholder='Enter detailed clinical notes...'></textarea>";
                    } elseif ($type === 'Number' || $type === 'Numeric Value') {
                        $html .= "<input type='number' step='any' name='{$name}' data-field='{$safe_attr}' class='form-control fw-bold' {$req} placeholder='Enter number...'>";
                    } elseif ($type === 'Date' || $type === 'Date Picker') {
                        $html .= "<input type='date' name='{$name}' data-field='{$safe_attr}' class='form-control fw-bold' {$req}>";
                    } elseif ($type === 'Select Dropdown' || $type === 'Select Dropdown (Custom Options)') {
                        $opts = explode(',', $f['options_csv']);
                        $html .= "<select name='{$name}' data-field='{$safe_attr}' class='form-select fw-bold' {$req}><option value=''>-- Select Option --</option>";
                        foreach($opts as $o) if(trim($o)!=='') $html .= "<option value='".htmlspecialchars(trim($o))."'>".htmlspecialchars(trim($o))."</option>";
                        $html .= "</select>";
                    } elseif ($type === 'Radio Buttons (Single Option)' || strpos($type, 'Radio') !== false) {
                        $opts = explode(',', $f['options_csv']);
                        $html .= "<div class='d-flex flex-wrap gap-3 mt-1'>";
                        foreach($opts as $idx => $o) {
                            $o = trim($o); if($o==='') continue;
                            $rid = "radio_{$f['id']}_{$idx}";
                            $html .= "<div class='form-check'><input class='form-check-input' type='radio' name='{$name}' data-field='{$safe_attr}' id='{$rid}' value='".htmlspecialchars($o, ENT_QUOTES)."' {$req}><label class='form-check-label fw-bold text-dark' for='{$rid}'>".htmlspecialchars($o)."</label></div>";
                        }
                        $html .= "</div>";
                    } else {
                        $html .= "<input type='text' name='{$name}' data-field='{$safe_attr}' class='form-control fw-bold' {$req} placeholder='Enter value...'>";
                    }
                    $html .= "</div>";
                }
            }
        }
        $html .= "</div>";

        $full_body = "
        <form id='universalActionForm' onsubmit='return false;'>
            <input type='hidden' name='action' value='save_pool_action'>
            <input type='hidden' name='form_id' value='$form_id'>
            <input type='hidden' name='visit_id' value='$visit_id'>
            <input type='hidden' name='patient_no' value='".$conn->real_escape_string($_POST['patient_no'] ?? '')."'>
            <input type='hidden' name='edit_timestamp' id='edit_timestamp' value=''>
            <div class='p-3 bg-white border rounded shadow-sm'>$html</div>
        </form>";

        ob_end_clean(); echo json_encode(['status' => 'success', 'title' => $fName, 'html' => $full_body]); exit;
    }

    if ($action === 'save_pool_action') {
        $visit_id = (int)$_POST['visit_id'];
        $patient_no = $_POST['patient_no'];
        $module_name = "form_" . (int)$_POST['form_id'];
        $is_edit = !empty($_POST['edit_timestamp']);
        $anchor_time = $is_edit ? $_POST['edit_timestamp'] : date('Y-m-d H:i:s');

        validateFormAccess($conn, $visit_id, $is_edit);

        $conn->begin_transaction();

        if ($is_edit) {
            if(!$conn->query("DELETE FROM clinical_diagnoses WHERE visit_id=$visit_id AND created_at='$anchor_time'")) throw new Exception("Edit Reset Failed (Diag): " . $conn->error);
            if(!$conn->query("UPDATE clinical_prescriptions SET status='Cancelled' WHERE visit_id=$visit_id AND created_at='$anchor_time' AND status='Pending Pharmacy'")) throw new Exception("Edit Reset Failed (Rx): " . $conn->error);
            if(!$conn->query("UPDATE ipd_patient_service_requests SET clinical_status='Cancelled' WHERE visit_id=$visit_id AND requested_at='$anchor_time' AND clinical_status='Pending'")) throw new Exception("Edit Reset Failed (Svc): " . $conn->error);
            if(!$conn->query("UPDATE clinical_admission_requests SET status='Cancelled' WHERE visit_master_id=$visit_id AND created_at='$anchor_time' AND status='Pending'")) throw new Exception("Edit Reset Failed (Admit): " . $conn->error);
            if(!$conn->query("UPDATE ipd_medication_charts SET is_deleted=1 WHERE visit_id=$visit_id AND entry_time='$anchor_time'")) throw new Exception("Edit Reset Failed (Med Chart): " . $conn->error);
            if(!$conn->query("UPDATE ipd_fluid_charts SET is_deleted=1 WHERE visit_id=$visit_id AND recorded_at='$anchor_time'")) throw new Exception("Edit Reset Failed (Fluid Chart): " . $conn->error);
            if(!$conn->query("UPDATE ipd_theatre_requests SET status='Cancelled' WHERE visit_id=$visit_id AND created_at='$anchor_time' AND status='Scheduled'")) throw new Exception("Edit Reset Failed (Theatre): " . $conn->error);
        }

        if (!empty($_POST['diag_icd'])) {
            $principal_code = $_POST['diag_principal'] ?? '';
            $diag_summary = [];

            $stmtDiag = $conn->prepare("INSERT INTO clinical_diagnoses (visit_id, patient_no, code_type, code, gdrg_mapped_code, description, is_principal, diagnosis_type, doctor_id, created_at) VALUES (?, ?, 'ICD-10', ?, ?, ?, ?, 'New', ?, ?)");
            if (!$stmtDiag) throw new Exception("Prepare Diagnosis Failed: " . $conn->error);
            
            foreach($_POST['diag_icd'] as $idx => $icd) {
                $desc = $_POST['diag_desc'][$idx];
                $gdrg = $_POST['diag_gdrg'][$idx];
                if($gdrg === 'Unmapped') $gdrg = null;
                $is_princ = ($icd === $principal_code) ? 1 : 0;
                
                $stmtDiag->bind_param("issssiis", $visit_id, $patient_no, $icd, $gdrg, $desc, $is_princ, $staff_id, $anchor_time);
                if (!$stmtDiag->execute()) throw new Exception("Execute Diagnosis Failed: " . $stmtDiag->error);

                $diag_summary[] = ($is_princ ? "[PRINCIPAL] " : "[SECONDARY] ") . $icd . " - " . $desc . ($gdrg ? " (G-DRG: $gdrg)" : "");
            }
            $stmtDiag->close();
            $_POST['dynamic_fields']['Clinical Diagnoses'] = implode("<br>", $diag_summary);
        }

        if (!empty($_POST['native_clinical_outcome'])) {
            $outcome = $_POST['native_clinical_outcome'];
            $_POST['dynamic_fields']['Patient Disposition / Outcome'] = $outcome;

            $qOutAct = $conn->query("SELECT triggers_action FROM ipd_setup_round_outcomes WHERE outcome_name = '".$conn->real_escape_string($outcome)."' LIMIT 1");
            $outActRow = $qOutAct ? $qOutAct->fetch_assoc() : null;
            $action_trigger = $outActRow['triggers_action'] ?? '';

            if ($action_trigger === 'direct_discharge') {
                if(!$conn->query("UPDATE ipd_admission_episodes SET status = 'Discharged', discharge_outcome = '$outcome', discharge_date = '$anchor_time', discharged_by = $staff_id WHERE visit_master_id = $visit_id")) throw new Exception("Direct Discharge Update Failed: " . $conn->error);
                
                $nr_date = $_POST['next_review_date'] ?? null;
                if(!empty($nr_date)) {
                    if(!$conn->query("UPDATE ipd_admission_episodes SET next_review_date = '$nr_date' WHERE visit_master_id = $visit_id")) throw new Exception("Discharge Review Date Failed: " . $conn->error);
                    $_POST['dynamic_fields']['Follow-up / Review Date'] = date($global_date_format, strtotime($nr_date));
                    $_POST['dynamic_fields']['_raw_next_review_date'] = $nr_date;
                }
                $qBed = $conn->query("SELECT bed_id FROM ipd_admission_episodes WHERE visit_master_id = $visit_id");
                if($qBed && $b = $qBed->fetch_assoc()) {
                    if(!$conn->query("UPDATE ipd_beds SET bed_status_id = 4, bed_status = 'Housekeeping', occupancy_status = 'Vacant' WHERE id = " . (int)$b['bed_id'])) throw new Exception("Bed Housekeeping Update Failed: " . $conn->error);
                }
                $_POST['dynamic_fields']['Direct Discharge'] = "Patient directly discharged. Bed vacated.";

            } elseif ($action_trigger === 'pending_discharge') {
                if(!$conn->query("UPDATE ipd_admission_episodes SET status = 'Pending Discharge' WHERE visit_master_id = $visit_id")) throw new Exception("Pending Discharge Update Failed: " . $conn->error);
                
                $nr_date = $_POST['next_review_date'] ?? null;
                if(!empty($nr_date)) {
                    if(!$conn->query("UPDATE ipd_admission_episodes SET next_review_date = '$nr_date' WHERE visit_master_id = $visit_id")) throw new Exception("Review Date Update Failed: " . $conn->error);
                    $_POST['dynamic_fields']['Follow-up / Review Date'] = date($global_date_format, strtotime($nr_date));
                    $_POST['dynamic_fields']['_raw_next_review_date'] = $nr_date;
                }
            } elseif ($action_trigger === 'transfer_workflow') {
                $is_surgical = isset($_POST['is_surgical_transfer']) ? 1 : 0;
                $t_notes = trim($_POST['transfer_notes'] ?? '');
                $qEp = $conn->query("SELECT id, ward_id, bed_id, status FROM ipd_admission_episodes WHERE visit_master_id = $visit_id LIMIT 1");
                $ep = $qEp ? $qEp->fetch_assoc() : null;
                
                if ($is_surgical) {
                    $th_room_id = (int)$_POST['theatre_room_id'];
                    $th_proc_id = (int)$_POST['theatre_procedure_id'];
                    $th_surg_id = (int)$_POST['theatre_surgeon_id'];
                    
                    $qProcName = $conn->query("SELECT procedure_name FROM ipd_setup_surgical_procedures WHERE id = $th_proc_id");
                    $proc_name = $qProcName ? ($qProcName->fetch_assoc()['procedure_name'] ?? 'Surgical Procedure') : 'Surgical Procedure';
                    
                    if(!$conn->query("UPDATE ipd_admission_episodes SET status = 'In Theatre' WHERE visit_master_id = $visit_id")) throw new Exception("In Theatre Update Failed: " . $conn->error);
                    
                    if($ep) {
                        $origin_episode_id = $ep['id'];
                        $origin_bed_id = $ep['bed_id'];
                        $qStat = $conn->query("SELECT id FROM ipd_setup_bed_statuses WHERE status_name = 'Undergoing Surgical Procedure'");
                        $stat = $qStat ? $qStat->fetch_assoc() : null;
                        $stat_id = $stat ? $stat['id'] : 2; 
                        
                        if(!$conn->query("UPDATE ipd_beds SET bed_status_id = $stat_id, bed_status = 'Undergoing Surgical Procedure', occupancy_status = 'Reserved for Surgery' WHERE id = $origin_bed_id")) throw new Exception("Bed Reservation Failed: " . $conn->error);
                        
                        $stmtTh = $conn->prepare("INSERT INTO ipd_theatre_requests (visit_id, surgeon_id, procedure_name, remarks, status, requested_by, origin_episode_id, origin_bed_id, room_id, created_at) VALUES (?, ?, ?, ?, 'Scheduled', ?, ?, ?, ?, ?)");
                        if (!$stmtTh) throw new Exception("Theatre Request Prepare Failed: " . $conn->error);
                        
                        $stmtTh->bind_param("iissiiiis", $visit_id, $th_surg_id, $proc_name, $t_notes, $staff_id, $origin_episode_id, $origin_bed_id, $th_room_id, $anchor_time);
                        if(!$stmtTh->execute()) throw new Exception("Theatre Request Execute Failed: " . $stmtTh->error);
                    }
                    $_POST['dynamic_fields']['Theatre Transfer'] = "Patient transferred to Operating Theatre for: $proc_name. Bed Reserved.";
                } else {
                    $target_ward = (int)($_POST['transfer_ward_id'] ?? 0);
                    if($target_ward > 0 && $ep) {
                        $from_ward = $ep['ward_id'];
                        $from_bed = $ep['bed_id'];
                        $transfer_type = ($ep['status'] === 'In Theatre') ? 'Theatre Transfer' : 'Ward Transfer';
                        
                        $qWName = $conn->query("SELECT ward_name FROM ipd_wards WHERE id=$target_ward");
                        $w_name = $qWName ? ($qWName->fetch_assoc()['ward_name'] ?? 'Unknown Ward') : 'Unknown Ward';
                        
                        $_POST['dynamic_fields']['Transfer Target'] = $w_name;
                        $_POST['dynamic_fields']['Transfer Notes'] = $t_notes;
                        
                        $stmtReq = $conn->prepare("INSERT INTO clinical_admission_requests (visit_master_id, patient_no, transfer_type, target_ward_id, from_ward_id, from_bed_id, requested_ward, admission_diagnosis, treatment_plan, status, requested_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, 'Internal Ward Transfer', ?, 'Pending', ?, ?)");
                        if (!$stmtReq) throw new Exception("Ward Request Prepare Failed: " . $conn->error);
                        
                        $stmtReq->bind_param("issiiissis", $visit_id, $patient_no, $transfer_type, $target_ward, $from_ward, $from_bed, $w_name, $t_notes, $staff_id, $anchor_time);
                        if(!$stmtReq->execute()) throw new Exception("Ward Request Execute Failed: " . $stmtReq->error);
                    }
                }
            }
        }
        
        if (!empty($_POST['order_service'])) {
            $stmtQ = $conn->prepare("INSERT INTO ipd_patient_service_requests (visit_id, patient_no, ipd_service_id, billed_amount, requested_by, requested_at) VALUES (?, ?, ?, 0, ?, ?)");
            if (!$stmtQ) throw new Exception("Service Request Prepare Failed: " . $conn->error);
            
            foreach ($_POST['order_service'] as $svc_str) {
                $parts = explode('||', $svc_str); $svc_id = (int)$parts[0];
                $stmtQ->bind_param("isiis", $visit_id, $patient_no, $svc_id, $staff_id, $anchor_time); 
                if(!$stmtQ->execute()) throw new Exception("Service Request Execute Failed: " . $stmtQ->error);
                $_POST['dynamic_fields']['Investigations / Services Ordered'][] = "Service Requested ID: $svc_id";
            }
        }

        if (!empty($_POST['rx_drug'])) {
            $dispensary = $_POST['dispensing_pharmacy'] ?? '';
            $stmtRx = $conn->prepare("INSERT INTO clinical_prescriptions (visit_id, patient_no, service_id, drug_name, formulation, strength, dose, frequency, duration_days, quantity, dispensing_pharmacy, remarks, prescribed_by, status, created_at, start_date, end_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pending Pharmacy', ?, ?, ?)");
            if (!$stmtRx) throw new Exception("Prescription Prepare Failed: " . $conn->error);
            
            foreach ($_POST['rx_drug'] as $index => $drug_compound) {
                if (empty($drug_compound)) continue;
                
                $parts = explode('||', $drug_compound);
                $service_id = (int)$parts[0]; 
                $drug_name = $parts[1];
                
                $form = $_POST['rx_form'][$index] ?? ''; 
                $strength = $_POST['rx_strength'][$index] ?? '';
                $dose = $_POST['rx_dose'][$index] ?? ''; 
                $freq = $_POST['rx_freq'][$index] ?? '';
                $dur = (int)($_POST['rx_dur'][$index] ?? 1); 
                $total_qty = (int)($_POST['rx_qty'][$index] ?? 1); 
                $rem = $_POST['rx_remarks'][$index] ?? ''; 
                
                $sd = !empty($_POST['rx_start'][$index]) ? $_POST['rx_start'][$index] : date('Y-m-d'); 
                $ed = !empty($_POST['rx_end'][$index]) ? $_POST['rx_end'][$index] : date('Y-m-d', strtotime($sd . " + $dur days"));
                
                $stmtRx->bind_param("isisssssiississs", $visit_id, $patient_no, $service_id, $drug_name, $form, $strength, $dose, $freq, $dur, $total_qty, $dispensary, $rem, $staff_id, $anchor_time, $sd, $ed);
                if(!$stmtRx->execute()) throw new Exception("Prescription Execute Failed: " . $stmtRx->error);
                
                $_POST['dynamic_fields']['Prescriptions Ordered'][] = "<b class='text-primary fs-6'>{$drug_name} {$strength} {$form}</b><br><span class='badge bg-light text-dark border'>Sig: {$dose} {$freq} for {$dur} Days</span> <span class='badge bg-success bg-opacity-10 text-success border border-success'>Qty to Dispense: {$total_qty}</span>";
            }
            $stmtRx->close();
        }

        if (!empty($_POST['med_chart_id'])) {
            $stmtMc = $conn->prepare("INSERT INTO ipd_medication_charts (visit_id, prescription_id, administered_dose, status, remarks, administered_by, administered_at, entry_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            if (!$stmtMc) throw new Exception("Med Chart Prepare Failed: " . $conn->error);
            
            foreach($_POST['med_chart_id'] as $rx_id) {
                $rx_id = (int)$rx_id;
                $dose = $_POST['med_chart_dose'][$rx_id] ?? '';
                $time = $_POST['med_chart_time'][$rx_id] ?? date('H:i');
                $mStatus = $_POST['med_chart_status'][$rx_id] ?? 'Given';
                $rem = $_POST['med_chart_remarks'][$rx_id] ?? '';
                
                $admin_at = date('Y-m-d', strtotime($anchor_time)) . ' ' . $time . ':00';
                
                $stmtMc->bind_param("iisssiss", $visit_id, $rx_id, $dose, $mStatus, $rem, $staff_id, $admin_at, $anchor_time);
                if(!$stmtMc->execute()) throw new Exception("Med Chart Execute Failed: " . $stmtMc->error);
                
                $_POST['dynamic_fields']['Medications Charted / Administered'][] = "{$mStatus} (RX #{$rx_id})";
            }
            $stmtMc->close();
        }

        if (!empty($_POST['fluid_chart_type'])) {
            $stmtFl = $conn->prepare("INSERT INTO ipd_fluid_charts (visit_id, fluid_type, volume_ml, remarks, recorded_by, recorded_at) VALUES (?, ?, ?, ?, ?, ?)");
            if (!$stmtFl) throw new Exception("Fluid Chart Prepare Failed: " . $conn->error);
            
            foreach($_POST['fluid_chart_type'] as $idx => $fType) {
                $fType = trim($fType);
                $vol = (int)($_POST['fluid_chart_vol'][$idx] ?? 0);
                $rem = trim($_POST['fluid_chart_remarks'][$idx] ?? '');
                
                if(!empty($fType) && $vol > 0) {
                    $stmtFl->bind_param("isisis", $visit_id, $fType, $vol, $rem, $staff_id, $anchor_time);
                    if(!$stmtFl->execute()) throw new Exception("Fluid Chart Execute Failed: " . $stmtFl->error);
                    $_POST['dynamic_fields']['Fluids Charted (Intake/Output)'][] = "{$fType}: {$vol}ml";
                }
            }
            $stmtFl->close();
        }

        if (isset($_POST['dynamic_fields']) && is_array($_POST['dynamic_fields'])) {
            foreach ($_POST['dynamic_fields'] as $key => $value) {
                $val = is_array($value) ? implode('<br>', $value) : trim((string)$value); 
                if ($val !== '') {
                    if ($is_edit) {
                        $chkFld = $conn->prepare("SELECT id FROM ipd_dynamic_responses WHERE visit_id=? AND module_name=? AND field_name=? AND recorded_at=? AND is_deleted=0");
                        $chkFld->bind_param("isss", $visit_id, $module_name, $key, $anchor_time);
                        $chkFld->execute(); 
                        $existing = $chkFld->get_result()->fetch_assoc(); 
                        $chkFld->close();

                        if ($existing) {
                            if(!$conn->query("UPDATE ipd_dynamic_responses SET field_value='".$conn->real_escape_string($val)."', edited_at=NOW(), edited_by=$staff_id WHERE id=".$existing['id'])) throw new Exception("Update Dynamic Field Failed: " . $conn->error);
                        } else {
                            if(!$conn->query("INSERT INTO ipd_dynamic_responses (visit_id, module_name, field_name, field_value, recorded_by, recorded_at) VALUES ($visit_id, '$module_name', '".$conn->real_escape_string($key)."', '".$conn->real_escape_string($val)."', $staff_id, '$anchor_time')")) throw new Exception("Insert Dynamic Field Failed: " . $conn->error);
                        }
                    } else {
                        if(!$conn->query("INSERT INTO ipd_dynamic_responses (visit_id, module_name, field_name, field_value, recorded_by, recorded_at) VALUES ($visit_id, '$module_name', '".$conn->real_escape_string($key)."', '".$conn->real_escape_string($val)."', $staff_id, '$anchor_time')")) throw new Exception("Insert Dynamic Field Failed: " . $conn->error);
                    }
                }
            }
        }

        $conn->commit();
        ob_end_clean(); echo json_encode(['status' => 'success', 'message' => 'Record successfully saved.']); exit;
    }

    if ($action === 'delete_pool_action') {
        $visit_id = (int)$_POST['visit_id'];
        $form_id = (int)$_POST['form_id'];
        $module_name = "form_" . $form_id;
        $anchor_time = $_POST['recorded_at'];

        validateFormAccess($conn, $visit_id, true);

        $conn->begin_transaction();
        
        if(!$conn->query("UPDATE ipd_dynamic_responses SET is_deleted=1, deleted_at=NOW(), deleted_by=$staff_id WHERE visit_id=$visit_id AND module_name='$module_name' AND recorded_at='$anchor_time'")) throw new Exception("Delete Dynamic Field Failed: " . $conn->error);
        if(!$conn->query("UPDATE ipd_fluid_charts SET is_deleted=1 WHERE visit_id=$visit_id AND recorded_at='$anchor_time'")) throw new Exception("Delete Fluid Chart Failed: " . $conn->error);
        if(!$conn->query("UPDATE ipd_medication_charts SET is_deleted=1 WHERE visit_id=$visit_id AND entry_time='$anchor_time'")) throw new Exception("Delete Med Chart Failed: " . $conn->error);
        
        if(!$conn->query("UPDATE clinical_prescriptions SET status='Cancelled' WHERE visit_id=$visit_id AND created_at='$anchor_time' AND status='Pending Pharmacy'")) throw new Exception("Cancel Rx Failed: " . $conn->error);
        if(!$conn->query("UPDATE ipd_patient_service_requests SET clinical_status='Cancelled' WHERE visit_id=$visit_id AND requested_at='$anchor_time' AND clinical_status='Pending'")) throw new Exception("Cancel Service Failed: " . $conn->error);
        if(!$conn->query("UPDATE clinical_admission_requests SET status='Cancelled' WHERE visit_master_id=$visit_id AND created_at='$anchor_time' AND status='Pending'")) throw new Exception("Cancel Admit Failed: " . $conn->error);
        if(!$conn->query("UPDATE ipd_theatre_requests SET status='Cancelled' WHERE visit_id=$visit_id AND created_at='$anchor_time' AND status='Scheduled'")) throw new Exception("Cancel Theatre Failed: " . $conn->error);

        $conn->commit();
        ob_end_clean(); echo json_encode(['status' => 'success', 'message' => 'Record permanently voided.']); exit;
    }

} catch (Throwable $e) {
    if(isset($conn) && is_object($conn)) {
        try { $conn->rollback(); } catch(Exception $ex) {}
    }
    while (ob_get_level()) { ob_end_clean(); }
    echo json_encode([
        'status' => 'error', 
        'message' => 'System Error: ' . $e->getMessage() . ' on line ' . $e->getLine()
    ]); 
    exit;
}
?>