const apiDataUrl = '/rimax/application/dripend/includes/ipd/processPatientIPDRecords.php';
const apiFormUrl = '/rimax/application/dripend/includes/ipd/processIPDFormEngine.php';
const apiReportUrl = '/rimax/application/dripend/includes/ipd/processIPDReports.php';
let activeChart = null;
let calcTimer; 

window.isChartNewLocked = false;
window.isChartEditLocked = false;
window.chartLockReasonNew = "";
window.chartLockReasonEdit = "";

$(document).ready(function() { 
    loadTab('overview'); 
    fetchAlerts();
});

// Beautiful App Native Modals (Replaces native alerts)
window.showAppResponse = function(title, msg, type = 'success') {
    if(type === 'success') {
        $('#appResIcon').attr('class', 'fa-solid fa-circle-check text-success fa-4x mb-3');
        $('#appResBtn').attr('class', 'btn btn-success fw-bold px-4 mt-2');
    } else {
        $('#appResIcon').attr('class', 'fa-solid fa-circle-xmark text-danger fa-4x mb-3');
        $('#appResBtn').attr('class', 'btn btn-dark fw-bold px-4 mt-2');
    }
    $('#appResTitle').text(title);
    $('#appResMsg').text(msg);
    $('#appResponseModal').modal('show');
};

window.appConfirm = function(title, msg, callback) {
    $('#appConfTitle').text(title);
    $('#appConfMsg').text(msg);
    $('#appConfirmModal').modal('show');
    
    $('#btnAppConfirm').off('click').on('click', function() {
        $('#appConfirmModal').modal('hide');
        if (typeof callback === 'function') callback();
    });
};

window.appPrompt = function(title, msg, defaultVal, callback) {
    $('#appPromptTitle').text(title);
    $('#appPromptMsg').text(msg);
    $('#appPromptInput').val(defaultVal);
    $('#appPromptModal').modal('show');
    
    $('#btnAppPromptSubmit').off('click').on('click', function() {
        let val = $('#appPromptInput').val();
        if(!val) return;
        $('#appPromptModal').modal('hide');
        if (typeof callback === 'function') callback(val);
    });
};

function fetchAlerts() {
    $.post(apiDataUrl, { action: 'fetch_clinical_alerts', visit_id: P_VISIT_ID }, function(res) {
        if(res.status === 'success') {
            $('#clinicalAlertsBanner').html(res.html);
            if (res.locks) {
                window.isChartNewLocked = res.locks.block_new;
                window.isChartEditLocked = res.locks.block_edit;
                window.chartLockReasonNew = res.locks.reason_new;
                window.chartLockReasonEdit = res.locks.reason_edit;
            }
        }
    }, 'json');
}

window.loadTab = function(tabName) {
    $('.nav-link').removeClass('active');
    $(`button[onclick="loadTab('${tabName}')"]`).addClass('active');
    $('#tab_container').html('<div class="text-center py-5 text-muted"><i class="fa-solid fa-spinner fa-spin fa-3x text-primary mb-3"></i></div>');

    $.post(apiDataUrl, { action: 'fetch_tab_data', visit_id: P_VISIT_ID, tab: tabName }, function(res) {
        if(res.status === 'success') $('#tab_container').hide().html(res.html).fadeIn(200);
    }, 'json');
};

