// Ensure configuration exists
if (!window.OpdConfig) {
    console.error("CRITICAL: window.OpdConfig is missing. Check PHP configuration output.");
}

// Custom App Notification Modal
function appAlert(title, message, type = 'info') {
    let iconHtml = '';
    if(type === 'success') iconHtml = '<i class="fa-solid fa-circle-check fa-3x text-success mb-2"></i>';
    else if(type === 'error') iconHtml = '<i class="fa-solid fa-circle-xmark fa-3x text-danger mb-2"></i>';
    else if(type === 'warning') iconHtml = '<i class="fa-solid fa-triangle-exclamation fa-3x text-warning mb-2"></i>';
    else iconHtml = '<i class="fa-solid fa-circle-info fa-3x text-primary mb-2"></i>';

    $('#appNotifIcon').html(iconHtml);
    $('#appNotifTitle').text(title);
    $('#appNotifMsg').text(message);
    $('#appNotificationModal').modal('show');
}

// Generate HTML Options safely
let jsDiagStatusOptions = '';
if(window.OpdConfig.diagStatusOptions) {
    window.OpdConfig.diagStatusOptions.forEach(ds => jsDiagStatusOptions += `<option value="${ds.status_name}">${ds.status_name}</option>`);
}

let jsFormOptions = '';
if(window.OpdConfig.formOptions) {
    window.OpdConfig.formOptions.forEach(f => jsFormOptions += `<option value="${f.formulation_name}">${f.formulation_name}</option>`);
}

let jsFreqOptions = '';
if(window.OpdConfig.freqOptions) {
    window.OpdConfig.freqOptions.forEach(f => {
        let mult = f.multiplier || 1;
        jsFreqOptions += `<option value="${f.freq_code}" data-multiplier="${mult}">${f.freq_code}</option>`;
    });
}

let icdOptionsHTML = '';
if(window.OpdConfig.icdOptions) {
    window.OpdConfig.icdOptions.forEach(i => icdOptionsHTML += `<option value="${i.code} - ${i.description}">${i.code} - ${i.description}</option>`);
}

let labOptionsHTML = '';
if(window.OpdConfig.labOptions) {
    window.OpdConfig.labOptions.forEach(l => labOptionsHTML += `<option value="${l.id}||${l.service_name}" data-dept-id="${l.department_id || ''}" data-dept-name="${l.department_name || ''}">${l.service_name}</option>`);
}

let drugOptionsHTML = '';
if(window.OpdConfig.drugOptions) {
    window.OpdConfig.drugOptions.forEach(d => {
        let f_val = d.drug_formulation || '';
        let s_val = $.trim((d.drug_strength || '') + ' ' + (d.strength_unit || ''));
        let val = d.service_id + '||' + d.service_name;
        drugOptionsHTML += `<option value="${val}" data-form="${f_val}" data-strength="${s_val}">${d.service_name}</option>`;
    });
}

$(document).ready(function() {
    $('.select2-diag').select2({ placeholder: "Search ICD-10 Code or Disease..." });
    $('.select2-helpers').select2({ placeholder: "Select assisting staff..." });
    $('.select2-generic').select2();
    
    // Listen for changes on outcome to trigger auto-fill
    $('#outcome_sel').on('change', function() {
        toggleAdmit();
    });
    
    // Also trigger auto-fill if user modifies diagnosis/fields while outcome is already Admission
    $(document).on('change', 'input[name="is_principal"], .diag-code-input', function() {
        if ($('#outcome_sel').find(':selected').attr('data-admit') === '1') {
            toggleAdmit();
        }
    });

    toggleAdmit();
});

// Auto-fill form and strength on drug selection
$(document).on('select2:select', '.select2-drug-dynamic', function (e) {
    const row = $(this).closest('.form-row');
    const selected = $(this).find(':selected');
    const form = selected.attr('data-form');
    const strength = selected.attr('data-strength');

    if(form && form.trim() !== '') {
        let formField = row.find('.form-field');
        if(formField.find("option[value='" + form + "']").length === 0) {
            formField.append(new Option(form, form, true, true));
        }
        formField.val(form).trigger('change.select2');
    }
    if(strength && strength.trim() !== '') {
        row.find('.strength-field').val(strength.trim());
    }
});

