document.addEventListener('DOMContentLoaded', function() {
    
    // 1. Initialize Checkbox Toggles securely
    function setupDependentToggle(toggleId, blockId) {
        const toggle = document.getElementById(toggleId);
        const block = document.getElementById(blockId);
        if(toggle && block) {
            // Set initial state
            block.classList.toggle('active', toggle.checked);
            
            // Listen for changes
            toggle.addEventListener('change', function() {
                block.classList.toggle('active', this.checked);
            });
        }
    }

    setupDependentToggle('smsToggle', 'smsBlock');
    setupDependentToggle('emailToggle', 'emailBlock');
    setupDependentToggle('paymentToggle', 'paymentBlock');
    setupDependentToggle('hl7Toggle', 'hl7Block');
    setupDependentToggle('pacsToggle', 'pacsBlock');

    // 2. Load DB Data for Hot-Swapping
    const dataNode = document.getElementById('db-integration-data');
    let dbConfig = {};
    if (dataNode) {
        try { 
            dbConfig = JSON.parse(dataNode.textContent); 
        } catch (e) { 
            console.error("Could not parse DB Configs"); 
        }
    }

    // Helper to safely extract configuration keys
    function getConfig(module, provider, key, defaultVal = '') {
        if (dbConfig[module] && dbConfig[module][provider] && dbConfig[module][provider][key]) {
            return dbConfig[module][provider][key];
        }
        return defaultVal;
    }

    // 3. Hot-Swap Logic for SMS
    const smsSelect = document.getElementById('smsProviderSelect');
    if (smsSelect) {
        smsSelect.addEventListener('change', function() {
            const prov = this.value;
            document.getElementById('smsSenderId').value = getConfig('sms', prov, 'sender_id');
            document.getElementById('smsUrl').value = getConfig('sms', prov, 'destination_url');
            document.getElementById('smsApiKey').value = getConfig('sms', prov, 'api_key');
        });
        // Trigger immediately to populate fields on page load
        smsSelect.dispatchEvent(new Event('change'));
    }

    // Hot-Swap Logic for Email (SMTP is the only provider currently, but this keeps it consistent)
    if (document.getElementById('emailHost')) {
        document.getElementById('emailHost').value = getConfig('email', 'SMTP', 'smtp_host');
        document.getElementById('emailPort').value = getConfig('email', 'SMTP', 'smtp_port');
        document.getElementById('emailUser').value = getConfig('email', 'SMTP', 'smtp_user');
        document.getElementById('emailPass').value = getConfig('email', 'SMTP', 'smtp_pass');
        document.getElementById('emailFromName').value = getConfig('email', 'SMTP', 'from_name');
    }

    // Hot-Swap Logic for Payments
    const paySelect = document.getElementById('paymentProviderSelect');
    if (paySelect) {
        paySelect.addEventListener('change', function() {
            const prov = this.value;
            document.getElementById('paymentEnv').value = getConfig('payment', prov, 'environment', 'test');
            document.getElementById('paymentUrl').value = getConfig('payment', prov, 'destination_url');
            document.getElementById('paymentPubKey').value = getConfig('payment', prov, 'public_key');
            document.getElementById('paymentSecKey').value = getConfig('payment', prov, 'secret_key');
        });
        // Trigger immediately to populate fields on page load
        paySelect.dispatchEvent(new Event('change'));
    }

    // Hot-Swap Logic for HL7
    const hl7Select = document.getElementById('hl7ProviderSelect');
    if (hl7Select) {
        hl7Select.addEventListener('change', function() {
            const prov = this.value;
            document.getElementById('hl7Ip').value = getConfig('hl7', prov, 'ip_address');
            document.getElementById('hl7Port').value = getConfig('hl7', prov, 'port');
        });
        // Trigger immediately to populate fields on page load
        hl7Select.dispatchEvent(new Event('change'));
    }
});

// Global Notification Helper
window.showIntegrationNotification = function(type, message) {
    const banner = document.getElementById('uiNotificationBanner');
    if (!banner) return;

    banner.style.display = 'flex';
    if (type === 'success') {
        banner.style.backgroundColor = '#f0fdf4';
        banner.style.color = '#166534';
        banner.style.border = '1px solid #bbf7d0';
        banner.innerHTML = '<i class="fa-solid fa-circle-check"></i> ' + message;
    } else {
        banner.style.backgroundColor = '#fef2f2';
        banner.style.color = '#991b1b';
        banner.style.border = '1px solid #fecaca';
        banner.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i> <strong>Error:</strong> ' + message;
    }
    
    // Scroll to the top so the user sees the banner
    window.scrollTo({ top: 0, behavior: 'smooth' });
    
    // Hide after 8 seconds
    setTimeout(() => { banner.style.display = 'none'; }, 8000);
};

// 4. Save Function
window.saveIntegrations = function(btnElement) {
    const form = document.getElementById('integrationsForm');
    const formData = new FormData(form);

    // Explicitly capture toggle switch states (Unchecked HTML checkboxes do not post data natively)
    const toggles = ['sms_enabled', 'email_enabled', 'payment_enabled', 'hl7_enabled', 'pacs_enabled', 'biometrics_enabled'];
    toggles.forEach(name => {
        formData.set(name, form.elements[name] && form.elements[name].checked ? '1' : '0');
    });

    const originalHTML = btnElement.innerHTML;
    btnElement.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Encrypting & Saving...';
    btnElement.disabled = true;

    // Connect to the backend processor
    fetch('../../dripend/systemSetup/facility/process_integrations.php', {
        method: 'POST',
        body: formData
    })
    .then(async response => {
        const text = await response.text();
        try {
            const data = JSON.parse(text);
            
            if(data.status === 'success') {
                window.showIntegrationNotification('success', 'API Keys securely updated for all active providers.');
                btnElement.innerHTML = '<i class="fa-solid fa-shield-check"></i> Integrations Secured';
                btnElement.style.backgroundColor = '#16a34a';
                
                setTimeout(() => {
                    btnElement.innerHTML = originalHTML;
                    btnElement.disabled = false;
                    btnElement.style.backgroundColor = ''; 
                }, 3000);
            } else {
                window.showIntegrationNotification('error', data.message || 'Unknown Backend Database Error.');
                btnElement.innerHTML = originalHTML;
                btnElement.disabled = false;
            }
        } catch (e) {
            console.error("Server Response:", text);
            window.showIntegrationNotification('error', 'Server crash. Please check browser console for PHP errors.');
            btnElement.innerHTML = originalHTML;
            btnElement.disabled = false;
        }
    })
    .catch(err => {
        console.error('Fetch error:', err);
        window.showIntegrationNotification('error', 'Network Error. Could not connect to the backend server.');
        btnElement.innerHTML = originalHTML;
        btnElement.disabled = false;
    });
};