window.openUniversalModal = function(form_id, editTime = null) {
    if (!editTime && window.isChartNewLocked) {
        showAppResponse("Access Denied", window.chartLockReasonNew, "error");
        return;
    }
    if (editTime && window.isChartEditLocked) {
        showAppResponse("Access Denied", window.chartLockReasonEdit, "error");
        return;
    }

    $('#uModalTitle').html('<i class="fa fa-spinner fa-spin"></i> Loading Form...');
    $('#uModalBody').html('<div class="text-center py-5"><i class="fa-solid fa-spinner fa-spin fa-3x text-primary"></i></div>');
    $('#universalActionModal').modal('show');

    $.post(apiFormUrl, { action: 'get_action_interface', visit_id: P_VISIT_ID, patient_no: P_NO, form_id: form_id, edit_timestamp: editTime || '' }, function(res) {
        if(res.status === 'success') {
            $('#uModalTitle').html(res.title);
            $('#uModalBody').html(res.html);
            
            setTimeout(() => {
                $('.select2-basic').select2({ dropdownParent: $('#universalActionModal'), width: '100%' });
                
                if($('#icd_search_select').length > 0) {
                    $('#icd_search_select').select2({
                        dropdownParent: $('#universalActionModal'),
                        width: '100%',
                        placeholder: "Search by diagnosis name or ICD code...",
                        ajax: {
                            url: apiFormUrl,
                            type: 'GET',
                            dataType: 'json',
                            delay: 250,
                            data: function(params) { return { action: 'search_icd_gdrg', q: params.term }; },
                            processResults: function(data) { return { results: data.results }; }
                        }
                    });
                }
                
                $('.rich-text-editor').summernote({
                    height: 150,
                    toolbar: [
                        ['style', ['bold', 'italic', 'underline', 'clear']],
                        ['font', ['strikethrough', 'superscript', 'subscript']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['view', ['fullscreen']]
                    ]
                });

                $('.dispensary-select').on('change', function() {
                    if($(this).val()) {
                        $('.rx-add-btn').prop('disabled', false);
                        $('#dispensary_lock_notice').slideUp();
                    }
                });
                
                if(editTime) {
                    $('#edit_timestamp').val(editTime);
                    $('#uModalTitle').append(' <span class="badge bg-warning text-dark ms-2 shadow-sm border border-warning"><i class="fa-solid fa-pen"></i> EDITING RECORD</span>');
                    
                    $.post(apiFormUrl, { action: 'get_edit_data', form_id: form_id, visit_id: P_VISIT_ID, recorded_at: editTime }, function(editRes) {
                        if(editRes.status === 'success') {
                            for(let key in editRes.data) {
                                if (key === 'NATIVE_FLUID') {
                                    $('#fluid_dynamic_container').empty();
                                    editRes.data[key].forEach(f => {
                                        let btn = $('#fluid_dynamic_container').siblings('button');
                                        let optsStr = btn.attr('onclick').match(/'([^']+)'/)[1];
                                        addFluidRow(optsStr);
                                        let lastRow = $('.fluid-row').last();
                                        lastRow.find('select[name="fluid_chart_type[]"]').val(f.fluid_type);
                                        lastRow.find('input[name="fluid_chart_vol[]"]').val(f.volume_ml);
                                        lastRow.find('input[name="fluid_chart_remarks[]"]').val(f.remarks);
                                    });
                                } else if (key === 'NATIVE_MED') {
                                    editRes.data[key].forEach(m => {
                                        let row = $(`input[name='med_chart_id[]'][value='${m.prescription_id}']`).closest('tr');
                                        if(row.length) {
                                            row.find('.med-chart-checkbox').prop('checked', true).trigger('change');
                                            row.find(`input[name='med_chart_dose[${m.prescription_id}]']`).val(m.administered_dose || row.find(`input[name='med_chart_dose[${m.prescription_id}]']`).val());
                                            row.find(`select[name='med_chart_status[${m.prescription_id}]']`).val($.trim(m.status));
                                            row.find(`input[name='med_chart_time[${m.prescription_id}]']`).val(m.administered_at.substring(11, 16));
                                            row.find(`input[name='med_chart_remarks[${m.prescription_id}]']`).val(m.remarks);
                                        }
                                    });
                                } else if (key === 'NATIVE_DIAG') {
                                    $('#diag_tbody').empty();
                                    if(editRes.data[key].length > 0) {
                                        editRes.data[key].forEach(d => {
                                            let checked = d.is_principal == 1 ? 'checked' : '';
                                            let html = `<tr id='row_${d.icd.replace('.','')}'>
                                                <td class='text-center'><input class='form-check-input border-secondary' style='transform:scale(1.3); cursor:pointer;' type='radio' name='diag_principal' value='${d.icd}' ${checked} required></td>
                                                <td><b class='text-primary'>${d.icd}</b><br><span class='small fw-bold text-muted'>${d.descr}</span>
                                                    <input type='hidden' name='diag_icd[]' value='${d.icd}'>
                                                    <input type='hidden' name='diag_desc[]' value='${d.descr}'>
                                                </td>
                                                <td><span class='badge bg-dark px-2 py-1 fs-6 shadow-sm'>${d.gdrg || 'Unmapped'}</span><input type='hidden' name='diag_gdrg[]' value='${d.gdrg || 'Unmapped'}'></td>
                                                <td class='text-center'><button type='button' class='btn btn-sm btn-light border text-danger shadow-sm' onclick='$(this).closest("tr").remove(); checkDiagEmpty();'><i class='fa fa-trash'></i></button></td>
                                            </tr>`;
                                            $('#diag_tbody').append(html);
                                        });
                                        $('#diag_validation_flag').val('filled');
                                    } else {
                                        checkDiagEmpty();
                                    }
                                } else if (key === 'NATIVE_TRANSFER') {
                                    if (editRes.data[key]) {
                                        let t = editRes.data[key];
                                        if (t.transfer_type === 'Ward Transfer') {
                                            $('#transfer_ward_id').val(t.target_ward_id).trigger('change');
                                            $('textarea[name="transfer_notes"]').val(t.treatment_plan);
                                        }
                                    }
                                } else if (key === 'NATIVE_THEATRE') {
                                    if (editRes.data[key]) {
                                        let t = editRes.data[key];
                                        $('#is_surgical_transfer').prop('checked', true).trigger('change');
                                        setTimeout(() => {
                                            $('#theatre_room_id').val(t.room_id).trigger('change');
                                            $('#theatre_procedure_id').val(t.procedure_id).trigger('change');
                                            $('#theatre_surgeon_id').val(t.surgeon_id).trigger('change');
                                            $('textarea[name="transfer_notes"]').val(t.remarks);
                                        }, 200);
                                    }
                                } else if (key === 'Patient Disposition / Outcome' || key === 'Clinical Review Outcome') {
                                    $('#native_clinical_outcome').val(editRes.data[key]).trigger('change');
                                } else if (key === '_raw_next_review_date') {
                                    $('#next_review_date').val(editRes.data[key]);
                                } else {
                                    let fld = $('[data-field]').filter(function() { return $(this).attr('data-field') === key; });
                                    if(fld.length > 0) {
                                        if(fld.attr('type') === 'radio' || fld.attr('type') === 'checkbox') {
                                            fld.filter(`[value="${editRes.data[key]}"]`).prop('checked', true);
                                        } else if(fld.hasClass('rich-text-editor')) {
                                            fld.summernote('code', editRes.data[key]);
                                        } else {
                                            fld.val(editRes.data[key]).trigger('change');
                                        }
                                    }
                                }
                            }
                        }
                    }, 'json');
                }
            }, 100);
        }
    }, 'json');
};