// Calculate drug quantities dynamically
$(document).on('input', '.dose-field, .dur-field', calculateRowQty);
$(document).on('select2:select', '.freq-field', calculateRowQty);

function calculateRowQty() {
    const row = $(this).closest('.form-row');
    const doseStr = row.find('.dose-field').val() || '0';
    const freqOpt = row.find('.freq-field').find(':selected');
    const multiplier = parseFloat(freqOpt.attr('data-multiplier')) || 0;
    const days = parseFloat(row.find('.dur-field').val()) || 0;

    let dose = parseFloat(doseStr) || 0;
    if(doseStr.includes('1/2') || doseStr.includes('0.5')) dose = 0.5;

    if (dose > 0 && multiplier > 0 && days > 0) {
        const total = Math.ceil(dose * multiplier * days);
        row.find('.total-qty-field').val(total);
    } else {
        row.find('.total-qty-field').val('');
    }
}

// Auto Route labs to proper department
window.autoRouteService = function(elem) {
    const row = $(elem).closest('.form-row');
    const selected = $(elem).find(':selected');
    const deptId = selected.attr('data-dept-id') || '';
    const deptName = selected.attr('data-dept-name') || '';

    row.find('.dept-id-field').val(deptId);
    row.find('.dept-name-field').val(deptName);
    monitorLabs();
};

function monitorLabs() {
    const labInputs = document.querySelectorAll('.select2-lab-dynamic');
    let hasLab = false;
    labInputs.forEach(input => { if(input.value.trim() !== '') hasLab = true; });
    if(hasLab) {
        const sel = $('#outcome_sel');
        sel.val('Awaiting Labs').trigger('change');
    }
}

// ==============================================================================
// ASYNCHRONOUS FORM SUBMISSION (No more raw HTML error pages)
// ==============================================================================
window.validateAndSubmit = function() {
    // 1. Identify which radio button is checked
    const principalRadio = document.querySelector('input[name="is_principal"]:checked');
    if (!principalRadio) {
        appAlert("Validation Error", "You must select one Principal Diagnosis by checking its radio button.", "error");
        switchTab('tab-diag', document.querySelectorAll('.patient-tab')[window.OpdConfig.tabCount]); 
        return;
    }
    
    // 2. Find the row corresponding to that radio button to check its diagnosis code
    const val = principalRadio.value;
    const hiddenInputs = document.querySelectorAll('input[name="diag_row_id[]"]');
    let principalCodeInput = null;
    
    hiddenInputs.forEach(input => {
        if(input.value === val) {
            const row = input.closest('.form-row');
            principalCodeInput = row.querySelector('.diag-code-input');
        }
    });

    if (!principalCodeInput || principalCodeInput.value.trim() === '') {
        appAlert("Validation Error", "The row marked as Principal Diagnosis must have an ICD-10 Code selected.", "error");
        switchTab('tab-diag', document.querySelectorAll('.patient-tab')[window.OpdConfig.tabCount]); 
        return; 
    }
    
    // 3. Admission Ward Validation
    const selOpt = $('#outcome_sel').find(':selected');
    if (selOpt.attr('data-admit') === '1') {
        const admitWard = $('select[name="admit_ward"]').val();
        if(!admitWard || admitWard.trim() === '') {
            appAlert("Action Required", "You have recommended Admission. You must select a Recommended Ward.", "warning");
            switchTab('tab-outcome', document.querySelectorAll('.patient-tab')[window.OpdConfig.tabCount + 2]); 
            return;
        }
        
        const wardInstructions = $('textarea[name="ward_instructions"]').val();
        if(!wardInstructions || wardInstructions.trim() === '') {
            appAlert("Action Required", "Please provide detailed instructions for the ward regarding this admission.", "warning");
            switchTab('tab-outcome', document.querySelectorAll('.patient-tab')[window.OpdConfig.tabCount + 2]); 
            return;
        }
    }
    
    // Convert standard form submit to AJAX
    let form = $('#consultForm');
    let submitBtn = $('.btn-save');
    let originalHtml = submitBtn.html();

    submitBtn.prop('disabled', true).html('<i class="fa-solid fa-spinner fa-spin"></i> Processing & Signing...');

    $.ajax({
        url: form.attr('action'),
        type: 'POST',
        data: form.serialize(),
        dataType: 'json',
        success: function(response) {
            if(response.status === 'success') {
                appAlert("Success", response.message, "success");
                setTimeout(function() {
                    window.location.href = '/rimax/application/views/consultation/consultationQueue.php';
                }, 1500);
            } else {
                submitBtn.prop('disabled', false).html(originalHtml);
                appAlert("Encounter Blocked", response.message, "error");
            }
        },
        error: function(xhr, status, error) {
            submitBtn.prop('disabled', false).html(originalHtml);
            appAlert("System Error", "A critical error occurred while saving. Please check connection.", "error");
        }
    });
};

