<?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";

// Validation Helper for Theatre Workflow Access Rules
function validateTheatreAccess($conn, $req_id, $is_edit) {
    $qRules = $conn->query("SELECT * FROM system_workflow_rules LIMIT 1");
    $rules = $qRules ? $qRules->fetch_assoc() : null;
    if (!$rules) return;

    $qTh = $conn->query("SELECT status FROM ipd_theatre_requests WHERE id = $req_id LIMIT 1");
    $th = $qTh ? $qTh->fetch_assoc() : null;
    $th_status = $th ? $th['status'] : '';
    
    $is_post_surgery = in_array($th_status, ['Completed', 'Cancelled', 'Rejected']);

    if ($is_edit) {
        if ($is_post_surgery && $rules['block_edit_theatre_post_surgery']) throw new Exception("Workflow Rule: Editing is blocked because the surgery has been completed/closed.");
    } else {
        if ($is_post_surgery && $rules['block_new_theatre_post_surgery']) throw new Exception("Workflow Rule: Adding new records is blocked because the surgery has been completed/closed.");
    }
}

try {
    $conn->query("CREATE TABLE IF NOT EXISTS `ipd_theatre_dynamic_responses` (
        `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        `req_id` bigint(20) UNSIGNED NOT NULL,
        `visit_id` bigint(20) UNSIGNED NOT NULL,
        `stage_id` int(11) NOT NULL,
        `field_name` varchar(150) NOT NULL,
        `field_value` text DEFAULT NULL,
        `recorded_by` int(10) UNSIGNED NOT NULL,
        `recorded_at` timestamp NOT NULL DEFAULT current_timestamp(),
        `is_deleted` tinyint(1) DEFAULT 0,
        `edited_at` datetime DEFAULT NULL,
        `edited_by` int(11) DEFAULT NULL,
        `deleted_at` datetime DEFAULT NULL,
        `deleted_by` int(11) DEFAULT NULL,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    if ($action === 'stop_prescription') {
        $rx_id = (int)$_POST['rx_id'];
        $reason = trim($conn->real_escape_string($_POST['reason'] ?? 'Discontinued in Theatre'));
        $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_edit_data') {
        $stage_id = (int)$_POST['stage_id'];
        $req_id = (int)$_POST['req_id'];
        $visit_id = (int)$_POST['visit_id'];
        $recorded_at = $_POST['recorded_at'];

        $data = [];
        $q = $conn->prepare("SELECT field_name, field_value FROM ipd_theatre_dynamic_responses WHERE req_id = ? AND stage_id = ? AND recorded_at = ? AND is_deleted = 0");
        $q->bind_param("iis", $req_id, $stage_id, $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;

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

    if ($action === 'get_action_interface') {
        $visit_id = (int)$_POST['visit_id'];
        $req_id = (int)$_POST['req_id'];
        $stage_id = (int)$_POST['stage_id'];

        $stmtS = $conn->query("SELECT stage_name FROM ipd_setup_clinical_stages WHERE id = $stage_id LIMIT 1");
        $stageMeta = $stmtS ? $stmtS->fetch_assoc() : ['stage_name' => 'Surgical Stage'];
        
        $dyn_html = "";
        
        $qSec = $conn->query("SELECT DISTINCT s.id, s.section_name FROM theatre_form_setup t JOIN ipd_setup_form_sections s ON t.section_id = s.id WHERE t.stage_id = $stage_id AND t.is_active=1 ORDER BY s.id ASC");
        
        while($qSec && $sec = $qSec->fetch_assoc()) {
            $dyn_html .= "<h6 class='fw-bold text-dark small text-uppercase mt-4 mb-3 border-bottom pb-2' style='color:#0ea5e9 !important;'><i class='fa-solid fa-layer-group me-2'></i>".htmlspecialchars($sec['section_name'])."</h6><div class='row g-3'>";
            
            $qFld = $conn->query("SELECT * FROM theatre_form_setup WHERE stage_id = $stage_id AND section_id = {$sec['id']} AND is_active=1 ORDER BY display_order ASC");
            
            while($qFld && $f = $qFld->fetch_assoc()) {
                $req = $f['is_required'] ? 'required' : '';
                $req_star = $f['is_required'] ? "<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 === '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='Theatre / In-Patient Pharmacy' selected>Theatre / In-Patient Pharmacy</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($fq = $dbFreq->fetch_assoc()) {
                            $fOpts .= "<option value='{$fq['freq_code']}'>{$fq['description']}</option>";
                        }
                    }
                    
                    $dyn_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-info rounded-3 shadow-sm my-3'>
                        <div class='bg-info bg-opacity-10 p-3 border-bottom border-info d-flex justify-content-between align-items-center'>
                            <h6 class='fw-bold text-info mb-0 text-uppercase'><i class='fa-solid fa-pills me-2'></i> {$lbl} (Theatre Prescribing Engine)</h6>
                            <select name='dispensing_pharmacy' class='form-select form-select-sm border-info fw-bold text-info dispensary-select' style='width:auto; background:white;'>{$dispOpts}</select>
                        </div>
                        <div class='p-3 bg-light'>
                            <div id='rx_dynamic_container'></div>
                            <button type='button' class='btn btn-sm btn-info text-white fw-bold mt-2 shadow-sm rx-add-btn' onclick='addDynamicRxRow()'>
                                <i class='fa-solid fa-plus me-1'></i> Add Intra-Op Medication
                            </button>
                        </div>
                    </div>";
                }
                elseif ($type === 'native_medication' || $type === 'Native: Medication Chart') {
                    $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>";
                    
                    $dyn_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} (Charting) <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 ($type === 'native_fluid') {
                    $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]));
                    $dyn_html .= "
                    <div class='col-12 mt-3 p-3 bg-primary bg-opacity-10 border border-primary rounded shadow-sm'>
                        <h6 class='fw-bold text-primary small text-uppercase mb-3'><i class='fa-solid fa-droplet me-2'></i> {$lbl} (Theatre I/O)</h6>
                        <div id='fluid_dynamic_container'></div>
                        <button type='button' class='btn btn-sm btn-primary 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 === 'config_map') {
                    $ref = $f['dictionary_reference'];
                    $optsHtml = "<option value=''>-- Select Option --</option>";
                    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>";
                    }
                    $dyn_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 {
                    $dyn_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) {
                        $dyn_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') {
                        $dyn_html .= "<input type='number' step='any' name='{$name}' data-field='{$safe_attr}' class='form-control fw-bold' {$req} placeholder='Enter number...'>";
                    } elseif ($type === 'date') {
                        $dyn_html .= "<input type='date' name='{$name}' data-field='{$safe_attr}' class='form-control fw-bold' {$req}>";
                    } elseif ($type === 'time') {
                        $dyn_html .= "<input type='time' name='{$name}' data-field='{$safe_attr}' class='form-control fw-bold' {$req}>";
                    } elseif ($type === 'select') {
                        $opts = explode(',', $f['field_options']);
                        $dyn_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)!=='') $dyn_html .= "<option value='".htmlspecialchars(trim($o))."'>".htmlspecialchars(trim($o))."</option>";
                        $dyn_html .= "</select>";
                    } elseif ($type === 'radio' || $type === 'checkbox') {
                        $opts = explode(',', $f['field_options']);
                        $dyn_html .= "<div class='d-flex flex-wrap gap-3 mt-1'>";
                        $inputType = $type === 'radio' ? 'radio' : 'checkbox';
                        $arrayBracket = $type === 'checkbox' ? '[]' : '';
                        foreach($opts as $idx => $o) {
                            $o = trim($o); if($o==='') continue;
                            $rid = "opt_{$f['id']}_{$idx}";
                            $dyn_html .= "<div class='form-check'><input class='form-check-input' type='{$inputType}' name='{$name}{$arrayBracket}' data-field='{$safe_attr}' id='{$rid}' value='".htmlspecialchars($o, ENT_QUOTES)."'><label class='form-check-label fw-bold text-dark' for='{$rid}'>".htmlspecialchars($o)."</label></div>";
                        }
                        $dyn_html .= "</div>";
                    } else {
                        $dyn_html .= "<input type='text' name='{$name}' data-field='{$safe_attr}' class='form-control fw-bold' {$req} placeholder='Enter value...'>";
                    }
                    $dyn_html .= "</div>";
                }
            }
            $dyn_html .= "</div>";
        }

        $full_body = "<form id='universalActionForm' onsubmit='return false;'><input type='hidden' name='action' value='save_pool_action'><input type='hidden' name='stage_id' value='$stage_id'><input type='hidden' name='req_id' value='$req_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'>$dyn_html</div></form>";

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

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

        // STRICT BACKEND LOCK VALIDATION
        validateTheatreAccess($conn, $req_id, $is_edit);

        $conn->begin_transaction();

        if ($is_edit) {
            if(!$conn->query("UPDATE ipd_theatre_dynamic_responses SET is_deleted=1 WHERE req_id=$req_id AND stage_id=$stage_id AND recorded_at='$anchor_time'")) throw new Exception("Edit Reset Failed (EAV): " . $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): " . $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 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 (!empty($_POST['rx_drug'])) {
            $dispensary = $_POST['dispensing_pharmacy'] ?? 'Theatre / In-Patient 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] ?? 'Intra-Operative Administration'; 
                
                $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']['Surgical Medications 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-info bg-opacity-10 text-info border border-info'>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] ?? 'Intra-Op Charting');
                
                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']['Surgical Fluids Charted (I/O)'][] = "{$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 !== '') {
                    $stmtEav = $conn->prepare("INSERT INTO ipd_theatre_dynamic_responses (req_id, visit_id, stage_id, field_name, field_value, recorded_by, recorded_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    if (!$stmtEav) throw new Exception("EAV Prepare Failed: " . $conn->error);

                    $stmtEav->bind_param("iiissis", $req_id, $visit_id, $stage_id, $key, $val, $staff_id, $anchor_time);
                    if(!$stmtEav->execute()) throw new Exception("EAV Execute Failed: " . $stmtEav->error);
                }
            }
        }

        if(!$conn->query("UPDATE ipd_theatre_requests SET status = 'In Progress' WHERE id = $req_id AND status = 'Scheduled'")) throw new Exception("Theatre Status Update Failed: " . $conn->error);

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

    if ($action === 'delete_pool_action') {
        $req_id = (int)$_POST['req_id'];
        $visit_id = (int)$_POST['visit_id'];
        $stage_id = (int)$_POST['stage_id'];
        $anchor_time = $_POST['recorded_at'];

        // STRICT BACKEND LOCK VALIDATION
        validateTheatreAccess($conn, $req_id, true);

        $conn->begin_transaction();
        
        if(!$conn->query("UPDATE ipd_theatre_dynamic_responses SET is_deleted=1, deleted_at=NOW(), deleted_by=$staff_id WHERE req_id=$req_id AND stage_id=$stage_id 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);

        $conn->commit();
        ob_end_clean(); echo json_encode(['status' => 'success', 'message' => 'Surgical 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;
}
?>