window.editRecord = function(form_id, editTime) {
    openUniversalModal(form_id, editTime);
};

window.deleteRecord = function(form_id, editTime) {
    if (window.isChartEditLocked) {
        showAppResponse("Access Denied", window.chartLockReasonEdit, "error");
        return;
    }

    appConfirm("Void Clinical Record", "Are you sure you want to completely void this clinical record? This action will be recorded in the system audit trail.", function() {
        $.post(apiFormUrl, { action: 'delete_pool_action', visit_id: P_VISIT_ID, form_id: form_id, recorded_at: editTime }, function(res) {
            if(res.status === 'success') {
                let activeTab = $('.nav-link.active').attr('onclick').match(/'([^']+)'/)[1];
                loadTab(activeTab);
                fetchAlerts();
            } else {
                showAppResponse("Error Voiding Record", res.message, "error");
            }
        }, 'json');
    });
};

window.stopActivePrescription = function(rx_id) {
    if (window.isChartNewLocked || window.isChartEditLocked) {
        showAppResponse("Access Denied", "Clinical chart is locked. Cannot modify prescriptions.", "error");
        return;
    }

    appPrompt("Discontinue Medication", "Enter clinical reason for stopping this medication:", "Discontinued by Doctor", function(reason) {
        $.post(apiFormUrl, { action: 'stop_prescription', rx_id: rx_id, reason: reason }, function(res) {
            if(res.status === 'success') {
                showAppResponse("Medication Stopped", res.message, "success");
                let formId = $('input[name="form_id"]').val();
                if (formId) openUniversalModal(formId); 
                let activeTab = $('.nav-link.active').attr('onclick').match(/'([^']+)'/)[1];
                loadTab(activeTab);
            } else {
                showAppResponse("Error", res.message, "error");
            }
        }, 'json');
    });
};