// UI Toggles
window.switchTab = function(tabId, tabElement) {
    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
    document.querySelectorAll('.patient-tab').forEach(t => t.classList.remove('active'));
    document.getElementById(tabId).classList.add('active');
    tabElement.classList.add('active');
};

// Auto-Fill Admission Setup
window.toggleAdmit = function() {
    const sel = document.getElementById('outcome_sel');
    const requiresAdmit = sel.options[sel.selectedIndex].getAttribute('data-admit'); 
    
    if (requiresAdmit == '1') {
        
        // GATEKEEPER 1: Active Admission
        if (window.OpdConfig.activeAdmission) {
            appAlert('Admission Blocked', `This patient is already admitted to ${window.OpdConfig.activeAdmission.ward_name}. You cannot recommend a new admission until they are discharged.`, 'error');
            $(sel).val('Discharged').trigger('change.select2');
            document.getElementById('admit_panel').style.display = 'none';
            return;
        }
        
        // GATEKEEPER 2: Pending Recommendation
        if (window.OpdConfig.pendingAdmission) {
            $('#pendingAdmWard').text(window.OpdConfig.pendingAdmission.requested_ward);
            $('#pendingAdmDate').text(window.OpdConfig.pendingAdmission.created_at);
            $('#modalPendingAdmission').modal('show');
            $(sel).val('Discharged').trigger('change.select2'); // Revert until cleared
            document.getElementById('admit_panel').style.display = 'none';
            return;
        }

        document.getElementById('admit_panel').style.display = 'block';

        // Auto-fill Diagnosis
        const principalRadio = document.querySelector('input[name="is_principal"]:checked');
        if (principalRadio) {
            const val = principalRadio.value;
            const hiddenInputs = document.querySelectorAll('input[name="diag_row_id[]"]');
            hiddenInputs.forEach(input => {
                if(input.value === val) {
                    const row = input.closest('.form-row');
                    const diagCodeSelect = row.querySelector('.diag-code-input');
                    if (diagCodeSelect && diagCodeSelect.selectedIndex > -1) {
                        const diagText = diagCodeSelect.options[diagCodeSelect.selectedIndex].text;
                        if (diagText) {
                            const diagParts = diagText.split(' - ');
                            const finalDiag = diagParts[1] ? diagParts[1].trim() : diagText;
                            if($('input[name="admit_diag"]').val().trim() === '') {
                                $('input[name="admit_diag"]').val(finalDiag);
                            }
                        }
                    }
                }
            });
        }

        // Auto-fill Instructions with non-empty dynamic fields
        if($('textarea[name="ward_instructions"]').val().trim() === '') {
            let instructions = "";
            $('[name^="dynamic_fields"]').each(function() {
                let label = $(this).closest('.form-col').find('label').first().text().replace('*', '').trim();
                let val = $(this).val();
                if(Array.isArray(val)) val = val.join(', ');
                if (val && val.trim() !== '') {
                    instructions += label + ":\n" + val.trim() + "\n\n";
                }
            });
            $('textarea[name="ward_instructions"]').val(instructions.trim());
        }
    } else {
        document.getElementById('admit_panel').style.display = 'none';
    }
};

