// Wrapped in an init function so the SPA router can call it when the module loads
window.initIpdManagement = function() {
    
    // Destroy previous event listeners to prevent duplicate firing in SPA
    $('#frmAddWard').off('submit');
    $('#frmGenerateBeds').off('submit');
    $('#frmAddIpdHelper').off('submit');

    // 1. Submit Ward Setup
    $('#frmAddWard').on('submit', function(e) {
        e.preventDefault();
        let formData = $(this).serialize();
        
        $.ajax({
            url: '/rimax/application/dripend/systemSetup/ipd/processIPDManagement.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(res) {
                if(res.status === 'success') {
                    alert('Ward successfully created and initialized.');
                    $('#frmAddWard')[0].reset();
                    // Optionally, trigger a refresh of the ward dropdown in tab 2 here
                } else {
                    alert('Error: ' + res.message);
                }
            },
            error: function() {
                alert('A network error occurred while creating the ward.');
            }
        });
    });

    // 2. Submit Room & Bed Generator
    $('#frmGenerateBeds').on('submit', function(e) {
        e.preventDefault();
        let numBeds = $('input[name="number_of_beds"]').val();
        let roomName = $('input[name="room_number_or_name"]').val();
        
        if(!confirm(`WARNING: You are about to deploy ${numBeds} physical beds into ${roomName}. This action will alter hospital capacity metrics. Proceed?`)) {
            return;
        }

        let formData = $(this).serialize();
        
        $.ajax({
            url: '/rimax/application/dripend/systemSetup/ipd/processIPDManagement.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(res) {
                if(res.status === 'success') {
                    alert(res.message); 
                    $('#frmGenerateBeds')[0].reset();
                } else {
                    alert('Generation Error: ' + res.message);
                }
            },
            error: function() {
                alert('A network error occurred during bed generation.');
            }
        });
    });

    // 3. Submit IPD Helpers Mapping
    $('#frmAddIpdHelper').on('submit', function(e) {
        e.preventDefault();
        let formData = $(this).serialize();
        
        $.ajax({
            url: '/rimax/application/dripend/systemSetup/ipd/processIPDManagement.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(res) {
                if(res.status === 'success') {
                    alert('Clinical helper field mapped successfully to the IPD workspace.');
                    $('#frmAddIpdHelper')[0].reset();
                } else {
                    alert('Mapping Error: ' + res.message);
                }
            },
            error: function() {
                alert('A network error occurred while mapping the helper.');
            }
        });
    });
};

// Auto-initialize if loaded directly outside the SPA framework
if (document.readyState === 'complete' || document.readyState !== 'loading') {
    if(typeof window.initIpdManagement === 'function') {
        window.initIpdManagement();
    }
} else {
    document.addEventListener('DOMContentLoaded', function() {
        if(typeof window.initIpdManagement === 'function') {
            window.initIpdManagement();
        }
    });
}