window.addDiagnosisRow = function() {
    let selectEl = $('#icd_search_select');
    let data = selectEl.select2('data');
    if(!data || data.length === 0 || !data[0].id) { 
        showAppResponse("Validation Error", "Please search and select a diagnosis first.", "error"); 
        return; 
    }
    
    let parts = data[0].id.split('|||');
    let icd = parts[0]; let desc = parts[1]; let gdrg = parts[2];

    if($(`#row_${icd.replace('.','')}`).length > 0) { 
        showAppResponse("Duplicate Entry", "This diagnosis is already in the list.", "error"); 
        return; 
    }

    $('#diag_empty_row').remove();
    let isFirst = $('#diag_tbody tr').length === 0;
    let checked = isFirst ? 'checked' : '';

    let html = `
    <tr id='row_${icd.replace('.','')}'>
        <td class='text-center'><input class='form-check-input border-secondary' style='transform:scale(1.3); cursor:pointer;' type='radio' name='diag_principal' value='${icd}' ${checked} required></td>
        <td><b class='text-primary'>${icd}</b><br><span class='small fw-bold text-muted'>${desc}</span>
            <input type='hidden' name='diag_icd[]' value='${icd}'>
            <input type='hidden' name='diag_desc[]' value='${desc}'>
        </td>
        <td><span class='badge bg-dark px-2 py-1 fs-6 shadow-sm'>${gdrg}</span><input type='hidden' name='diag_gdrg[]' value='${gdrg}'></td>
        <td class='text-center'><button type='button' class='btn btn-sm btn-light border text-danger shadow-sm' onclick='$(this).closest("tr").remove(); checkDiagEmpty();'><i class='fa fa-trash'></i></button></td>
    </tr>`;
    
    $('#diag_tbody').append(html);
    $('#diag_validation_flag').val('filled');
    selectEl.val(null).trigger('change');
};

window.checkDiagEmpty = function() {
    if($('#diag_tbody tr').length === 0) {
        $('#diag_tbody').html("<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>");
        $('#diag_validation_flag').val('');
    }
};

$(document).on('change', '#is_surgical_transfer', function() {
    if($(this).is(':checked')) {
        $('#standard_transfer_box').slideUp();
        $('#transfer_ward_id').prop('required', false);
        $('#surgical_transfer_box').slideDown();
        $('#theatre_room_id, #theatre_procedure_id, #theatre_surgeon_id').prop('required', true);
    } else {
        $('#surgical_transfer_box').slideUp();
        $('#theatre_room_id, #theatre_procedure_id, #theatre_surgeon_id').prop('required', false);
        $('#standard_transfer_box').slideDown();
        $('#transfer_ward_id').prop('required', true);
    }
});

$(document).on('change', '#native_clinical_outcome', function() {
    let trigger = $(this).find(':selected').data('trigger');
    
    $('#transfer_workflow_container').slideUp();
    $('#transfer_ward_id, #theatre_room_id, #theatre_procedure_id, #theatre_surgeon_id').prop('required', false);
    
    $('#next_review_container').slideUp();
    $('#next_review_date').prop('required', false);
    $('#req_rev_star').hide();

    if(trigger === 'transfer_workflow') {
        $('#transfer_workflow_container').slideDown();
        $('#is_surgical_transfer').prop('checked', false).trigger('change');
    } else if (trigger === 'pending_discharge' || trigger === 'direct_discharge') {
        $('#next_review_container').slideDown();
        $('#next_review_date').prop('required', true);
        $('#req_rev_star').show();
    }
});