window.cancelPendingAdmission = function() {
    let reqId = window.OpdConfig.pendingAdmission.id;
    $.post('/rimax/application/dripend/includes/consultation/processUpdateConsultation.php', {
        action: 'cancel_pending_admission',
        request_id: reqId
    }, function(res) {
        if(res.status === 'success') {
            window.OpdConfig.pendingAdmission = null; // Clear it
            $('#modalPendingAdmission').modal('hide');
            appAlert('Success', 'Previous admission recommendation successfully cancelled. You can now recommend a new admission.', 'success');
        } else {
            appAlert('Error', res.message, 'error');
        }
    }, 'json');
};

window.toggleRx = function() {
    const dept = document.getElementById('dispensary_dept').value;
    const wrapper = document.getElementById('rx_container_wrapper');
    wrapper.style.opacity = dept ? '1' : '0.5';
    wrapper.style.pointerEvents = dept ? 'auto' : 'none';
};

// Lab Results Viewer Logic
window.toggleAllLabs = function(source) {
    let checkboxes = document.getElementsByClassName('lab-result-chk');
    for(var i=0, n=checkboxes.length; i<n; i++) {
        checkboxes[i].checked = source.checked;
    }
}

window.viewSelectedLabs = function() {
    let ids = [];
    $('.lab-result-chk:checked').each(function() { ids.push($(this).val()); });
    if(ids.length === 0) { 
        appAlert('No Selection', 'Please check the box next to at least one completed investigation to view results.', 'warning'); 
        return; 
    }
    viewLabResults(ids);
}

window.viewLabResults = function(request_ids) {
    $('#labResultsArea').html('<div class="text-center py-5"><i class="fa fa-spinner fa-spin fa-2x text-primary mb-3"></i><br>Fetching Results...</div>');
    $('#modalLabResults').modal('show');
    
    $.post('/rimax/application/dripend/includes/consultation/processConsultation.php', {
        action: 'fetch_lab_results',
        request_ids: request_ids
    }, function(res) {
        if(res.status === 'success') {
            $('#labResultsArea').html(res.html);
        } else {
            $('#labResultsArea').html('<div class="text-center text-danger py-5"><i class="fa-solid fa-triangle-exclamation fa-2x mb-3"></i><br>Failed to load results.</div>');
        }
    }, 'json');
}

// DOM Row Generators
let diagRowCounter = window.OpdConfig.baseDiagCount;

window.addDiagRow = function() {
    let currentIdx = diagRowCounter++;
    const row = document.createElement('div');
    row.className = 'form-row align-items-center';
    row.innerHTML = `
        <input type="hidden" name="diag_row_id[]" value="${currentIdx}">
        <div class="form-col" style="flex:0.3; text-align:center;">
            <label>Principal</label>
            <input type="radio" name="is_principal" value="${currentIdx}" required style="transform: scale(1.4); cursor:pointer;">
        </div>
        <div class="form-col" style="flex:0.5;"><select name="diag_type[]" class="input-control select2-generic" style="width:100%;"><option value="ICD-10">ICD-10</option><option value="G-DRG">G-DRG</option></select></div>
        <div class="form-col" style="flex:2.5;"><select name="diag_code[]" class="input-control select2-diag-dynamic diag-code-input" style="width: 100%;"><option value=""></option>${icdOptionsHTML}</select></div>
        <div class="form-col" style="flex:2;"><input type="text" name="diag_desc[]" class="input-control" placeholder="Description"></div>
        <div class="form-col" style="flex:0.8;"><select name="diag_status[]" class="input-control select2-generic" style="width:100%;">${jsDiagStatusOptions}</select></div>
        <button type="button" class="btn-red" onclick="this.parentElement.remove()" style="margin-top:22px;"><i class="fa-solid fa-trash"></i></button>
    `;
    document.getElementById('diag_container').insertBefore(row, document.getElementById('diag_container').lastElementChild);
    $(row).find('.select2-diag-dynamic').select2({ placeholder: "Search ICD-10 Code or Disease..." });
    $(row).find('.select2-generic').select2();
};

