<?php $nonce = wp_create_nonce( 'quttera' ); ?>

<script type="text/javascript">

    // ===== FORM STATE TRACKING =====
    let initialFormState = {};
    let formHasChanged = false;

    jQuery(document).ready(function($) {
        // ===== INITIALIZATION =====
        initializePageLoad();
        
        // Capture initial form state and set up change tracking
        captureInitialFormState();
        setupFormChangeListeners();
        updateSaveButtonState();

        // ===== FORM SUBMISSION =====
        $('form').on('submit', function(e) {
            e.preventDefault();
            submitAllSettings();
        });

        // ===== WHITELIST IPS MANAGEMENT =====
        document.getElementById('add_whitelist_btn').addEventListener('click', addWhitelistIP);
        document.getElementById('whitelist_ip_input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                addWhitelistIP();
            }
        });

        // ===== TRUSTED PROXY MANAGEMENT =====
        document.getElementById('add_trusted_proxy_btn').addEventListener('click', addTrustedProxy);
        document.getElementById('trusted_proxy_input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                addTrustedProxy();
            }
        });

        // ===== TRUSTED PROXY ENABLE/DISABLE HANDLER =====
        document.getElementById('trusted_proxy_enabled').addEventListener('change', function() {
            toggleTrustedProxySection(this.checked);
        });

        // ===== MANUAL BLACKLIST MANAGEMENT =====
        document.getElementById('add_manual_blocked_btn').addEventListener('click', addManuallyBlockedIP);
        document.getElementById('manual_blocked_ip_input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                addManuallyBlockedIP();
            }
        });
    });


    /**
     * Initialize page on load
     */
    function initializePageLoad() {
        renderWhitelistIPsList();
        renderTrustedProxiesList();
        renderManuallyBlockedIPsList();
        initializeTrustedProxySection();
    }

    /**
     * Capture the initial state of all form fields for change detection
     */
    function captureInitialFormState() {
        const state = {};
        const form = document.querySelector('form');
        
        // Get all input fields
        form.querySelectorAll('input[type="text"], input[type="email"], input[type="checkbox"], input[type="radio"]').forEach(input => {
            if (input.type === 'checkbox' || input.type === 'radio') {
                state[input.name + '_' + input.value] = input.checked;
            } else {
                state[input.name] = input.value;
            }
        });
        
        // Get all select fields
        form.querySelectorAll('select').forEach(select => {
            state[select.name] = select.value;
        });
        
        // Get all hidden fields (for IP lists)
        form.querySelectorAll('input[type="hidden"]').forEach(input => {
            state[input.id] = input.value;
        });
        
        initialFormState = state;
        console.log('Initial form state captured:', initialFormState);
    }

    /**
     * Compare current form state with initial state
     */
    function getCurrentFormState() {
        const state = {};
        const form = document.querySelector('form');
        
        // Get all input fields
        form.querySelectorAll('input[type="text"], input[type="email"], input[type="checkbox"], input[type="radio"]').forEach(input => {
            if (input.type === 'checkbox' || input.type === 'radio') {
                state[input.name + '_' + input.value] = input.checked;
            } else {
                state[input.name] = input.value;
            }
        });
        
        // Get all select fields
        form.querySelectorAll('select').forEach(select => {
            state[select.name] = select.value;
        });
        
        // Get all hidden fields (for IP lists)
        form.querySelectorAll('input[type="hidden"]').forEach(input => {
            state[input.id] = input.value;
        });
        
        return state;
    }

    /**
     * Check if form state has changed from initial state
     */
    function hasFormChanged() {
        const currentState = getCurrentFormState();
        
        for (const key in initialFormState) {
            if (initialFormState[key] !== currentState[key]) {
                console.log(`Change detected in field: ${key}`);
                return true;
            }
        }
        
        // Also check if any new fields were added
        for (const key in currentState) {
            if (!(key in initialFormState)) {
                console.log(`New field detected: ${key}`);
                return true;
            }
        }
        
        return false;
    }

    /**
     * Update the Save button state based on whether form has changed
     */
    function updateSaveButtonState() {
        const saveBtn = document.querySelector('form button[type="submit"]');
        if (!saveBtn) return;
        
        // Always reset button text to "Save"
        saveBtn.textContent = 'Save';
        
        formHasChanged = hasFormChanged();
        
        if (formHasChanged) {
            saveBtn.disabled = false;
            saveBtn.style.opacity = '1';
            saveBtn.style.cursor = 'pointer';
        } else {
            saveBtn.disabled = true;
            saveBtn.style.opacity = '0.5';
            saveBtn.style.cursor = 'not-allowed';
        }
        
        console.log('Save button state updated. Has changes:', formHasChanged);
    }

    /**
     * Set up change listeners on all form fields
     */
    function setupFormChangeListeners() {
        const form = document.querySelector('form');
        
        // Listen for changes on all input fields
        form.querySelectorAll('input[type="text"], input[type="email"], input[type="checkbox"], input[type="radio"]').forEach(input => {
            input.addEventListener('change', updateSaveButtonState);
            input.addEventListener('input', updateSaveButtonState);
        });
        
        // Listen for changes on all select fields
        form.querySelectorAll('select').forEach(select => {
            select.addEventListener('change', updateSaveButtonState);
        });
    }

    /**
     * Hook into IP list changes to update form state
     * This is called after IP lists are modified
     */
    function onIPListChanged() {
        updateSaveButtonState();
    }

    /**
     * Check for IP conflicts between whitelisted, blacklisted, and trusted proxy lists
     * Returns object with conflicts found and error message
     */
    function checkIPConflicts() {
        const whitelist = getWhitelistIPs();
        const blacklist = getManuallyBlockedIPs();
        const trustedProxies = getTrustedProxyIPs();
        
        const conflicts = {
            found: false,
            whitelistInBlacklist: [],
            blacklistInTrusted: []
        };
        
        // Check whitelist IPs in blacklist
        whitelist.forEach(ip => {
            if (blacklist.includes(ip)) {
                conflicts.found = true;
                conflicts.whitelistInBlacklist.push(ip);
            }
        });
        
        // Check blacklist IPs in trusted proxies
        blacklist.forEach(ip => {
            if (trustedProxies.includes(ip)) {
                conflicts.found = true;
                conflicts.blacklistInTrusted.push(ip);
            }
        });
        
        return conflicts;
    }

    /**
     * Format conflicts into error message
     */
    function formatConflictMessage(conflicts) {
        let message = 'IP Conflicts detected:\n\n';
        
        if (conflicts.whitelistInBlacklist.length > 0) {
            message += '• Whitelisted IP(s) in blacklist: ' + conflicts.whitelistInBlacklist.join(', ') + '\n';
        }
        if (conflicts.blacklistInTrusted.length > 0) {
            message += '• Blacklisted IP(s) in trusted proxies: ' + conflicts.blacklistInTrusted.join(', ') + '\n';
        }
        
        message += '\nPlease remove the conflicting IPs from the blacklist.';
        return message;
    }

    /**
     * Collect and submit ALL settings in one procedure
     */
    function submitAllSettings() {
        // Check if there are any changes before submitting
        if (!hasFormChanged()) {
            showAlert('alert-warning', 'No changes detected. Make changes to the settings before saving.');
            return;
        }
        
        // Check for IP conflicts before saving
        const conflicts = checkIPConflicts();
        if (conflicts.found) {
            showAlert('alert-danger', formatConflictMessage(conflicts));
            return;
        }
        
        // Collect blocked IPs from the rendered list
        const blockedIPsContainer = document.getElementById('manual_blocked_ips_list');
        if (!blockedIPsContainer) {
            console.warn('Manual blocked IPs container not found');
            return;
        }
        const blockedIPItems = blockedIPsContainer.querySelectorAll('.list-group-item strong');
        const blockedIPs = [];
        blockedIPItems.forEach(item => {
            const ip = item.textContent.trim();
            if (ip) blockedIPs.push(ip);
        });

        const formData = {
            // General tab
            alert_email: document.querySelector('input[name="alert_email"]').value,
            alarms_enabled: document.querySelector('input[name="alarms_enabled"]').checked ? 'on' : 'off',
            hosting_type: document.querySelector('input[name="hosting_type"]:checked').value,

            // Scanner tab
            scan_mode: document.querySelector('select[name="scan_mode"]').value,
            cure_mode: document.querySelector('select[name="cure_mode"]').value,
            fs_integrity_mode: document.querySelector('select[name="fs_integrity_mode"]').value,
            continuous_scan_period: document.querySelector('select[name="continuous_scan_period"]').value || '',

            // Protection tab
            bot_protection_enabled: document.querySelector('select[name="bot_protection_enabled"]').value,

            // Brute-force tab
            bruteforce_enabled: document.querySelector('select[name="bruteforce_enabled"]').value,
            trusted_proxy_enabled: document.querySelector('input[name="trusted_proxy_enabled"]').checked ? 'on' : 'off',
            whitelist_ips: document.querySelector('#whitelist_ips_field').value,
            trusted_proxy_ips: document.querySelector('#trusted_proxy_ips_field').value,
            manually_blocked_ips: document.querySelector('#manually_blocked_ips_field').value,
            blocked_ips: blockedIPs.join(';'),

            // Security
            action: 'scanner-settings',
            _wpnonce: '<?php echo $nonce; ?>',
            _wp_http_referer: document.querySelector('input[name="_wp_http_referer"]').value,
        };

        const submitBtn = document.querySelector('form button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.textContent = 'Saving...';

        showAlert('alert-info', 'Submitting settings...');

        jQuery.ajax({
            type: 'POST',
            url: ajaxurl,
            data: formData,
            success: function(response) {
                console.log('Settings saved:', response);
                // Update initial state to current state (no more unsaved changes)
                captureInitialFormState();
                updateSaveButtonState();
                showAlert('alert-success', response.data?.message || 'Settings saved successfully!');
            },
            error: function(xhr, status, error) {
                // Re-enable button but don't reset state
                updateSaveButtonState();
                console.error('Error saving settings:', xhr, error);
                const msg = xhr.responseJSON?.data?.message || 'Error saving settings';
                showAlert('alert-danger', msg);
            }
        });
    }

    /**
     * Show alert message
     */
    function showAlert(alertClass, message) {
        const form = document.querySelector('form');
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert ${alertClass} mt-3`;
        alertDiv.textContent = message;
        form.insertBefore(alertDiv, form.firstChild);

        setTimeout(function() {
            alertDiv.style.opacity = '0';
            alertDiv.style.transition = 'opacity 0.5s';
            setTimeout(() => alertDiv.remove(), 500);
        }, 5000);
    }

    /**
     * ===== WHITELIST IPS MANAGEMENT =====
     */
    function addWhitelistIP() {
        const input = document.getElementById('whitelist_ip_input');
        const ip = input.value.trim();

        if (!ip) {
            alert('Please enter an IP address');
            input.focus();
            return;
        }

        if (!validateIP(ip)) {
            alert('Invalid IP format. Use IPv4, IPv6, or CIDR notation (e.g., 192.168.1.0/24)');
            input.select();
            return;
        }

        const currentIPs = getWhitelistIPs();
        if (currentIPs.includes(ip)) {
            alert('This IP is already whitelisted');
            input.select();
            return;
        }

        // Check if IP is in blacklist
        const blacklist = getManuallyBlockedIPs();
        if (blacklist.includes(ip)) {
            alert('Cannot whitelist IP ' + ip + ' - it is currently blacklisted. Please remove it from blacklist first.');
            input.select();
            return;
        }

        currentIPs.push(ip);
        updateWhitelistField(currentIPs);
        renderWhitelistIPsList();
        input.value = '';
        input.focus();
    }

    function getWhitelistIPs() {
        const field = document.getElementById('whitelist_ips_field');
        const value = field.value.trim();
        return value ? value.split(';').map(ip => ip.trim()).filter(ip => ip.length > 0) : [];
    }

    function updateWhitelistField(ips) {
        document.getElementById('whitelist_ips_field').value = ips.join(';');
        onIPListChanged();
    }

    function renderWhitelistIPsList() {
        const ips = getWhitelistIPs();
        const container = document.getElementById('whitelist_ips_list');
        const emptyMsg = document.getElementById('whitelist_empty_msg');
        const count = document.getElementById('whitelist_count');

        container.innerHTML = '';
        count.textContent = ips.length;

        if (ips.length === 0) {
            emptyMsg.style.display = 'block';
            return;
        }

        emptyMsg.style.display = 'none';

        ips.forEach(function(ip) {
            const item = document.createElement('div');
            item.className = 'list-group-item d-flex justify-content-between align-items-center';
            item.innerHTML = `
                <div>
                    <strong>${escapeHtml(ip)}</strong>
                </div>
                <button type="button" class="btn btn-sm btn-outline-info" onclick="removeWhitelistIP('${ip.replace(/'/g, "\\'")}')">
                    <i class="bi bi-x"></i> Remove
                </button>
            `;
            container.appendChild(item);
        });
    }

    function removeWhitelistIP(ip) {
        console.log('removeWhitelistIP called with:', ip);
        //if (!confirm(`Remove whitelist entry: ${ip}?`)) return;
        let ips = getWhitelistIPs();
        ips = ips.filter(item => item !== ip);
        updateWhitelistField(ips);
        renderWhitelistIPsList();
    }

    /**
     * ===== TRUSTED PROXY MANAGEMENT =====
     */
    function addTrustedProxy() {
        const input = document.getElementById('trusted_proxy_input');
        const ip = input.value.trim();

        if (!ip) {
            alert('Please enter a proxy IP');
            input.focus();
            return;
        }

        if (!validateIP(ip)) {
            alert('Invalid IP format. Use IPv4, IPv6, or CIDR notation (e.g., 104.16.0.0/12)');
            input.select();
            return;
        }

        const currentIPs = getTrustedProxyIPs();
        if (currentIPs.includes(ip)) {
            alert('This proxy is already trusted');
            input.select();
            return;
        }

        // Check if IP is blacklisted
        const blacklist = getManuallyBlockedIPs();
        if (blacklist.includes(ip)) {
            alert('Cannot add trusted proxy ' + ip + ' - it is currently blacklisted. Please remove it from blacklist first.');
            input.select();
            return;
        }

        currentIPs.push(ip);
        updateTrustedProxyField(currentIPs);
        renderTrustedProxiesList();
        input.value = '';
        input.focus();
    }

    function getTrustedProxyIPs() {
        const field = document.getElementById('trusted_proxy_ips_field');
        const value = field.value.trim();
        return value ? value.split(';').map(ip => ip.trim()).filter(ip => ip.length > 0) : [];
    }

    function updateTrustedProxyField(ips) {
        document.getElementById('trusted_proxy_ips_field').value = ips.join(';');
        onIPListChanged();
    }

    function renderTrustedProxiesList() {
        const ips = getTrustedProxyIPs();
        const container = document.getElementById('trusted_proxies_list');
        const emptyMsg = document.getElementById('trusted_proxies_empty');

        container.innerHTML = '';

        if (ips.length === 0) {
            emptyMsg.style.display = 'block';
            return;
        }

        emptyMsg.style.display = 'none';

        ips.forEach(function(ip) {
            const item = document.createElement('div');
            item.className = 'list-group-item d-flex justify-content-between align-items-center';
            item.innerHTML = `
                <div>
                    <strong>${escapeHtml(ip)}</strong>
                    <div class="q-help">Trusted proxy IP</div>
                </div>
                <button type="button" class="btn btn-sm btn-outline-info" onclick="removeTrustedProxy('${ip.replace(/'/g, "\\'")}')">
                    <i class="bi bi-x"></i> Remove
                </button>
            `;
            container.appendChild(item);
        });
    }

    function removeTrustedProxy(ip) {
        console.log('removeTrustedProxy called with:', ip);
        //if (!confirm(`Remove trusted proxy: ${ip}?`)) return;
        let ips = getTrustedProxyIPs();
        ips = ips.filter(item => item !== ip);
        updateTrustedProxyField(ips);
        renderTrustedProxiesList();
    }

    /**
     * ===== MANUALLY BLOCKED IPS MANAGEMENT =====
     */
    function addManuallyBlockedIP() {
        const input = document.getElementById('manual_blocked_ip_input');
        const ip = input.value.trim();

        if (!ip) {
            alert('Please enter an IP address');
            input.focus();
            return;
        }

        if (!validateIP(ip)) {
            alert('Invalid IP format. Use IPv4, IPv6, or CIDR notation (e.g., 192.168.1.100 or 10.0.0.0/8)');
            input.select();
            return;
        }

        const currentIPs = getManuallyBlockedIPs();
        if (currentIPs.includes(ip)) {
            alert('This IP is already blacklisted');
            input.select();
            return;
        }

        // Check if IP is whitelisted
        const whitelist = getWhitelistIPs();
        if (whitelist.includes(ip)) {
            alert('Cannot blacklist IP ' + ip + ' - it is currently whitelisted. Please remove it from whitelist first.');
            input.select();
            return;
        }

        // Check if IP is trusted proxy
        const trustedProxies = getTrustedProxyIPs();
        if (trustedProxies.includes(ip)) {
            alert('Cannot blacklist IP ' + ip + ' - it is currently a trusted proxy. Please remove it from trusted proxies first.');
            input.select();
            return;
        }

        currentIPs.push(ip);
        updateManuallyBlockedIPsField(currentIPs);
        renderManuallyBlockedIPsList();
        // Mark form as modified
        document.getElementById('manually_blocked_ips_field').dispatchEvent(new Event('change', { bubbles: true }));
        input.value = '';
        input.focus();
    }

    function getManuallyBlockedIPs() {
        const field = document.getElementById('manually_blocked_ips_field');
        const value = field.value.trim();
        return value ? value.split(';').map(ip => ip.trim()).filter(ip => ip.length > 0) : [];
    }

    function updateManuallyBlockedIPsField(ips) {
        document.getElementById('manually_blocked_ips_field').value = ips.join(';');
        onIPListChanged();
    }

    function renderManuallyBlockedIPsList() {
        const ips = getManuallyBlockedIPs();
        const container = document.getElementById('manual_blocked_ips_list');
        const emptyMsg = document.getElementById('manual_blocked_empty');
        const countElement = document.getElementById('manual_count');

        // Update counter
        if (countElement) {
            countElement.textContent = ips.length;
        }

        container.innerHTML = '';

        if (ips.length === 0) {
            emptyMsg.style.display = 'block';
            return;
        }

        emptyMsg.style.display = 'none';

        ips.forEach(function(ip) {
            const item = document.createElement('div');
            item.className = 'list-group-item d-flex justify-content-between align-items-center';
            item.innerHTML = `
                <div>
                    <strong>${escapeHtml(ip)}</strong>
                    <div class="q-help">Manually blacklisted IP</div>
                </div>
                <button type="button" class="btn btn-sm btn-outline-info" onclick="removeManuallyBlockedIP('${ip.replace(/'/g, "\\'")}')">
                    <i class="bi bi-x"></i> Remove
                </button>
            `;
            container.appendChild(item);
        });
    }

    function removeManuallyBlockedIP(ip) {
        console.log('Removing manually blocked IP:', ip);
        //if (!confirm(`Remove blacklist for IP: ${ip}?`)) return;
        let ips = getManuallyBlockedIPs();
        ips = ips.filter(item => item !== ip);
        
        updateManuallyBlockedIPsField(ips);
        renderManuallyBlockedIPsList();
        // Mark form as modified
        document.getElementById('manually_blocked_ips_field').dispatchEvent(new Event('change', { bubbles: true }));
    }


    /**
     * ===== UTILITY FUNCTIONS =====
     */
    function validateIP(ip) {
        // Check if it contains CIDR notation
        if (ip.includes('/')) {
            const parts = ip.split('/');
            if (parts.length !== 2) return false;
            
            const addr = parts[0];
            const prefix = parts[1];
            
            // Validate prefix is numeric and in valid range
            if (!/^\d+$/.test(prefix)) return false;
            const prefixNum = parseInt(prefix, 10);
            
            // IPv4 with CIDR: prefix 0-32
            if (isValidIPv4(addr)) {
                return prefixNum >= 0 && prefixNum <= 32;
            }
            
            // IPv6 with CIDR: prefix 0-128
            if (isValidIPv6(addr)) {
                return prefixNum >= 0 && prefixNum <= 128;
            }
            
            return false;
        }
        
        // Regular IP address (IPv4 or IPv6)
        return isValidIPv4(ip) || isValidIPv6(ip);
    }

    function isValidIPv4(ip) {
        // Match IPv4 pattern: four octets separated by dots
        const ipv4Pattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
        const match = ip.match(ipv4Pattern);
        
        if (!match) return false;
        
        // Validate each octet is 0-255
        for (let i = 1; i <= 4; i++) {
            const octet = parseInt(match[i], 10);
            if (octet < 0 || octet > 255) {
                return false;
            }
        }
        
        return true;
    }

    function isValidIPv6(ip) {
        // Basic IPv6 validation using regex
        const ipv6Pattern = /^(([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}|::)$/;
        return ipv6Pattern.test(ip);
    }

    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    /**
     * Initialize trusted proxy section based on checkbox state
     */
    function initializeTrustedProxySection() {
        const checkbox = document.getElementById('trusted_proxy_enabled');
        if (!checkbox) return;
        const isEnabled = checkbox.checked;
        toggleTrustedProxySection(isEnabled);
    }

    /**
     * Toggle trusted proxy section enable/disable state
     * @param {boolean} isEnabled - True to enable, false to disable
     */
    function toggleTrustedProxySection(isEnabled) {
        const section = document.getElementById('trusted_proxy_config_section');
        if (!section) return;

        const input = document.getElementById('trusted_proxy_input');
        const button = document.getElementById('add_trusted_proxy_btn');
        const list = document.getElementById('trusted_proxies_list');
        
        if (isEnabled) {
            // ENABLE: Remove greyed out effect
            section.classList.remove('q-disabled');
            
            // Re-enable all form controls
            if (input) input.disabled = false;
            if (button) button.disabled = false;
            if (list) {
                list.querySelectorAll('button').forEach(btn => {
                    btn.disabled = false;
                });
            }
            
            // Restore opacity and interaction
            section.style.opacity = '1';
            section.style.pointerEvents = 'auto';
        } else {
            // DISABLE: Apply greyed out effect
            section.classList.add('q-disabled');
            
            // Disable all form controls
            if (input) input.disabled = true;
            if (button) button.disabled = true;
            if (list) {
                list.querySelectorAll('button').forEach(btn => {
                    btn.disabled = true;
                });
            }
            
            // Apply opacity reduction for visual feedback
            section.style.opacity = '0.5';
            section.style.pointerEvents = 'none';
        }
    }

</script>