window.addFluidRow = function(encodedData) {
    let obj = JSON.parse(atob(encodedData));
    let html = `
        <div class='row g-2 mb-2 align-items-center fluid-row bg-white p-2 border border-info rounded'>
            <div class='col-md-2'><select class='form-select border-info fluid-cat-selector'><option value='IN'>Intake (IN)</option><option value='OUT'>Output (OUT)</option></select></div>
            <div class='col-md-3'><select name='fluid_chart_type[]' class='form-select border-info fluid-type-selector' required><option value=''>-- Select Fluid --</option>${obj.IN}</select></div>
            <div class='col-md-3'><div class='input-group'><input type='number' name='fluid_chart_vol[]' class='form-control border-info fw-bold text-info' placeholder='Volume' required><span class='input-group-text bg-info text-white border-info fw-bold'>ml</span></div></div>
            <div class='col-md-3'><input type='text' name='fluid_chart_remarks[]' class='form-control border-info' placeholder='Remarks / Additives...'></div>
            <div class='col-md-1 text-end'><button type='button' class='btn btn-sm btn-danger shadow-sm' onclick='$(this).closest(".fluid-row").remove()'><i class='fa fa-times'></i></button></div>
        </div>`;
    let $row = $(html);
    $('#fluid_dynamic_container').append($row);
    $row.find('.fluid-cat-selector').on('change', function() {
        let val = $(this).val();
        $(this).closest('.fluid-row').find('.fluid-type-selector').html('<option value="">-- Select Fluid --</option>' + obj[val]);
    });
};

$(document).on('change', '.med-chart-checkbox', function() {
    let row = $(this).closest('tr');
    let id = $(this).val();
    if($(this).is(':checked')) {
        row.addClass('bg-success bg-opacity-10');
        $(`.med-input-${id}`).prop('disabled', false);
    } else {
        row.removeClass('bg-success bg-opacity-10');
        $(`.med-input-${id}`).prop('disabled', true);
    }
});

// =========================================================
// PRESCRIPTION ENGINE: DOM Template Based
// No Base64, NO empty attributes, 100% Reliable
// =========================================================
window.addDynamicRxRow = function() {
    let opts = $('#rx_drug_options_template').html();
    let fOpts = $('#rx_freq_options_template').html();
    let today = new Date().toISOString().split('T')[0];
    
    let html = `
    <div class="p-3 bg-white border border-primary border-opacity-25 shadow-sm rounded-3 mb-3 position-relative rx-wrapper-box">
        <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-2 py-0 px-2 shadow-sm" onclick="this.closest('.rx-wrapper-box').remove()"><i class="fa-solid fa-times"></i></button>
        <div class="row g-2 align-items-end mb-2 border-bottom pb-3">
            <div class="col-md-4">
                <label class="small fw-bold text-muted mb-1">Search Drug <span class="text-danger">*</span></label>
                <select name="rx_drug[]" class="form-select select2-drug-dyn rx-svc-fld" required>
                    <option value="">-- Select --</option>
                    ${opts}
                </select>
            </div>
            <div class="col-md-4">
                <label class="small fw-bold text-muted mb-1">Formulation</label>
                <input type="text" name="rx_form[]" class="form-control fw-bold text-dark rx-form-fld" placeholder="e.g. Tablet">
            </div>
            <div class="col-md-4">
                <label class="small fw-bold text-muted mb-1">Base Strength <span class="text-danger">*</span></label>
                <input type="text" name="rx_strength[]" class="form-control fw-bold text-primary rx-str-fld" required placeholder="e.g. 500 mg">
            </div>
        </div>
        <div class="row g-2 align-items-end">
            <div class="col-md-4">
                <label class="small fw-bold text-dark mb-1">Target Dose <span class="text-danger">*</span></label>
                <input type="text" name="rx_dose[]" class="form-control fw-bold border-secondary rx-dose-fld" placeholder="e.g. 500" required>
            </div>
            <div class="col-md-4">
                <label class="small fw-bold text-dark mb-1">Frequency <span class="text-danger">*</span></label>
                <select name="rx_freq[]" class="form-select fw-bold border-secondary rx-freq-fld" required>
                    ${fOpts}
                </select>
            </div>
            <div class="col-md-4">
                <label class="small fw-bold text-dark mb-1">Duration (Days) <span class="text-danger">*</span></label>
                <input type="number" name="rx_dur[]" class="form-control fw-bold border-secondary rx-dur-fld" value="5" min="1" required>
            </div>
            
            <div class="col-12 bg-light p-3 border rounded-3 d-flex align-items-center justify-content-between mt-3">
                <div>
                    <span class="d-block small fw-bold text-muted text-uppercase mb-1">Engine Output Log</span>
                    <div class="mb-0 rx-calc-log"><small class="text-muted">Awaiting Input...</small></div>
                </div>
                <div class="text-end">
                    <label class="small fw-bold text-success mb-1 text-uppercase">Final Physical Qty <span class="text-danger">*</span></label>
                    <input type="number" name="rx_qty[]" class="form-control fw-bold border-success text-success bg-white shadow-sm rx-qty-fld" style="font-size:20px; text-align:center; width: 120px;" required readonly>
                </div>
            </div>
            
            <input type="hidden" name="rx_start[]" value="${today}">
            <input type="hidden" name="rx_end[]" class="rx-end-fld">
            <div class="col-12 mt-3">
                <label class="small fw-bold text-muted mb-1">Pharmacist Notes</label>
                <input type="text" name="rx_remarks[]" class="form-control" placeholder="Notes...">
            </div>
        </div>
    </div>`;
    
    $('#rx_dynamic_container').append(html);
    $('#rx_dynamic_container .select2-drug-dyn').last().select2({ dropdownParent: $('#universalActionModal'), width: '100%' });
};