window.addRxRow = function() {
    const wrapper = document.createElement('div');
    wrapper.innerHTML = `
        <div class="form-row">
            <div class="form-col" style="flex:2.5;"><label>Search Formulary</label><select name="rx_drug[]" class="input-control select2-drug-dynamic" style="width: 100%;"><option value=""></option>${drugOptionsHTML}</select></div>
            <div class="form-col" style="flex:1;"><label>Form</label><select name="rx_form[]" class="input-control select2-generic form-field" style="width:100%;"><option value="">Select</option>${jsFormOptions}</select></div>
            <div class="form-col" style="flex:1;"><label>Strength</label><input type="text" name="rx_strength[]" class="input-control strength-field" placeholder="e.g. 500mg"></div>
            <div class="form-col" style="flex:0.8;"><label>Dose</label><input type="text" name="rx_dose[]" class="input-control dose-field" placeholder="e.g. 1"></div>
            <div class="form-col" style="flex:1.2;"><label>Freq</label><select name="rx_freq[]" class="input-control select2-generic freq-field" style="width:100%;"><option value="">Select</option>${jsFreqOptions}</select></div>
            <div class="form-col" style="flex:0.5;"><label>Days</label><input type="number" name="rx_dur[]" class="input-control dur-field"></div>
            <div class="form-col" style="flex:0.8;"><label style="color:#0284c7;">Total Qty</label><input type="number" name="rx_qty[]" class="input-control total-qty-field" style="border-color:#0ea5e9; font-weight:bold;" readonly></div>
        </div>
        <div class="form-row" style="margin-top:-5px; margin-bottom:25px; border-bottom:1px dashed var(--border); padding-bottom:20px;">
            <div class="form-col" style="flex:1;"><input type="text" name="rx_remarks[]" class="input-control" placeholder="Prescription Notes / Remarks"></div>
            <button type="button" class="btn-red" onclick="this.parentElement.previousElementSibling.remove(); this.parentElement.remove();"><i class="fa-solid fa-trash"></i></button>
        </div>
    `;
    document.getElementById('rx_container').appendChild(wrapper);
    $(wrapper).find('.select2-drug-dynamic').select2({ placeholder: "Search Drug..." });
    $(wrapper).find('.select2-generic').select2();
};

window.addLabRow = function() {
    const row = document.createElement('div');
    row.className = 'form-row';
    row.innerHTML = `
        <div class="form-col" style="flex:3;"><label>Test / Procedure Requested</label><select name="lab_test[]" class="input-control select2-lab-dynamic" style="width: 100%;" onchange="autoRouteService(this)"><option value=""></option>${labOptionsHTML}</select></div>
        <div class="form-col" style="flex:1;"><label>Routed Department</label><input type="hidden" name="lab_dept_id[]" class="dept-id-field"><input type="text" class="input-control input-readonly dept-name-field" placeholder="Auto-mapped..." readonly></div>
        <button type="button" class="btn-red" onclick="this.parentElement.remove()" style="margin-top:22px;"><i class="fa-solid fa-trash"></i></button>
    `;
    document.getElementById('lab_container').insertBefore(row, document.getElementById('lab_container').lastElementChild);
    $(row).find('.select2-lab-dynamic').select2({ placeholder: "Search Service Catalog..." });
};