try {
    let dtDiets, dtFluids, dtVitals, dtFreqs, dtO2Modes, dtO2Flows, dtEquip, dtMedRoutes, dtMedInst, dtBlood, dtIsolation, dtItems, dtRegistry, dtIpdServices, dtCorpTariffs, dtPocRanges, dtPocParams, dtSvcTypes, dtOutcomes;
    window.masterDicts = [];

    $.fn.dataTable.ext.errMode = 'none';

    window.initClinicalCareConfig = function() {
        const apiUrl = '/rimax/application/dripend/systemSetup/ipd/processClinicalCare.php';

        const renderIndex = (data, type, row, meta) => `<strong>${meta.row + 1}</strong>`;
        const renderStatus = (data) => data == 1 ? '<span class="badge bg-success bg-opacity-10 text-success border border-success">Active</span>' : '<span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary">Inactive</span>';
        
        const renderActions = (table, id, isActive) => {
            let toggleClass = isActive == 1 ? 'btn-outline-warning' : 'btn-outline-success';
            let toggleText = isActive == 1 ? '<i class="fa fa-pause"></i>' : '<i class="fa fa-play"></i>';
            return `
                <div class="btn-group shadow-sm">
                    <button class="btn btn-sm btn-primary" onclick="editClinicalRecord('${table}', ${id})" title="Edit"><i class="fa fa-edit"></i></button>
                    <button class="btn btn-sm ${toggleClass}" onclick="toggleData('${table}', ${id}, ${isActive == 1 ? 0 : 1})" title="Toggle Status">${toggleText}</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteData('${table}', ${id})" title="Delete"><i class="fa fa-trash"></i></button>
                </div>
            `;
        };

        function fetchServiceDropdowns() {
            $.post(apiUrl, { action: 'fetch_service_types' }, function(res) {
                if(res && res.status === 'success') {
                    let tOpts = ''; 
                    (res.types || []).forEach(t => tOpts += `<option value="${t.id}">${t.type_name}</option>`);
                    $('#svc_type').html(tOpts);

                    let iOpts = '<option value="">- Select HMO -</option>';
                    (res.insurance || []).forEach(i => iOpts += `<option value="${i.id}">${i.insurance_name}</option>`);
                    $('#corp_ins_id').html(iOpts);
                }
            }, 'json').fail(function() { console.error('Failed to fetch dropdowns'); });
        }
        fetchServiceDropdowns();

        try {
            dtIpdServices = $('#tblIpdServices').DataTable({
                ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'ipd_services' } },
                pageLength: 10,
                columns: [
                    { data: null, render: (d) => {
                        let badge = d.requires_result == 1 ? `<span class="badge bg-success ms-2"><i class="fa fa-chart-line"></i> POC Setup Active</span>` : '';
                        return `<b class="text-primary" style="font-size:15px;">${d.service_name || 'N/A'}</b> ${badge}<br><span class="badge bg-secondary">${d.service_type || 'Uncategorized'}</span>`;
                    }},
                    { data: null, render: (d, t, r, meta) => {
                        let c = meta.settings.json.currency || 'GHS';
                        return `<span class="small text-muted">A:</span> ${c} ${d.cash_price_adult || 0} <br> <span class="small text-muted">C:</span> ${c} ${d.cash_price_child || 0}`;
                    }},
                    { data: null, render: (d, t, r, meta) => {
                        if(d.is_nhis_covered != 1) return '<span class="text-muted">No</span>';
                        let c = meta.settings.json.currency || 'GHS';
                        return `<span class="text-success fw-bold"><i class="fa fa-check"></i> Covered</span><br><span class="small text-muted">A: ${c} ${d.nhis_tariff_adult || 0} | C: ${c} ${d.nhis_tariff_child || 0}</span>`;
                    }},
                    { data: null, render: d => {
                        let html = `<button class="btn btn-sm btn-outline-dark fw-bold mb-1 w-100 text-start" onclick="openCorpTariffs(${d.id}, '${(d.service_name||'').replace(/'/g, "\\'")}')"><i class="fa fa-shield-halved me-1"></i> ${d.corp_count || 0} Ins. Maps</button>`;
                        if(d.requires_result == 1) {
                            html += `<br><button class="btn btn-sm btn-outline-info fw-bold w-100 text-start mb-1" onclick="openPocParameters(${d.id}, '${(d.service_name||'').replace(/'/g, "\\'")}')"><i class="fa fa-list-check me-1"></i> ${d.param_count || 0} Parameters</button>`;
                            if(d.result_type === 'Numeric') {
                                html += `<br><button class="btn btn-sm btn-outline-primary fw-bold w-100 text-start" onclick="openPocRanges(${d.id}, '${(d.service_name||'').replace(/'/g, "\\'")}', '${(d.unit_of_measure||'').replace(/'/g, "\\'")}')"><i class="fa fa-chart-bar me-1"></i> Ref. Ranges</button>`;
                            }
                        }
                        return html;
                    }},
                    { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_services', r.id, r.is_active) }
                ]
            });
            dtSvcTypes = $('#tblSvcTypes').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'svc_type' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_service_types', r.id, r.is_active) }]});
            
            // NEW OUTCOMES DATATABLE
            dtOutcomes = $('#tblOutcomes').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'outcome' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'triggers_action', render: d => d ? `<span class="badge bg-secondary bg-opacity-10 text-dark border border-secondary">${d}</span>` : 'None' }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_round_outcomes', r.id, r.is_active) }]});
            
            dtDiets = $('#tblDiets').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'diet' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'description' }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_diet_types', r.id, r.is_active) }]});
            dtFluids = $('#tblFluids').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'fluid' } }, columns: [{ data: null, render: renderIndex }, { data: 'fluid_category', render: d => d==='Intake'?'<span class="badge bg-info">Intake</span>':'<span class="badge bg-warning text-dark">Output</span>' }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_fluid_types', r.id, r.is_active) }]});
            dtVitals = $('#tblVitals').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'vital' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'unit_of_measure' }, { data: null, render: (d,t,r) => r.critical_low ? `<span class="text-danger">${r.critical_low}</span> - <span class="text-danger">${r.critical_high}</span>` : 'N/A' }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_vital_params', r.id, r.is_active) }]});
            dtFreqs = $('#tblFreqs').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'obs_freq' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'interval_minutes' }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_obs_frequencies', r.id, r.is_active) }]});
            dtO2Modes = $('#tblO2Modes').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'o2_mode' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_oxygen_modes', r.id, r.is_active) }]});
            dtO2Flows = $('#tblO2Flows').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'o2_flow' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'value_lpm' }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_oxygen_flow_rates', r.id, r.is_active) }]});
            dtEquip = $('#tblEquip').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'equipment' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_ward_equipment', r.id, r.is_active) }]});
            dtMedRoutes = $('#tblMedRoutes').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'med_route' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_med_routes', r.id, r.is_active) }]});
            dtMedInst = $('#tblMedInst').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'med_inst' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_med_instructions', r.id, r.is_active) }]});
            dtBlood = $('#tblBlood').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'blood_prod' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_blood_products', r.id, r.is_active) }]});
            dtIsolation = $('#tblIsolation').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'isolation' } }, columns: [{ data: null, render: renderIndex }, { data: 'name', render: d => `<b>${d}</b>` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_setup_isolation_types', r.id, r.is_active) }]});
            dtItems = $('#tblDictItems').DataTable({ ajax: { url: apiUrl, type: 'POST', data: function(d) { d.action = 'fetch_dict_items'; d.dict_id = $('#active_dict_id').val(); } }, pageLength: 10, columns: [ { data: null, render: renderIndex }, { data: null, render: d => `<b class="text-dark">${d.item_name}</b><br><span class="badge bg-light text-secondary border mt-1">${d.input_type}</span>${d.options_csv ? `<span class="small text-muted ms-1">[ ${d.options_csv} ]</span>` : ''}` }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('ipd_custom_dict_items', r.id, r.is_active) } ] });
            dtRegistry = $('#tblRegistry').DataTable({ ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: 'registry' } }, pageLength: 10, columns: [ { data: null, render: renderIndex }, { data: 'dictionary_name', render: d => `<b class="text-primary">${d}</b>` }, { data: 'target_table', render: d => `<span class="badge bg-dark">${d}</span>` }, { data: 'filter_condition', render: d => d ? `<code class="small text-danger">${d}</code>` : '<span class="text-muted small">None</span>' }, { data: 'is_active', render: renderStatus }, { data: null, orderable: false, render: (d,t,r) => renderActions('system_dictionaries_registry', r.id, r.is_active) } ] });
        } catch(e) { console.error('DataTable init failed', e); }

        window.openIpdServiceModal = function() {
            $('#frmIpdService')[0].reset(); $('#svc_id').val(''); 
            $('#div_nhis_pricing').hide(); $('#div_poc_config').hide(); $('#div_svc_options').hide();
            $('#modalIpdService').modal('show');
        };

        $('#svc_nhis_covered').on('change', function() { if($(this).is(':checked')) $('#div_nhis_pricing').slideDown(); else $('#div_nhis_pricing').slideUp(); });
        $('#svc_req_res').on('change', function() { if($(this).is(':checked')) $('#div_poc_config').slideDown(); else $('#div_poc_config').slideUp(); });
        $('#svc_result_type').on('change', function() { if($(this).val() === 'Options') { $('#div_svc_options').slideDown(); $('#svc_options').prop('required', true); } else { $('#div_svc_options').slideUp(); $('#svc_options').prop('required', false).val(''); } });

        window.openPocParameters = function(service_id, service_name) {
            $('#param_svc_id').val(service_id); $('#lblPocParamName').text(service_name);
            if ($.fn.DataTable.isDataTable('#tblPocParams')) { $('#tblPocParams').DataTable().destroy(); }
            
            dtPocParams = $('#tblPocParams').DataTable({
                ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_poc_params', service_id: service_id } },
                paging: false, info: false, searching: false,
                columns: [
                    { data: 'parameter_name', render: d => `<b class="text-info">${d}</b>` },
                    { data: 'unit_of_measure', render: d => d || '-' },
                    { data: 'result_type' },
                    { data: 'options_csv', render: d => d ? `<span class="small text-muted">${d}</span>` : '-' },
                    { data: null, orderable: false, render: (d,t,r) => `
                        <button class="btn btn-sm btn-light border text-primary" onclick="editClinicalRecord('ipd_poc_parameters', ${r.id})"><i class="fa fa-pen"></i></button>
                        <button class="btn btn-sm btn-light border text-danger" onclick="deleteData('ipd_poc_parameters', ${r.id})"><i class="fa fa-times"></i></button>` 
                    }
                ]
            });
            $('#modalPocParameters').modal('show');
        };

        $('#param_res_type').on('change', function() { 
            if($(this).val() === 'Options') { $('#div_param_options').slideDown(); $('#param_options').prop('required', true); } 
            else { $('#div_param_options').slideUp(); $('#param_options').prop('required', false).val(''); } 
        });

        $('#frmPocParameter').on('submit', function(e) { 
            e.preventDefault(); 
            $.post(apiUrl, $(this).serialize(), res => { 
                if(res.status === 'success') { 
                    $('#frmPocParameter')[0].reset(); 
                    $('#param_svc_id').val($('#param_svc_id').val()); 
                    if(dtPocParams) dtPocParams.ajax.reload(null, false); 
                    if(dtIpdServices) dtIpdServices.ajax.reload(null, false);
                } 
            }); 
        });

        window.openPocRanges = function(service_id, service_name, unit) {
            $('#rng_svc_id').val(service_id);
            let uom = unit ? ` (${unit})` : '';
            $('#lblPocRangeName').text(service_name + uom);
            
            if ($.fn.DataTable.isDataTable('#tblPocRanges')) { $('#tblPocRanges').DataTable().destroy(); }
            dtPocRanges = $('#tblPocRanges').DataTable({
                ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_poc_ranges', service_id: service_id } },
                paging: false, info: false, searching: false,
                columns: [
                    { data: 'gender_target', render: d => `<b>${d}</b>` },
                    { data: null, render: d => `${d.min_age_years} - ${d.max_age_years}` },
                    { data: null, render: d => `<span class="text-success fw-bold">${d.min_value||'-'}</span> to <span class="text-success fw-bold">${d.max_value||'-'}</span>` },
                    { data: null, render: d => `<span class="text-danger small">L: ${d.critical_low||'N/A'}</span> <br> <span class="text-danger small">H: ${d.critical_high||'N/A'}</span>` },
                    { data: null, orderable: false, render: (d,t,r) => `<button class="btn btn-sm btn-light text-danger border" onclick="deleteData('ipd_poc_reference_ranges', ${r.id})"><i class="fa fa-times"></i></button>` }
                ]
            });
            $('#modalPocRanges').modal('show');
        };

        window.openCorpTariffs = function(service_id, service_name) {
            $('#corp_svc_id').val(service_id); 
            $('#lblCorpServiceName').text(`Mapping Insurance for: ${service_name}`);
            if ($.fn.DataTable.isDataTable('#tblCorpTariffs')) { $('#tblCorpTariffs').DataTable().destroy(); }
            
            let sysCurr = dtIpdServices.ajax.json() ? dtIpdServices.ajax.json().currency : 'GHS';

            dtCorpTariffs = $('#tblCorpTariffs').DataTable({
                ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_corp_tariffs', service_id: service_id } },
                paging: false, info: false, searching: false,
                columns: [
                    { data: 'insurance_name', render: d => `<b class="text-dark">${d}</b>` },
                    { data: null, render: d => `<span class="small text-muted">A:</span> ${sysCurr} ${d.tariff_amount_adult || 0}<br><span class="small text-muted">C:</span> ${sysCurr} ${d.tariff_amount_child || 0}` },
                    { data: null, render: d => d.is_copay_required == 1 ? `<span class="text-danger small fw-bold">A: ${sysCurr} ${d.copay_amount_adult || 0}</span><br><span class="text-danger small fw-bold">C: ${sysCurr} ${d.copay_amount_child || 0}</span>` : '<span class="text-muted small">None</span>' },
                    { data: null, orderable: false, render: (d,t,r) => `<button class="btn btn-sm btn-light text-danger border" onclick="deleteData('ipd_service_corporate_tariffs', ${r.id})"><i class="fa fa-times"></i> Remove</button>` }
                ]
            });
            $('#modalCorpTariffs').modal('show');
        };

        function loadSidebarMenu() {
            $('#dynamic-dict-menu').html('<div class="text-center p-3"><div class="spinner-border spinner-border-sm text-primary"></div></div>');
            $.post(apiUrl, { action: 'fetch_master_dicts' }, function(res) {
                if(res && res.status === 'success') {
                    window.masterDicts = res.data || []; let html = '';
                    if(window.masterDicts.length === 0) { html = '<div class="text-muted small p-3 text-center">No custom dictionaries created yet.</div>'; } 
                    else {
                        window.masterDicts.forEach(d => {
                            let icon = d.is_active == 1 ? 'fa-book-medical text-primary' : 'fa-book text-muted';
                            html += `<button class="nav-link text-start rounded-0 border-0 border-bottom dict-tab" data-id="${d.id}" data-name="${d.dict_name}" data-desc="${d.description || ''}"><i class="fa-solid ${icon} me-2 w-20px"></i> ${d.dict_name}</button>`;
                        });
                    }
                    $('#dynamic-dict-menu').html(html);
                }
            }, 'json').fail(function() { $('#dynamic-dict-menu').html('<div class="text-danger small p-3 text-center">Connection Error</div>'); });
        }
        loadSidebarMenu();

        $(document).on('click', '.dict-tab', function() {
            $('.nav-link').removeClass('active'); $(this).addClass('active');
            $('#welcome-state').hide(); $('#items-state').show();
            $('#active_dict_id').val($(this).data('id')); $('#lblDictName').text($(this).data('name')); $('#lblDictDesc').text($(this).data('desc') || 'Manage options for this dictionary.');
            $('.tab-pane').removeClass('show active'); $('#tab-custom-items').addClass('show active'); 
            if(dtItems) dtItems.ajax.reload();
        });

        window.openDictModal = function(type, title) {
            $('#frmUniversalDict')[0].reset(); $('#dict_id').val(''); $('#dict_type').val(type); $('#dictModalTitle').text('Add ' + title);
            let html = '';
            if (type === 'diet') html = `<div class="mb-3"><label class="form-label">Diet Name <span class="text-danger">*</span></label><input type="text" name="dict_name" id="f_name" class="form-control" required></div><div class="mb-3"><label class="form-label">Description</label><input type="text" name="description" id="f_desc" class="form-control"></div>`;
            else if (type === 'fluid') html = `<div class="mb-3"><label class="form-label">Fluid Category <span class="text-danger">*</span></label><select name="fluid_category" id="f_cat" class="form-select" required><option value="Intake">Intake (Oral/IV)</option><option value="Output">Output (Drain/Urine)</option></select></div><div class="mb-3"><label class="form-label">Fluid Name <span class="text-danger">*</span></label><input type="text" name="dict_name" id="f_name" class="form-control" required></div>`;
            else if (type === 'vital') html = `<div class="mb-3"><label class="form-label">Parameter Name <span class="text-danger">*</span></label><input type="text" name="dict_name" id="f_name" class="form-control" required></div><div class="mb-3"><label class="form-label">Unit of Measure</label><input type="text" name="unit_of_measure" id="f_unit" class="form-control"></div><div class="row"><div class="col-6"><label class="form-label text-danger">Critical Low</label><input type="number" step="0.01" name="critical_low" id="f_low" class="form-control"></div><div class="col-6"><label class="form-label text-danger">Critical High</label><input type="number" step="0.01" name="critical_high" id="f_high" class="form-control"></div></div>`;
            else if (type === 'obs_freq') html = `<div class="mb-3"><label class="form-label">Frequency Label <span class="text-danger">*</span></label><input type="text" name="dict_name" id="f_name" class="form-control" required></div><div class="mb-3"><label class="form-label text-primary">Interval in Minutes <span class="text-danger">*</span></label><input type="number" name="interval_minutes" id="f_mins" class="form-control border-primary" required></div>`;
            else if (type === 'o2_flow') html = `<div class="mb-3"><label class="form-label">Flow Rate Label <span class="text-danger">*</span></label><input type="text" name="dict_name" id="f_name" class="form-control" required></div><div class="mb-3"><label class="form-label text-primary">Numeric Liters Per Minute <span class="text-danger">*</span></label><input type="number" step="0.1" name="value_lpm" id="f_lpm" class="form-control border-primary" required></div>`;
            else if (type === 'outcome') html = `<div class="mb-3"><label class="form-label">Outcome Name <span class="text-danger">*</span></label><input type="text" name="dict_name" id="f_name" class="form-control" required></div><div class="mb-3"><label class="form-label text-primary">System Trigger / Action <span class="text-danger">*</span></label><select name="triggers_action" id="f_trigger" class="form-select border-primary" required><option value="remain_ward">Remain on Ward</option><option value="pending_discharge">Pending / Recommend Discharge</option><option value="direct_discharge">Direct Discharge (Free Bed)</option><option value="transfer_workflow">Internal Ward Transfer</option></select></div>`;
            else html = `<div class="mb-3"><label class="form-label">Name <span class="text-danger">*</span></label><input type="text" name="dict_name" id="f_name" class="form-control" required></div>`;
            $('#dict_body_content').html(html); $('#modalUniversalDict').modal('show');
        };

        window.editClinicalRecord = function(table, id) {
            $.post(apiUrl, { action: 'get_record', table: table, id: id }, function(res) {
                if(res && res.status === 'success') {
                    let d = res.data;
                    if (table === 'ipd_services') { 
                        openIpdServiceModal(); 
                        setTimeout(()=> { 
                            $('#svc_id').val(id); $('#svc_name').val(d.service_name); $('#svc_type').val(d.service_type_id).trigger('change'); 
                            $('#svc_cash_adult').val(d.cash_price_adult); $('#svc_cash_child').val(d.cash_price_child); 
                            if(d.is_nhis_covered==1) $('#svc_nhis_covered').prop('checked',true).trigger('change'); 
                            $('#svc_nhis_adult').val(d.nhis_tariff_adult); $('#svc_nhis_child').val(d.nhis_tariff_child); 
                            $('#svc_nhis_copay_adult').val(d.nhis_copay_adult); $('#svc_nhis_copay_child').val(d.nhis_copay_child); 
                            if(d.requires_result==1) $('#svc_req_res').prop('checked',true).trigger('change'); 
                            $('#svc_unit').val(d.unit_of_measure); $('#svc_result_type').val(d.result_type).trigger('change'); $('#svc_options').val(d.options_csv); 
                        }, 100); 
                    }
                    else if (table === 'ipd_poc_parameters') {
                        $('#i_item_id').val(''); 
                        $('#param_id').val(id); $('#param_name').val(d.parameter_name); $('#param_unit').val(d.unit_of_measure);
                        $('#param_res_type').val(d.result_type).trigger('change'); $('#param_options').val(d.options_csv);
                    }
                    else if (table === 'system_dictionaries_registry') { openRegistryModal(); setTimeout(()=> { $('#reg_id').val(id); $('#reg_name').val(d.dictionary_name); $('#reg_table').val(d.target_table); $('#reg_disp').val(d.display_column); $('#reg_val').val(d.value_column); $('#reg_filter').val(d.filter_condition); }, 100); }
                    else if (table === 'ipd_custom_dict_items') { openItemModal(); setTimeout(()=> { $('#i_item_id').val(id); $('#i_item_name').val(d.item_name); $('#i_input_type').val(d.input_type).trigger('change'); $('#i_options_csv').val(d.options_csv); }, 100); }
                    else if (table === 'ipd_setup_diet_types') { openDictModal('diet', 'Diet Type'); setTimeout(()=> { $('#dict_id').val(id); $('#f_name').val(d.diet_name); $('#f_desc').val(d.description); }, 100); }
                    else if (table === 'ipd_setup_fluid_types') { openDictModal('fluid', 'Fluid Type'); setTimeout(()=> { $('#dict_id').val(id); $('#f_cat').val(d.fluid_category); $('#f_name').val(d.fluid_name); }, 100); }
                    else if (table === 'ipd_setup_vital_params') { openDictModal('vital', 'Vital Parameter'); setTimeout(()=> { $('#dict_id').val(id); $('#f_name').val(d.param_name); $('#f_unit').val(d.unit_of_measure); $('#f_low').val(d.critical_low); $('#f_high').val(d.critical_high); }, 100); }
                    else if (table === 'ipd_setup_obs_frequencies') { openDictModal('obs_freq', 'Observation Frequency'); setTimeout(()=> { $('#dict_id').val(id); $('#f_name').val(d.frequency_name); $('#f_mins').val(d.interval_minutes); }, 100); }
                    else if (table === 'ipd_setup_oxygen_flow_rates') { openDictModal('o2_flow', 'Oxygen Flow Rate'); setTimeout(()=> { $('#dict_id').val(id); $('#f_name').val(d.flow_rate_name); $('#f_lpm').val(d.value_lpm); }, 100); }
                    else if (table === 'ipd_setup_round_outcomes') { openDictModal('outcome', 'Clinical Outcome'); setTimeout(()=> { $('#dict_id').val(id); $('#f_name').val(d.outcome_name); $('#f_trigger').val(d.triggers_action); }, 100); }
                    else {
                        let type = '', title = '', name = '';
                        if(table === 'ipd_setup_oxygen_modes') { type = 'o2_mode'; title = 'Oxygen Mode'; name = d.mode_name; }
                        if(table === 'ipd_setup_ward_equipment') { type = 'equipment'; title = 'Equipment'; name = d.equipment_name; }
                        if(table === 'ipd_setup_med_routes') { type = 'med_route'; title = 'Medication Route'; name = d.route_name; }
                        if(table === 'ipd_setup_med_instructions') { type = 'med_inst'; title = 'Medication Instruction'; name = d.instruction_name; }
                        if(table === 'ipd_setup_blood_products') { type = 'blood_prod'; title = 'Blood Product'; name = d.product_name; }
                        if(table === 'ipd_setup_isolation_types') { type = 'isolation'; title = 'Isolation Type'; name = d.isolation_name; }
                        if(table === 'ipd_setup_service_types') { type = 'svc_type'; title = 'Service Type'; name = d.type_name; }
                        openDictModal(type, title); setTimeout(()=> { $('#dict_id').val(id); $('#f_name').val(name); }, 100);
                    }
                }
            }, 'json');
        };

        window.openMasterDictModal = function() { $('#frmMasterDict')[0].reset(); $('#m_dict_id').val(''); $('#modalMasterDict').modal('show'); };
        window.editMasterDict = function() { let id = $('#active_dict_id').val(); let dict = window.masterDicts.find(d => d.id == id); if(dict) { $('#m_dict_id').val(dict.id); $('#m_dict_name').val(dict.dict_name); $('#m_dict_desc').val(dict.description); $('#modalMasterDict').modal('show'); } };
        window.openItemModal = function() { $('#frmDictItem')[0].reset(); $('#i_item_id').val(''); $('#i_dict_id').val($('#active_dict_id').val()); $('#div_dict_item_opts').hide(); $('#modalDictItem').modal('show'); };
        $('#i_input_type').on('change', function() { if(['Checkbox (Multiple)', 'Radio (Single)'].includes($(this).val())) { $('#div_dict_item_opts').slideDown(); $('#i_options_csv').prop('required', true); } else { $('#div_dict_item_opts').slideUp(); $('#i_options_csv').prop('required', false).val(''); } });
        window.openRegistryModal = function() { $('#frmRegistry')[0].reset(); $('#reg_id').val(''); $('#modalRegistry').modal('show'); };

        // Submissions
        $('#frmIpdService').on('submit', function(e) { e.preventDefault(); $.post(apiUrl, $(this).serialize(), res => { if(res.status === 'success') { $('#modalIpdService').modal('hide'); if(dtIpdServices) dtIpdServices.ajax.reload(null, false); } }); });
        $('#corp_copay_a, #corp_copay_c').on('input', function() { if(parseFloat($(this).val()) > 0) $('#corp_req_copay').prop('checked', true); });
        $('#frmCorpTariff').on('submit', function(e) { e.preventDefault(); $.post(apiUrl, $(this).serialize(), res => { if(res.status === 'success') { $('#frmCorpTariff')[0].reset(); if(dtCorpTariffs) dtCorpTariffs.ajax.reload(null, false); if(dtIpdServices) dtIpdServices.ajax.reload(null, false); } }); });
        
        $('#frmPocRange').on('submit', function(e) { e.preventDefault(); $.post(apiUrl, $(this).serialize(), res => { if(res.status === 'success') { $('#frmPocRange')[0].reset(); $('#rng_svc_id').val($('#corp_svc_id').val()); if(dtPocRanges) dtPocRanges.ajax.reload(null, false); } }); });

        $('#frmUniversalDict').on('submit', function(e) { 
            e.preventDefault(); 
            $.post(apiUrl, $(this).serialize(), function(res) { 
                if(res && res.status === 'success') { 
                    $('#modalUniversalDict').modal('hide'); 
                    if(dtDiets) dtDiets.ajax.reload(null, false); if(dtFluids) dtFluids.ajax.reload(null, false); if(dtVitals) dtVitals.ajax.reload(null, false); if(dtFreqs) dtFreqs.ajax.reload(null, false); if(dtO2Modes) dtO2Modes.ajax.reload(null, false); if(dtO2Flows) dtO2Flows.ajax.reload(null, false); if(dtEquip) dtEquip.ajax.reload(null, false); if(dtMedRoutes) dtMedRoutes.ajax.reload(null, false); if(dtMedInst) dtMedInst.ajax.reload(null, false); if(dtBlood) dtBlood.ajax.reload(null, false); if(dtIsolation) dtIsolation.ajax.reload(null, false); if(dtSvcTypes) dtSvcTypes.ajax.reload(null, false); if(dtOutcomes) dtOutcomes.ajax.reload(null, false); fetchServiceDropdowns(); 
                } 
            }, 'json'); 
        });
        
        $('#frmMasterDict').on('submit', function(e) { e.preventDefault(); $.post(apiUrl, $(this).serialize(), function(res) { if(res.status === 'success') { $('#modalMasterDict').modal('hide'); loadSidebarMenu(); if($('#m_dict_id').val() === '') { setTimeout(() => { $(`.dict-tab[data-id="${res.insert_id}"]`).click(); }, 500); } } }, 'json'); });
        $('#frmDictItem').on('submit', function(e) { e.preventDefault(); $.post(apiUrl, $(this).serialize(), res => { if(res.status === 'success') { $('#modalDictItem').modal('hide'); if(dtItems) dtItems.ajax.reload(null, false); } }, 'json'); });
        $('#frmRegistry').on('submit', function(e) { e.preventDefault(); $.post(apiUrl, $(this).serialize(), res => { if(res.status === 'success') { $('#modalRegistry').modal('hide'); if(dtRegistry) dtRegistry.ajax.reload(null, false); } }, 'json'); });

        // Deletes and Toggles
        window.deleteData = function(table, id) {
            if(confirm('Are you sure you want to delete this?')) {
                $.post(apiUrl, {action: 'delete_record', table: table, id: id}, function(res) {
                    if(table === 'ipd_services') { if(dtIpdServices) dtIpdServices.ajax.reload(null, false); }
                    else if(table === 'ipd_service_corporate_tariffs') { if(dtCorpTariffs) dtCorpTariffs.ajax.reload(null, false); if(dtIpdServices) dtIpdServices.ajax.reload(null, false); }
                    else if(table === 'ipd_poc_reference_ranges') { if(dtPocRanges) dtPocRanges.ajax.reload(null, false); }
                    else if(table === 'ipd_poc_parameters') { if(dtPocParams) dtPocParams.ajax.reload(null, false); if(dtIpdServices) dtIpdServices.ajax.reload(null, false); }
                    else if(table === 'ipd_setup_service_types') { if(dtSvcTypes) dtSvcTypes.ajax.reload(null, false); fetchServiceDropdowns(); }
                    else if(table === 'ipd_setup_round_outcomes') { if(dtOutcomes) dtOutcomes.ajax.reload(null, false); }
                    else if(table === 'ipd_custom_dictionaries') { $('#items-state').hide(); $('#welcome-state').show(); loadSidebarMenu(); }
                    else if(table === 'ipd_custom_dict_items') { if(dtItems) dtItems.ajax.reload(null, false); }
                    else if(table === 'system_dictionaries_registry') { if(dtRegistry) dtRegistry.ajax.reload(null, false); }
                    else { if(dtDiets) dtDiets.ajax.reload(null, false); if(dtFluids) dtFluids.ajax.reload(null, false); if(dtVitals) dtVitals.ajax.reload(null, false); if(dtFreqs) dtFreqs.ajax.reload(null, false); if(dtO2Modes) dtO2Modes.ajax.reload(null, false); if(dtO2Flows) dtO2Flows.ajax.reload(null, false); if(dtEquip) dtEquip.ajax.reload(null, false); if(dtMedRoutes) dtMedRoutes.ajax.reload(null, false); if(dtMedInst) dtMedInst.ajax.reload(null, false); if(dtBlood) dtBlood.ajax.reload(null, false); if(dtIsolation) dtIsolation.ajax.reload(null, false); }
                }, 'json');
            }
        };
        window.toggleData = function(table, id, status) {
            $.post(apiUrl, {action: 'toggle_status', table: table, id: id, status: status}, function(res) {
                if(table === 'ipd_services') { if(dtIpdServices) dtIpdServices.ajax.reload(null, false); }
                else if(table === 'ipd_setup_service_types') { if(dtSvcTypes) dtSvcTypes.ajax.reload(null, false); fetchServiceDropdowns(); }
                else if(table === 'ipd_setup_round_outcomes') { if(dtOutcomes) dtOutcomes.ajax.reload(null, false); }
                else if(table === 'ipd_poc_reference_ranges') { if(dtPocRanges) dtPocRanges.ajax.reload(null, false); }
                else if(table === 'ipd_poc_parameters') { if(dtPocParams) dtPocParams.ajax.reload(null, false); }
                else if(table === 'ipd_custom_dictionaries') loadSidebarMenu();
                else if(table === 'ipd_custom_dict_items') { if(dtItems) dtItems.ajax.reload(null, false); }
                else if(table === 'system_dictionaries_registry') { if(dtRegistry) dtRegistry.ajax.reload(null, false); }
                else { if(dtDiets) dtDiets.ajax.reload(null, false); if(dtFluids) dtFluids.ajax.reload(null, false); if(dtVitals) dtVitals.ajax.reload(null, false); if(dtFreqs) dtFreqs.ajax.reload(null, false); if(dtO2Modes) dtO2Modes.ajax.reload(null, false); if(dtO2Flows) dtO2Flows.ajax.reload(null, false); if(dtEquip) dtEquip.ajax.reload(null, false); if(dtMedRoutes) dtMedRoutes.ajax.reload(null, false); if(dtMedInst) dtMedInst.ajax.reload(null, false); if(dtBlood) dtBlood.ajax.reload(null, false); if(dtIsolation) dtIsolation.ajax.reload(null, false); }
            }, 'json');
        };
    };
} catch (error) {
    console.error("Critical Runtime Error in JS", error);
}