document.addEventListener("DOMContentLoaded", function () {
    const serviceSelect = document.getElementById("service_id");
    const subDeptSelect = document.getElementById("lab_sub_dept_id");
    const mappingForm = document.getElementById("addMappingForm");
    const alertContainer = document.getElementById("addMappingAlert");

    // Load dropdown selections reactively from backend database sources
    loadFormDependencies();

    function loadFormDependencies() {
        // Fetch all diagnostic laboratory test entries
        fetch('get_lab_services_endpoint') 
            .then(response => response.json())
            .then(data => {
                serviceSelect.innerHTML = '<option value="">-- Select Lab Investigation --</option>';
                if(data.success && data.services.length > 0) {
                    data.services.forEach(service => {
                        let currentMapping = service.sub_dept_name ? ` (Currently: ${service.sub_dept_name})` : ' (Unmapped)';
                        serviceSelect.innerHTML += `<option value="${service.id}">${service.service_name}${currentMapping}</option>`;
                    });
                } else {
                    serviceSelect.innerHTML = '<option value="">No Active Laboratory Investigations Found</option>';
                }
            })
            .catch(() => {
                serviceSelect.innerHTML = '<option value="">Error loading investigations</option>';
            });

        // Fetch active lab workstation options (Haematology, Microbiology, etc.)
        fetch('get_lab_benches_endpoint')
            .then(response => response.json())
            .then(data => {
                subDeptSelect.innerHTML = '<option value="">-- Select Lab Bench --</option>';
                if(data.success && data.benches.length > 0) {
                    data.benches.forEach(bench => {
                        subDeptSelect.innerHTML += `<option value="${bench.id}">${bench.sub_dept_name}</option>`;
                    });
                } else {
                    subDeptSelect.innerHTML = '<option value="">No Active Lab Benches Found</option>';
                }
            })
            .catch(() => {
                subDeptSelect.innerHTML = '<option value="">Error loading benches</option>';
            });
    }

    // Submit request handling
    mappingForm.addEventListener("submit", function (e) {
        e.preventDefault();
        
        const formData = new FormData(mappingForm);

        fetch('save_mapping_endpoint', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alertContainer.innerHTML = `
                    <div class="lis-alert lis-alert-success">
                        <i class="fa-solid fa-circle-check"></i> ${data.message}
                    </div>
                `;
                mappingForm.reset();
                loadFormDependencies(); // Refresh option text to show updated mapping statuses
            } else {
                alertContainer.innerHTML = `
                    <div class="lis-alert lis-alert-error">
                        <i class="fa-solid fa-circle-xmark"></i> ${data.message}
                    </div>
                `;
            }
        })
        .catch(() => {
            alertContainer.innerHTML = `
                <div class="lis-alert lis-alert-error">
                    <i class="fa-solid fa-circle-xmark"></i> System communications failure. Please check server logs.
                </div>
            `;
        });
    });
});