// Select2 DOM Attribute Parsing
$(document).on('change', '.select2-drug-dyn', function () {
    const row = $(this).closest('.rx-wrapper-box');
    const selectedOpt = $(this).find('option:selected');
    
    let formVal = selectedOpt.attr('data-form') || '';
    let strVal = selectedOpt.attr('data-strength') || '';
    
    row.find('.rx-form-fld').val(formVal);
    row.find('.rx-str-fld').val(strVal);
    
    triggerEngineCalcRx(row);
});

// Observe all mathematical inputs
$(document).on('input change', '.rx-dose-fld, .rx-dur-fld, .rx-freq-fld, .rx-str-fld', function() {
    triggerEngineCalcRx($(this).closest('.rx-wrapper-box'));
});

function triggerEngineCalcRx(row) {
    clearTimeout(calcTimer);
    
    let raw_svc = row.find('.rx-svc-fld').val();
    let svc_id = raw_svc ? raw_svc.split('||')[0] : '';
    let dose = row.find('.rx-dose-fld').val();
    let freq = row.find('.rx-freq-fld').val();
    let dur = row.find('.rx-dur-fld').val();
    let str = row.find('.rx-str-fld').val(); 

    if(!svc_id || !dose || !freq || !dur) return;

    calcTimer = setTimeout(() => {
        row.find('.rx-calc-log').html('<i class="fa fa-spinner fa-spin text-primary"></i> <small class="text-muted">Calculating...</small>');
        $.post(apiFormUrl, { 
            action: 'calculate_engine_qty', 
            service_id: svc_id, 
            dose: dose, 
            frequency_code: freq, 
            duration: dur,
            strength: str 
        }, function(res) {
            if(res.status === 'success') {
                row.find('.rx-qty-fld').val(res.final_qty);
                row.find('.rx-calc-log').html(`<small class="text-success fw-bold"><i class="fa-solid fa-microchip me-1"></i> ${res.log}</small>`);
            } else {
                row.find('.rx-calc-log').html(`<small class="text-danger fw-bold"><i class="fa-solid fa-triangle-exclamation me-1"></i> Calculation Error</small>`);
            }
        }, 'json').fail(function() {
            row.find('.rx-calc-log').html(`<small class="text-danger fw-bold"><i class="fa-solid fa-triangle-exclamation me-1"></i> Backend Connection Failed</small>`);
        });
    }, 400); 
}

window.submitUniversalAction = function() {
    let form = $('#universalActionForm');
    if(!form[0].checkValidity()) { form[0].reportValidity(); return; }

    if ($('#next_review_date').is(':visible') && $('#next_review_date').val()) {
        let selDate = new Date($('#next_review_date').val());
        let now = new Date();
        now.setMinutes(now.getMinutes() - 5); 
        if (selDate < now) {
            showAppResponse("Invalid Date", "The Next Review / Follow-up Date cannot be logged in the past.", "error");
            return;
        }
    }

    let outcomeSelect = $('#native_clinical_outcome');
    if(outcomeSelect.length > 0) {
        let trigger = outcomeSelect.find(':selected').data('trigger');
        let outcomeName = outcomeSelect.val();
        if (trigger === 'direct_discharge' || trigger === 'pending_discharge' || trigger === 'transfer_workflow') {
            showOutcomeConfirmation(trigger, outcomeName);
            return; 
        }
    }
    
    executeFormSave();
};

function showOutcomeConfirmation(trigger, name) {
    let title = 'Confirm Action'; let msg = ''; let icon = 'fa-circle-info text-primary'; let btnClass = 'btn-primary';

    if (trigger === 'direct_discharge') {
        title = 'Direct Discharge Warning';
        msg = `Selecting <b>${name}</b> will permanently discharge the patient from this ward and free the bed immediately. Proceed?`;
        icon = 'fa-triangle-exclamation text-danger'; btnClass = 'btn-danger';
    } else if (trigger === 'pending_discharge') {
        title = 'Recommend Discharge';
        msg = `Selecting <b>${name}</b> will flag the patient for discharge. The bed remains occupied until cleared by nursing. Proceed?`;
        icon = 'fa-person-walking-arrow-right text-warning'; btnClass = 'btn-warning';
    } else if (trigger === 'transfer_workflow') {
        let isSurg = $('#is_surgical_transfer').is(':checked');
        if (isSurg) {
            title = 'Transfer to Operating Theatre';
            msg = `You are sending this patient to the Operating Theatre. Their current bed will be reserved as 'Undergoing Surgical Procedure'. Proceed?`;
            icon = 'fa-scalpel-line-dashed text-danger'; btnClass = 'btn-danger';
        } else {
            title = 'Ward Transfer Request';
            msg = `You are about to initiate a transfer request to another ward. The patient's current bed will remain occupied until the receiving ward accepts the transfer. Proceed?`;
            icon = 'fa-right-left text-info'; btnClass = 'btn-info';
        }
    }

    $('#dynOutIcon').attr('class', `fa-solid ${icon} fa-4x mb-3`);
    $('#dynOutTitle').text(title);
    $('#dynOutMsg').html(msg);
    $('#btnConfirmOutcome').attr('class', `btn fw-bold px-4 shadow-sm ${btnClass}`);
    
    $('#dynamicOutcomeModal').modal('show');
}

$('#btnConfirmOutcome').click(function() {
    $('#dynamicOutcomeModal').modal('hide');
    executeFormSave();
});

function executeFormSave() {
    let form = $('#universalActionForm');
    let btn = $('#uModalBtn'); let orig = btn.html();
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-2"></i> Saving & Processing...');

    $.post(apiFormUrl, form.serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if(res.status === 'success') {
            $('#universalActionModal').modal('hide');
            let activeTab = $('.nav-link.active').attr('onclick').match(/'([^']+)'/)[1];
            loadTab(activeTab);
            fetchAlerts();
            showAppResponse("Success", res.message, "success");
        } else {
            showAppResponse("Save Failed", res.message, "error");
        }
    }, 'json').fail(function(xhr, status, error) {
        btn.prop('disabled', false).html(orig);
        console.error("AJAX Save Error: ", xhr.responseText);
        
        let errMsg = "A fatal server error occurred while processing the request.";
        try {
            let j = JSON.parse(xhr.responseText);
            if(j.message) errMsg = j.message;
        } catch(e) {}
        
        showAppResponse("Server Error", errMsg, "error");
    });
}

window.printReport = function(type) {
    $('#reportTableData').html('<div class="text-center py-5"><i class="fa fa-spinner fa-spin fa-2x text-primary"></i><p class="mt-3 text-muted">Compiling analytics...</p></div>');
    if(activeChart) { activeChart.destroy(); }
    $('#reportChartContainer').hide();
    $('#reportViewerModal').modal('show');

    $.post(apiReportUrl, { action: 'generate_clinical_report', visit_id: P_VISIT_ID, report_type: type }, function(res) {
        if(res && res.status === 'success') {
            $('#reportTitle').html(`<i class="fa-solid fa-chart-line me-2"></i> ${res.title}`);
            $('#reportTableData').html(res.tableHtml);
            
            if(res.chartData) {
                $('#reportChartContainer').show();
                const ctx = document.getElementById('reportChart').getContext('2d');
                activeChart = new Chart(ctx, {
                    type: res.chartType || 'line',
                    data: res.chartData,
                    options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'top' } } }
                });
            }
        } else {
            $('#reportTableData').html(`<div class="text-danger p-4 fw-bold text-center">${res.message || 'Report Engine Failure'}</div>`);
        }
    }, 'json');
};