/*
    * VMP Security All Options Page Script
    * @package VMPFence
    * @since 2.2.2
    * @since 2.2.4 - Added license change modal handlers and activatePremiumLicense function refactor, Firewall Options
    * @since 2.2.5 - Added Firewall Options, Blocking Options, Scan Options, Live Traffic Options and Audit Log options scripts, WAF rules manual sync handler
*/

jQuery(document).ready(function($) {
    // Display deactivation notifications using toast system
    if (typeof vmpfenceAllOptions !== 'undefined') {
        if (vmpfenceAllOptions.deactivation_success) {
            if (typeof VMPFenceNotifications !== 'undefined') {
                VMPFenceNotifications.showToast(
                    'Your site has been successfully reset to a free license.',
                    'success',
                    5000,
                    'License Reset Complete'
                );
            }
            // Clean URL to remove success parameter
            if (window.history && window.history.replaceState) {
                var url = new URL(window.location);
                url.searchParams.delete('license_deactivated');
                url.searchParams.delete('cache_bust');
                window.history.replaceState({}, document.title, url);
            }
        }
        
        if (vmpfenceAllOptions.deactivation_error) {
            if (typeof VMPFenceNotifications !== 'undefined') {
                var errorMsg = vmpfenceAllOptions.error_message || 'License deactivation failed. Please try again.';
                VMPFenceNotifications.showToast(
                    errorMsg,
                    'error',
                    7000,
                    'Deactivation Failed'
                );
            }
            // Clean URL to remove error parameter
            if (window.history && window.history.replaceState) {
                var url = new URL(window.location);
                url.searchParams.delete('deactivation_error');
                url.searchParams.delete('cache_bust');
                window.history.replaceState({}, document.title, url);
            }
        }
        

    }
    
    // Handle license deactivation form submission
    $('#vmpfence-deactivate-form').on('submit', function(e) {
        var $form = $(this);
        var $submitBtn = $form.find('button[type="submit"]');
        
        // Disable button and show loading state
        $submitBtn.prop('disabled', true)
            .css('opacity', '0.6')
            .html('<span style="display: inline-block; margin-right: 8px;">⏳</span>Resetting license...');
        
        // Re-enable after 10 seconds as fallback (in case redirect fails)
        setTimeout(function() {
            $submitBtn.prop('disabled', false)
                .css('opacity', '1')
                .text('Reset site to a free license');
        }, 10000);
        
        // Let form submit naturally
        return true;
    });
    
    // Legacy handler for any other forms with deactivate button (keep for compatibility)
    $('form').on('submit', function(e) {
        var $form = $(this);
        var $deactivateBtn = $form.find('button[name="deactivate_license"]');
        
        if ($deactivateBtn.length > 0 && $form.attr('id') !== 'vmpfence-deactivate-form') {            
            // Disable button and show loading state
            $deactivateBtn.prop('disabled', true)
                .css('opacity', '0.6')
                .html('<span style="display: inline-block; margin-right: 8px;">⏳</span>Resetting license...');
            
            // Re-enable after 10 seconds as fallback
            setTimeout(function() {
                $deactivateBtn.prop('disabled', false)
                    .css('opacity', '1')
                    .text('Reset site to a free license');
            }, 10000);
            
            return true;
        }
    });
    
    // Search functionality
    var searchTimeout;
    var searchFieldActive = false;
    
    $('#vmpfence-options-search').on('focus click', function() {
        searchFieldActive = true;
        var searchTerm = $(this).val().toLowerCase();
        var $message = $('.vmpfence-search-message');
        
        if (searchTerm.length < 2) {
            $message.show();
        }
    });
    
    $('#vmpfence-options-search').on('blur', function() {
        var searchTerm = $(this).val().toLowerCase();
        if (searchTerm.length === 0) {
            searchFieldActive = false;
            $('.vmpfence-search-message').hide();
        }
    });
    
    $('#vmpfence-options-search').on('input', function() {
        clearTimeout(searchTimeout);
        var searchTerm = $(this).val().toLowerCase();
        var $message = $('.vmpfence-search-message');
        
        if (searchFieldActive) {
            if (searchTerm.length > 0 && searchTerm.length < 2) {
                $message.show();
            } else {
                $message.hide();
            }
        }
        
        if (searchTerm.length >= 2) {
            searchTimeout = setTimeout(function() {
                filterOptions(searchTerm);
            }, 300);
        } else if (searchTerm.length === 0) {
            // Show all sections
            $('.all-options-section').show();
            $('.vmpfence-accordion-item').show();
        }
    });
    
    function filterOptions(searchTerm) {
        $('.all-options-section').each(function() {
            var $section = $(this);
            var hasVisibleItems = false;
            
            $section.find('.vmpfence-accordion-item').each(function() {
                var $item = $(this);
                var headerText = $item.find('.vmpfence-accordion-header').text().toLowerCase();
                var contentText = $item.find('.vmpfence-accordion-content').text().toLowerCase();
                
                if (headerText.indexOf(searchTerm) !== -1 || contentText.indexOf(searchTerm) !== -1) {
                    $item.show();
                    hasVisibleItems = true;
                } else {
                    $item.hide();
                }
            });
            
            if (hasVisibleItems) {
                $section.show();
            } else {
                $section.hide();
            }
        });
    }
    
    // Restore Defaults button
    $('.vmpfence-btn-restore').on('click', function() {
        if (confirm('Are you sure you want to restore all options to their default values? This action cannot be undone.')) {
            // TODO: Implement restore defaults functionality
            alert('Restore defaults functionality to be implemented');
        }
    });
    
    // Cancel Changes button
    $('.vmpfence-btn-cancel').on('click', function() {
        location.reload();
    });
    
    // Toggle button group handler (for Real-Time IP Blocklist etc.)
    $(document).on('click', '.vmpfence-accordion-content .vmpfence-toggle-btn', function() {
        var $btn = $(this);
        var $group = $btn.closest('.vmpfence-btn-group');
        var $hidden = $group.find('input[type="hidden"]');
        var val = $btn.data('value');
        
        // Remove active from all buttons in group
        $group.find('.vmpfence-toggle-btn').removeClass('vmpfence-toggle-btn-active');
        // Add active to clicked
        $btn.addClass('vmpfence-toggle-btn-active');
        // Update hidden input value (on/off mapped to 1/0, others passed through)
        if (val === 'on' || val === 'off') {
            $hidden.val(val === 'on' ? '1' : '0');
        } else {
            $hidden.val(val);
        }
    });

    // Live Traffic mode button handler
    $(document).on('click', '.vmpfence-ao-lt-mode-btn', function() {
        var $btn = $(this);
        var $group = $btn.closest('.vmpfence-ao-lt-btn-group');
        $group.find('.vmpfence-ao-lt-mode-btn').removeClass('active');
        $btn.addClass('active');
        $btn.closest('.vmpfence-ao-lt-control').find('input[type="hidden"]').val($btn.data('value'));
    });

    // Audit Log mode button handler
    $(document).on('click', '.vmpfence-ao-al-toggle-btn', function() {
        var $btn = $(this);
        var $group = $btn.closest('.vmpfence-ao-al-toggle-group');
        $group.find('.vmpfence-ao-al-toggle-btn').removeClass('active');
        $btn.addClass('active');
        $btn.closest('.vmpfence-ao-al-row').find('input[type="hidden"]').val($btn.data('value'));
    });
    
    // === Allowlisted URLs Section ===
    (function() {
        var $table = $('.vmpfence-ao-allowlist-table');
        if (!$table.length) return;

        function getNonce() {
            return $('#ao_vmpfence_allowlist_nonce').val();
        }

        function formatParamDisplay(paramName, paramType) {
            var prefix = 'request.body';
            switch(paramType) {
                case 'POST Body': prefix = 'request.body'; break;
                case 'Query String': prefix = 'request.queryString'; break;
                case 'Cookie': prefix = 'request.cookie'; break;
                case 'File Name': prefix = 'request.fileNames'; break;
                case 'Header': prefix = 'request.headers'; break;
            }
            return prefix + '[' + paramName + ']';
        }

        function populateTable(data) {
            var $tbody = $table.find('tbody');
            $tbody.empty();
            if (!data || data.length === 0) {
                $tbody.append('<tr><td colspan="8" style="text-align: center; padding: 20px; color: #666;">No allowlisted parameters yet.</td></tr>');
                return;
            }
            $.each(data, function(i, entry) {
                var ts = new Date(entry.metadata.timestamp * 1000);
                var date = ts.toLocaleString();
                var disabled = entry.metadata.disabled ? '' : 'checked';
                var paramType = entry.metadata.param_type || 'POST Body';
                var displayParam = formatParamDisplay(entry.param_key, paramType);
                var row = '<tr data-path="' + entry.path + '" data-param="' + entry.param_key + '" data-rule="' + entry.rule_id + '">' +
                    '<td><input type="checkbox" class="vmpfence-ao-row-select"></td>' +
                    '<td><input type="checkbox" ' + disabled + ' class="vmpfence-ao-enabled-toggle"></td>' +
                    '<td>' + entry.path + '</td>' +
                    '<td>' + displayParam + '</td>' +
                    '<td>' + date + '</td>' +
                    '<td>' + entry.metadata.source + '</td>' +
                    '<td>' + (entry.metadata.user || '-') + '</td>' +
                    '<td>' + (entry.metadata.ip || '-') + '</td>' +
                    '</tr>';
                $tbody.append(row);
            });
        }

        // Stored full data for filtering
        var allData = [];

        function loadTable() {
            $.ajax({
                url: vmpfenceAllOptions.ajax_url,
                type: 'POST',
                data: { action: 'vmpfence_get_allowlist_data', nonce: getNonce() },
                success: function(resp) {
                    if (resp.success) {
                        allData = resp.data.data;
                        populateTable(allData);
                    }
                },
                error: function() { console.error('Failed to load allowlist data'); }
            });
        }
        loadTable();

        // ADD
        $('.vmpfence-ao-btn-add').on('click', function() {
            var path = $('#ao_allowlist_url').val().trim();
            var paramType = $('#ao_allowlist_param_type').val();
            var paramName = $('#ao_allowlist_param_name').val().trim();
            if (!path || !paramName) {
                if (typeof VMPFenceNotifications !== 'undefined') VMPFenceNotifications.showError('Please fill in all required fields', 3000);
                return;
            }
            $.ajax({
                url: vmpfenceAllOptions.ajax_url,
                type: 'POST',
                data: { action: 'vmpfence_add_param_allowlist', nonce: getNonce(), path: path, param_key: paramName, param_type: paramType, rule_id: 'all' },
                success: function(resp) {
                    if (resp.success) {
                        if (typeof VMPFenceNotifications !== 'undefined') VMPFenceNotifications.showSuccess(resp.data.message, 3000);
                        allData = resp.data.data;
                        populateTable(allData);
                        $('#ao_allowlist_url').val('');
                        $('#ao_allowlist_param_name').val('');
                    } else {
                        if (typeof VMPFenceNotifications !== 'undefined') VMPFenceNotifications.showError(resp.data.message || 'Failed to add entry', 4000);
                    }
                },
                error: function(x, s, e) {
                    if (typeof VMPFenceNotifications !== 'undefined') VMPFenceNotifications.showError('Failed: ' + e, 4000);
                }
            });
        });

        // DELETE
        $('.vmpfence-ao-btn-delete').on('click', function() {
            var $sel = $('.vmpfence-ao-row-select:checked');
            if (!$sel.length) { VMPFenceNotifications.showError('Please select entries to delete', 3000); return; }
            var entries = [];
            $sel.each(function() {
                var $r = $(this).closest('tr');
                entries.push({ path: $r.data('path'), param: $r.data('param'), rule: $r.data('rule') });
            });
            var del = function(i) {
                if (i >= entries.length) { VMPFenceNotifications.showSuccess('Selected entries deleted', 3000); loadTable(); return; }
                $.ajax({
                    url: vmpfenceAllOptions.ajax_url, type: 'POST',
                    data: { action: 'vmpfence_remove_param_allowlist', nonce: getNonce(), path: entries[i].path, param_key: entries[i].param, rule_id: entries[i].rule },
                    complete: function() { del(i + 1); }
                });
            };
            del(0);
        });

        // ENABLE
        $('.vmpfence-ao-btn-enable').on('click', function() {
            var $sel = $('.vmpfence-ao-row-select:checked');
            if (!$sel.length) { VMPFenceNotifications.showError('Please select entries to enable', 3000); return; }
            var entries = [];
            $sel.each(function() {
                var $r = $(this).closest('tr');
                var $cb = $r.find('.vmpfence-ao-enabled-toggle');
                if (!$cb.prop('checked')) entries.push({ path: $r.data('path'), param: $r.data('param'), rule: $r.data('rule'), cb: $cb });
            });
            if (!entries.length) { VMPFenceNotifications.showInfo('All selected entries are already enabled', 3000); return; }
            var en = function(i) {
                if (i >= entries.length) { VMPFenceNotifications.showSuccess('Selected entries enabled', 3000); return; }
                $.ajax({
                    url: vmpfenceAllOptions.ajax_url, type: 'POST',
                    data: { action: 'vmpfence_toggle_param_allowlist', nonce: getNonce(), path: entries[i].path, param_key: entries[i].param, rule_id: entries[i].rule },
                    success: function() { entries[i].cb.prop('checked', true); en(i + 1); },
                    error: function() { en(i + 1); }
                });
            };
            en(0);
        });

        // DISABLE
        $('.vmpfence-ao-btn-disable').on('click', function() {
            var $sel = $('.vmpfence-ao-row-select:checked');
            if (!$sel.length) { VMPFenceNotifications.showError('Please select entries to disable', 3000); return; }
            var entries = [];
            $sel.each(function() {
                var $r = $(this).closest('tr');
                var $cb = $r.find('.vmpfence-ao-enabled-toggle');
                if ($cb.prop('checked')) entries.push({ path: $r.data('path'), param: $r.data('param'), rule: $r.data('rule'), cb: $cb });
            });
            if (!entries.length) { VMPFenceNotifications.showInfo('All selected entries are already disabled', 3000); return; }
            var dis = function(i) {
                if (i >= entries.length) { VMPFenceNotifications.showSuccess('Selected entries disabled', 3000); return; }
                $.ajax({
                    url: vmpfenceAllOptions.ajax_url, type: 'POST',
                    data: { action: 'vmpfence_toggle_param_allowlist', nonce: getNonce(), path: entries[i].path, param_key: entries[i].param, rule_id: entries[i].rule },
                    success: function() { entries[i].cb.prop('checked', false); dis(i + 1); },
                    error: function() { dis(i + 1); }
                });
            };
            dis(0);
        });

        // TOGGLE individual
        $(document).on('change', '.vmpfence-ao-enabled-toggle', function() {
            var $cb = $(this), $r = $cb.closest('tr');
            $.ajax({
                url: vmpfenceAllOptions.ajax_url, type: 'POST',
                data: { action: 'vmpfence_toggle_param_allowlist', nonce: getNonce(), path: $r.data('path'), param_key: $r.data('param'), rule_id: $r.data('rule') },
                success: function(resp) {
                    if (resp.success) { VMPFenceNotifications.showSuccess(resp.data.message, 3000); }
                    else { $cb.prop('checked', !$cb.prop('checked')); VMPFenceNotifications.showError(resp.data.message, 4000); }
                },
                error: function() { $cb.prop('checked', !$cb.prop('checked')); VMPFenceNotifications.showError('Failed to toggle entry', 4000); }
            });
        });

        // SELECT ALL
        $('.vmpfence-ao-select-all').on('change', function() {
            $('.vmpfence-ao-row-select').prop('checked', $(this).prop('checked'));
        });

        // FILTER - "Filter By:" prefix logic
        (function() {
            var $sel = $('#ao_allowlist_filter_type');
            function addPrefix() {
                var $opt = $sel.find('option:selected');
                if ($opt.text().indexOf('Filter By: ') !== 0) {
                    $opt.text('Filter By: ' + $opt.text());
                }
            }
            function removePrefix() {
                $sel.find('option').each(function() {
                    $(this).text($(this).text().replace('Filter By: ', ''));
                });
            }
            $sel.on('focus mousedown', removePrefix);
            $sel.on('change blur', function() { removePrefix(); addPrefix(); });
            addPrefix(); // init
        })();

        // FILTER
        $('.vmpfence-ao-btn-filter').on('click', function() {
            var filterType = $('#ao_allowlist_filter_type').val();
            var filterVal = $('#ao_allowlist_filter_value').val().trim().toLowerCase();
            if (!filterType || !filterVal) { populateTable(allData); return; }
            var filtered = $.grep(allData, function(entry) {
                switch(filterType) {
                    case 'url': return entry.path.toLowerCase().indexOf(filterVal) !== -1;
                    case 'param': return entry.param_key.toLowerCase().indexOf(filterVal) !== -1;
                    case 'source': return (entry.metadata.source || '').toLowerCase().indexOf(filterVal) !== -1;
                    case 'user': return (entry.metadata.user || '').toLowerCase().indexOf(filterVal) !== -1;
                    case 'ip': return (entry.metadata.ip || '').toLowerCase().indexOf(filterVal) !== -1;
                    default: return true;
                }
            });
            populateTable(filtered);
        });
    })();

    // Rate Limiting: show/hide throttle behavior & delay options
    function checkThrottleOptionsVisibility() {
        var hasThrottle = false;
        $('#vmpfence_rl_global_action, #vmpfence_rl_crawler_action, #vmpfence_rl_crawler_404_action, #vmpfence_rl_human_action, #vmpfence_rl_human_404_action').each(function() {
            if ($(this).val() === 'throttle') {
                hasThrottle = true;
            }
        });
        if (hasThrottle) {
            $('#vmpfence_throttle_behavior_option').show();
            checkThrottleDelayVisibility();
        } else {
            $('#vmpfence_throttle_behavior_option').hide();
            $('#vmpfence_throttle_delay_option').hide();
        }
    }
    function checkThrottleDelayVisibility() {
        if ($('#vmpfence_rl_throttle_behavior').val() === 'slow_down') {
            $('#vmpfence_throttle_delay_option').show();
        } else {
            $('#vmpfence_throttle_delay_option').hide();
        }
    }
    // Bind change events
    $(document).on('change', '#vmpfence_rl_global_action, #vmpfence_rl_crawler_action, #vmpfence_rl_crawler_404_action, #vmpfence_rl_human_action, #vmpfence_rl_human_404_action', function() {
        checkThrottleOptionsVisibility();
    });
    $(document).on('change', '#vmpfence_rl_throttle_behavior', function() {
        checkThrottleDelayVisibility();
    });
    // Run on page load
    checkThrottleOptionsVisibility();

    // Country Blocking: show/hide redirect URL row based on action select
    $(document).on('change', '#vmpfence_cb_action', function() {
        if ($(this).val() === 'redirect') {
            $('#vmpfence_cb_redirect_row').show();
        } else {
            $('#vmpfence_cb_redirect_row').hide();
        }
    });

    // Scan Scheduling: Toggle ENABLED/DISABLED buttons
    $(document).on('click', '#vmpfence_so_sched_enabled ~ .vmpfence-toggle-btn', function() {
        var $hidden = $('#vmpfence_so_sched_enabled');
        var val = $(this).data('value');
        $hidden.siblings('.vmpfence-toggle-btn').removeClass('vmpfence-toggle-btn-active');
        $(this).addClass('vmpfence-toggle-btn-active');
        $hidden.val(val === 'on' ? '1' : '0');
    });

    // Scan Scheduling: show/hide manual rows based on mode radio
    $(document).on('change', 'input[name="vmpfence_so_sched_mode"]', function() {
        if ($(this).val() === 'manual') {
            $('.vmpfence-so-manual-row').show();
        } else {
            $('.vmpfence-so-manual-row').hide();
        }
    });

    // Basic Scan Type: click card to select (radio-like behavior with checkboxes)
    $(document).on('change', 'input[name="vmpfence_so_scan_type"]', function() {
        // Uncheck all others and remove selected class
        $('input[name="vmpfence_so_scan_type"]').not(this).prop('checked', false);
        $('.vmpfence-ao-scan-type-card').removeClass('vmpfence-ao-scan-type-selected');
        // Highlight the selected card
        $(this).closest('.vmpfence-ao-scan-type-card').addClass('vmpfence-ao-scan-type-selected');
    });

    // Basic Scan Type: clicking the card itself selects it
    $(document).on('click', '.vmpfence-ao-scan-type-card', function(e) {
        if ($(e.target).is('input[type="checkbox"]')) return; // let native handler fire
        var $cb = $(this).find('input[name="vmpfence_so_scan_type"]');
        if ($cb.css('display') === 'none') return; // don't allow clicking Custom card
        $cb.prop('checked', true).trigger('change');
    });

    // General Options: changing any checkbox auto-selects "Custom" scan type
    $(document).on('change', '.vmpfence-ao-general-options-list input[type="checkbox"]', function() {
        // Auto-select Custom scan type card
        $('input[name="vmpfence_so_scan_type"]').prop('checked', false);
        $('.vmpfence-ao-scan-type-card').removeClass('vmpfence-ao-scan-type-selected');
        var $customCb = $('#vmpfence_so_scan_custom');
        $customCb.prop('checked', true);
        $customCb.closest('.vmpfence-ao-scan-type-card').addClass('vmpfence-ao-scan-type-selected');
    });

    // WAF Category Toggle tracking for Advanced Firewall Options
    window.aoCategoryChanges = {};
    window.aoOriginalCategoryStates = {};
    $('.ao-category-toggle-checkbox').each(function() {
        var category = $(this).data('category');
        var enabled = parseInt($(this).data('enabled'));
        var total = parseInt($(this).data('total'));
        window.aoOriginalCategoryStates[category] = (enabled === total && total > 0) ? 1 : 0;
    });
    
    $(document).on('change', '.ao-category-toggle-checkbox', function() {
        var $cb = $(this);
        var category = $cb.data('category');
        var dbCategories = $cb.data('db-categories');
        var isEnabled = $cb.is(':checked') ? 1 : 0;
        var originalState = window.aoOriginalCategoryStates[category];
        var $row = $cb.closest('tr');
        
        if (isEnabled !== originalState) {
            window.aoCategoryChanges[category] = {
                enabled: isEnabled,
                db_categories: dbCategories
            };
            $row.css({ 'background-color': '#fff3cd', 'border-left': '3px solid #f0b849' });
        } else {
            delete window.aoCategoryChanges[category];
            $row.css({ 'background-color': '', 'border-left': '' });
        }
    });
    
    // Manually Refresh WAF Rules button - with toast notifications and sync state
    $('#vmpfence-ao-sync-waf-rules').on('click', function() {
        var $btn = $(this);
        var $status = $('#vmpfence-ao-sync-status');
        var nonce = $btn.data('nonce');
        var originalText = $btn.text();
        
        // Show confirmation modal if available, otherwise proceed directly
        var doSync = function() {
            // Show loading toast
            var loadingToast = null;
            if (typeof VMPFenceNotifications !== 'undefined') {
                loadingToast = VMPFenceNotifications.showInfo('Syncing firewall rules from API...', 0, 'Please Wait');
            }
            
            $btn.prop('disabled', true).text('\uD83D\uDD04 Syncing...');
            $status.html('<em style="color: #666;">Please wait...</em>');
            
            $.ajax({
                url: vmpfenceAllOptions.ajax_url,
                type: 'POST',
                data: { action: 'vmpfence_sync_waf_rules', nonce: nonce },
                success: function(response) {
                    // Remove loading toast
                    if (loadingToast && typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.removeToast(loadingToast);
                    }
                    
                    if (response.success) {
                        $status.html('<strong style="color: #00a32a;">\u2705 ' + response.data.message + '</strong>');
                        
                        if (typeof VMPFenceNotifications !== 'undefined') {
                            VMPFenceNotifications.showSuccess(
                                response.data.message + ' Page will reload in 2 seconds.',
                                3000,
                                'Rules Synced Successfully'
                            );
                        }
                        
                        setTimeout(function() { location.reload(); }, 2000);
                    } else {
                        $status.html('<strong style="color: #dc3232;">\u274C ' + (response.data || 'Sync failed') + '</strong>');
                        $btn.prop('disabled', false).text(originalText);
                        
                        if (typeof VMPFenceNotifications !== 'undefined') {
                            VMPFenceNotifications.showError(
                                response.data || 'Failed to sync firewall rules',
                                5000,
                                'Sync Failed'
                            );
                        }
                    }
                },
                error: function(xhr, status, error) {
                    // Remove loading toast
                    if (loadingToast && typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.removeToast(loadingToast);
                    }
                    
                    $status.html('<strong style="color: #dc3232;">\u274C AJAX error occurred</strong>');
                    $btn.prop('disabled', false).text(originalText);
                    
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showError(
                            'Network error: ' + (error || 'Connection failed'),
                            6000,
                            'Request Failed'
                        );
                    }
                }
            });
        };
        
        // Use confirmation modal if available
        if (typeof VMPFenceNotifications !== 'undefined' && typeof VMPFenceNotifications.showConfirmModal === 'function') {
            VMPFenceNotifications.showConfirmModal({
                title: 'Sync WAF Rules',
                message: 'This will fetch the latest firewall rules from the API.\n\nDo you want to continue?',
                confirmText: 'Yes, Sync Rules',
                cancelText: 'Cancel',
                type: 'info'
            }).then(function(confirmed) {
                if (confirmed) doSync();
            });
        } else {
            doSync();
        }
    });
    
    // Save Changes button
    $('.vmpfence-btn-save').on('click', function(e) {
        e.preventDefault();
                
        var $button = $(this);
        var originalText = $button.text();
        
        // Disable button and show loading state
        $button.prop('disabled', true).text('SAVING...');
        
        // Collect all checkbox values
        var formData = {
            action: 'vmpfence_save_all_options',
            nonce: vmpfenceAllOptions.nonce
        };
        
        // Add View Customization checkboxes
        if ($('input[name="display_all_options_menu"]').is(':checked')) {
            formData.display_all_options_menu = '1';
        }
        if ($('input[name="display_blocking_menu"]').is(':checked')) {
            formData.display_blocking_menu = '1';
        }
        if ($('input[name="display_live_traffic_menu"]').is(':checked')) {
            formData.display_live_traffic_menu = '1';
        }
        if ($('input[name="display_audit_log_menu"]').is(':checked')) {
            formData.display_audit_log_menu = '1';
        }
        
        // Add General Options checkboxes
        if ($('#vmpfence_auto_update').is(':checked')) {
            formData.vmpfence_auto_update = '1';
        }
        
        // Add alert email
        var alertEmail = $('#vmpfence_alert_email').val();
        if (alertEmail) {
            formData.vmpfence_alert_email = alertEmail;
        }
        
        // Add IP detection method
        var ipMethod = $('input[name="vmpfence_ip_method"]:checked').val();
        if (ipMethod) {
            formData.vmpfence_ip_method = ipMethod;
        } else {
            console.warn('No IP detection method selected');
        }
        
        // Add trusted proxies
        var trustedProxies = $('#vmpfence_trusted_proxies').val();
        if (trustedProxies) {
            formData.vmpfence_trusted_proxies = trustedProxies;
        }
        
        // Add trusted proxy preset
        var trustedProxyPreset = $('#vmpfence_trusted_proxy_preset').val();
        if (trustedProxyPreset) {
            formData.vmpfence_trusted_proxy_preset = trustedProxyPreset;
        }
        
        // Add Hide WordPress Version
        if ($('#vmpfence_hide_wp_version').is(':checked')) {
            formData.vmpfence_hide_wp_version = '1';
        }
        
        // Add Pause Live Updates
        if ($('#vmpfence_pause_live_updates').is(':checked')) {
            formData.vmpfence_pause_live_updates = '1';
        }
        
        // Add Enable Deactivation Choice
        if ($('#vmpfence_enable_deactivation_choice').is(':checked')) {
            formData.vmpfence_enable_deactivation_choice = '1';
        }
        
        // Add Update Interval
        var updateInterval = $('#vmpfence_update_interval').val();
        if (updateInterval) {
            formData.vmpfence_update_interval = updateInterval;
        }
        
        // Add Dashboard Notification Options
        if ($('#vmpfence_notify_updates_needed').is(':checked')) {
            formData.vmpfence_notify_updates_needed = '1';
        }
        if ($('#vmpfence_notify_scan_status').is(':checked')) {
            formData.vmpfence_notify_scan_status = '1';
        }
        if ($('#vmpfence_notify_security_alerts').is(':checked')) {
            formData.vmpfence_notify_security_alerts = '1';
        }
        if ($('#vmpfence_notify_promotions').is(':checked')) {
            formData.vmpfence_notify_promotions = '1';
        }
        if ($('#vmpfence_notify_blog_highlights').is(':checked')) {
            formData.vmpfence_notify_blog_highlights = '1';
        }
        if ($('#vmpfence_notify_product_updates').is(':checked')) {
            formData.vmpfence_notify_product_updates = '1';
        }
        
        // Add Email Alert Preferences
        if ($('#vmpfence_alert_on_auto_update').is(':checked')) {
            formData.vmpfence_alert_on_auto_update = '1';
        }
        if ($('#vmpfence_alert_on_deactivation').is(':checked')) {
            formData.vmpfence_alert_on_deactivation = '1';
        }
        if ($('#vmpfence_alert_on_waf_disabled').is(':checked')) {
            formData.vmpfence_alert_on_waf_disabled = '1';
        }
        if ($('#vmpfence_alert_on_scan_results').is(':checked')) {
            formData.vmpfence_alert_on_scan_results = '1';
        }
        var alertScanSeverity = $('#vmpfence_alert_scan_severity').val();
        if (alertScanSeverity) {
            formData.vmpfence_alert_scan_severity = alertScanSeverity;
        }
        if ($('#vmpfence_alert_on_ip_blocked').is(':checked')) {
            formData.vmpfence_alert_on_ip_blocked = '1';
        }
        if ($('#vmpfence_alert_on_lockout').is(':checked')) {
            formData.vmpfence_alert_on_lockout = '1';
        }
        if ($('#vmpfence_alert_on_breached_password').is(':checked')) {
            formData.vmpfence_alert_on_breached_password = '1';
        }
        if ($('#vmpfence_alert_on_lost_password').is(':checked')) {
            formData.vmpfence_alert_on_lost_password = '1';
        }
        if ($('#vmpfence_alert_on_admin_login').is(':checked')) {
            formData.vmpfence_alert_on_admin_login = '1';
        }
        if ($('#vmpfence_alert_admin_login_new_device').is(':checked')) {
            formData.vmpfence_alert_admin_login_new_device = '1';
        }
        if ($('#vmpfence_alert_on_user_login').is(':checked')) {
            formData.vmpfence_alert_on_user_login = '1';
        }
        if ($('#vmpfence_alert_user_login_new_device').is(':checked')) {
            formData.vmpfence_alert_user_login_new_device = '1';
        }
        if ($('#vmpfence_alert_on_attack_increase').is(':checked')) {
            formData.vmpfence_alert_on_attack_increase = '1';
        }
        var maxEmailAlerts = $('#vmpfence_max_email_alerts_per_hour').val();
        if (maxEmailAlerts !== undefined) {
            formData.vmpfence_max_email_alerts_per_hour = maxEmailAlerts;
        }
        
        // Add Activity Report Options
        if ($('#vmpfence_enable_email_summary').is(':checked')) {
            formData.vmpfence_enable_email_summary = '1';
        }
        var emailSummaryFrequency = $('#vmpfence_email_summary_frequency').val();
        if (emailSummaryFrequency) {
            formData.vmpfence_email_summary_frequency = emailSummaryFrequency;
        }
        var excludeDirectories = $('#vmpfence_exclude_directories').val();
        if (excludeDirectories !== undefined) {
            formData.vmpfence_exclude_directories = excludeDirectories;
        }
        if ($('#vmpfence_enable_activity_widget').is(':checked')) {
            formData.vmpfence_enable_activity_widget = '1';
        }
        
        // === Basic Firewall Options ===
        var wafEnabled = $('#vmpfence_waf_enabled').val();
        if (wafEnabled !== undefined) {
            formData.vmpfence_waf_enabled = wafEnabled;
        }
        var realtimeBlocklist = $('#vmpfence_realtime_ip_blocklist').val();
        if (realtimeBlocklist !== undefined) {
            formData.vmpfence_realtime_ip_blocklist = realtimeBlocklist;
        }
        
        // === Advanced Firewall Options ===
        var whitelistedIps = $('#vmpfence_whitelisted_ips_bypass').val();
        if (whitelistedIps !== undefined) {
            formData.vmpfence_whitelisted_ips_bypass = whitelistedIps;
        }
        var blockedUrls = $('#vmpfence_blocked_urls').val();
        if (blockedUrls !== undefined) {
            formData.vmpfence_blocked_urls = blockedUrls;
        }
        // Collect allowlisted services
        var services = {};
        var serviceIds = ['sucuri', 'facebook', 'uptime', 'statuscake', 'managewp', 'seznam', 'google'];
        $.each(serviceIds, function(i, svc) {
            services[svc] = $('#vmpfence_service_' + svc).is(':checked');
        });
        formData.vmpfence_whitelisted_services = JSON.stringify(services);
        
        // Collect WAF category toggle changes
        if (window.aoCategoryChanges && Object.keys(window.aoCategoryChanges).length > 0) {
            formData.vmpfence_category_toggles = JSON.stringify(window.aoCategoryChanges);
        }
        
        // === Brute Force Protection ===
        var bfEnabled = $('#vmpfence_bf_enabled').val();
        if (bfEnabled !== undefined) {
            formData.vmpfence_bf_enabled = bfEnabled;
        }
        var bfMaxLogin = $('#vmpfence_bf_max_login').val();
        if (bfMaxLogin) {
            formData.vmpfence_bf_max_login = bfMaxLogin;
        }
        var bfMaxForgot = $('#vmpfence_bf_max_forgot').val();
        if (bfMaxForgot) {
            formData.vmpfence_bf_max_forgot = bfMaxForgot;
        }
        var bfFailuresWindow = $('#vmpfence_bf_failures_window').val();
        if (bfFailuresWindow) {
            formData.vmpfence_bf_failures_window = bfFailuresWindow;
        }
        var bfLockoutDuration = $('#vmpfence_bf_lockout_duration').val();
        if (bfLockoutDuration) {
            formData.vmpfence_bf_lockout_duration = bfLockoutDuration;
        }
        if ($('#vmpfence_bf_lock_invalid').is(':checked')) {
            formData.vmpfence_bf_lock_invalid = '1';
        }
        var bfBlockedUsernames = $('#vmpfence_bf_blocked_usernames').val();
        if (bfBlockedUsernames !== undefined) {
            formData.vmpfence_bf_blocked_usernames = bfBlockedUsernames;
        }
        if ($('#vmpfence_bf_enforce_strong').is(':checked')) {
            formData.vmpfence_bf_enforce_strong = '1';
        }
        var bfStrongScope = $('#vmpfence_bf_strong_scope').val();
        if (bfStrongScope) {
            formData.vmpfence_bf_strong_scope = bfStrongScope;
        }
        if ($('#vmpfence_bf_dont_reveal').is(':checked')) {
            formData.vmpfence_bf_dont_reveal = '1';
        }
        if ($('#vmpfence_bf_prevent_admin').is(':checked')) {
            formData.vmpfence_bf_prevent_admin = '1';
        }
        if ($('#vmpfence_bf_prevent_discovery').is(':checked')) {
            formData.vmpfence_bf_prevent_discovery = '1';
        }
        if ($('#vmpfence_bf_disable_app_pw').is(':checked')) {
            formData.vmpfence_bf_disable_app_pw = '1';
        }
        if ($('#vmpfence_bf_block_post').is(':checked')) {
            formData.vmpfence_bf_block_post = '1';
        }
        var bfCustomBlockText = $('#vmpfence_bf_custom_block_text').val();
        if (bfCustomBlockText !== undefined) {
            formData.vmpfence_bf_custom_block_text = bfCustomBlockText;
        }
        if ($('#vmpfence_bf_check_pw_strength').is(':checked')) {
            formData.vmpfence_bf_check_pw_strength = '1';
        }
        if ($('#vmpfence_bf_participate_network').is(':checked')) {
            formData.vmpfence_bf_participate_network = '1';
        }
        
        // === Rate Limiting ===
        var rlEnabled = $('#vmpfence_rl_enabled').val();
        if (rlEnabled !== undefined) {
            formData.vmpfence_rl_enabled = rlEnabled;
        }
        var rlGoogleCrawler = $('#vmpfence_rl_google_crawler').val();
        if (rlGoogleCrawler) {
            formData.vmpfence_rl_google_crawler = rlGoogleCrawler;
        }
        var rlGlobalLimit = $('#vmpfence_rl_global_limit').val();
        if (rlGlobalLimit) {
            formData.vmpfence_rl_global_limit = rlGlobalLimit;
        }
        var rlGlobalAction = $('#vmpfence_rl_global_action').val();
        if (rlGlobalAction) {
            formData.vmpfence_rl_global_action = rlGlobalAction;
        }
        var rlCrawlerLimit = $('#vmpfence_rl_crawler_limit').val();
        if (rlCrawlerLimit) {
            formData.vmpfence_rl_crawler_limit = rlCrawlerLimit;
        }
        var rlCrawlerAction = $('#vmpfence_rl_crawler_action').val();
        if (rlCrawlerAction) {
            formData.vmpfence_rl_crawler_action = rlCrawlerAction;
        }
        var rlCrawler404Limit = $('#vmpfence_rl_crawler_404_limit').val();
        if (rlCrawler404Limit) {
            formData.vmpfence_rl_crawler_404_limit = rlCrawler404Limit;
        }
        var rlCrawler404Action = $('#vmpfence_rl_crawler_404_action').val();
        if (rlCrawler404Action) {
            formData.vmpfence_rl_crawler_404_action = rlCrawler404Action;
        }
        var rlHumanLimit = $('#vmpfence_rl_human_limit').val();
        if (rlHumanLimit) {
            formData.vmpfence_rl_human_limit = rlHumanLimit;
        }
        var rlHumanAction = $('#vmpfence_rl_human_action').val();
        if (rlHumanAction) {
            formData.vmpfence_rl_human_action = rlHumanAction;
        }
        var rlHuman404Limit = $('#vmpfence_rl_human_404_limit').val();
        if (rlHuman404Limit) {
            formData.vmpfence_rl_human_404_limit = rlHuman404Limit;
        }
        var rlHuman404Action = $('#vmpfence_rl_human_404_action').val();
        if (rlHuman404Action) {
            formData.vmpfence_rl_human_404_action = rlHuman404Action;
        }
        var rlBlockDuration = $('#vmpfence_rl_block_duration').val();
        if (rlBlockDuration) {
            formData.vmpfence_rl_block_duration = rlBlockDuration;
        }
        var rlThrottleBehavior = $('#vmpfence_rl_throttle_behavior').val();
        if (rlThrottleBehavior) {
            formData.vmpfence_rl_throttle_behavior = rlThrottleBehavior;
        }
        var rlThrottleDelay = $('#vmpfence_rl_throttle_delay').val();
        if (rlThrottleDelay) {
            formData.vmpfence_rl_throttle_delay = rlThrottleDelay;
        }
        var rlAllowlisted404 = $('#vmpfence_rl_allowlisted_404').val();
        if (rlAllowlisted404 !== undefined) {
            formData.vmpfence_rl_allowlisted_404 = rlAllowlisted404;
        }

        // ── Blocking Options: Advanced Country Blocking ──
        var cbAction = $('#vmpfence_cb_action').val();
        if (cbAction) {
            formData.vmpfence_cb_action = cbAction;
        }
        var cbRedirectUrl = $('#vmpfence_cb_redirect_url').val();
        if (cbRedirectUrl !== undefined) {
            formData.vmpfence_cb_redirect_url = cbRedirectUrl;
        }
        formData.vmpfence_cb_block_logged_in = $('#vmpfence_cb_block_logged_in').is(':checked') ? 1 : 0;
        var cbBypassField = $('#vmpfence_cb_bypass_field').val();
        if (cbBypassField !== undefined) {
            formData.vmpfence_cb_bypass_field = cbBypassField;
        }
        var cbBypassValue = $('#vmpfence_cb_bypass_value').val();
        if (cbBypassValue !== undefined) {
            formData.vmpfence_cb_bypass_value = cbBypassValue;
        }
        var cbBypassCookie = $('#vmpfence_cb_bypass_cookie').val();
        if (cbBypassCookie !== undefined) {
            formData.vmpfence_cb_bypass_cookie = cbBypassCookie;
        }

        // ── Scan Options: Scan Scheduling ──
        var soSchedEnabled = $('#vmpfence_so_sched_enabled').val();
        if (soSchedEnabled !== undefined) {
            formData.vmpfence_so_sched_enabled = soSchedEnabled;
        }
        var soSchedMode = $('input[name="vmpfence_so_sched_mode"]:checked').val();
        if (soSchedMode) {
            formData.vmpfence_so_sched_mode = soSchedMode;
        }
        var soManualPattern = $('#vmpfence_so_manual_pattern').val();
        if (soManualPattern) {
            formData.vmpfence_so_manual_pattern = soManualPattern;
        }
        var soStartHour = $('#vmpfence_so_start_hour').val();
        if (soStartHour !== undefined) {
            formData.vmpfence_so_start_hour = soStartHour;
        }
        var soTimezone = $('#vmpfence_so_timezone').val();
        if (soTimezone) {
            formData.vmpfence_so_timezone = soTimezone;
        }
        formData.vmpfence_so_random_offset = $('#vmpfence_so_random_offset').is(':checked') ? '1' : '0';

        // ── Scan Options: Basic Scan Type ──
        var soScanType = $('input[name="vmpfence_so_scan_type"]:checked').val();
        if (soScanType) {
            formData.vmpfence_so_scan_type = soScanType;
        }

        // ── Scan Options: General Options ──
        var goKeys = [
            'scansEnabled_checkGSB', 'spamvertizeCheck', 'checkSpamIP',
            'scansEnabled_checkHowGetIPs', 'scansEnabled_checkReadableConfig',
            'scansEnabled_suspectedFiles', 'scansEnabled_core', 'scansEnabled_themes',
            'scansEnabled_plugins', 'scansEnabled_coreUnknown', 'scansEnabled_malware',
            'scansEnabled_fileContents', 'scansEnabled_fileContentsGSB',
            'scansEnabled_posts', 'scansEnabled_comments', 'scansEnabled_suspiciousOptions',
            'scansEnabled_oldVersions', 'scansEnabled_suspiciousAdminUsers',
            'scansEnabled_passwds', 'scansEnabled_diskSpace', 'scansEnabled_wafStatus',
            'other_scanOutside', 'scansEnabled_scanImages'
        ];
        $.each(goKeys, function(i, key) {
            formData['vmpfence_go_' + key] = $('input[name="vmpfence_go_' + key + '"]').is(':checked') ? 1 : 0;
        });

        // ── Scan Options: Performance Options ──
        formData.vmpfence_po_low_resource = $('#vmpfence_po_low_resource').is(':checked') ? 1 : 0;
        var poMaxIssues = $('#vmpfence_po_max_issues').val();
        if (poMaxIssues !== undefined) {
            formData.vmpfence_po_max_issues = poMaxIssues;
        }
        var poMaxDuration = $('#vmpfence_po_max_duration').val();
        if (poMaxDuration !== undefined) {
            formData.vmpfence_po_max_duration = poMaxDuration;
        }
        var poMaxMem = $('#vmpfence_po_max_mem').val();
        if (poMaxMem !== undefined) {
            formData.vmpfence_po_max_mem = poMaxMem;
        }
        var poMaxExecTime = $('#vmpfence_po_max_exec_time').val();
        if (poMaxExecTime !== undefined) {
            formData.vmpfence_po_max_exec_time = poMaxExecTime;
        }

        // Advanced Scan Options
        formData.vmpfence_aso_exclude = $('#vmpfence_aso_exclude').val() || '';
        formData.vmpfence_aso_include_extra = $('#vmpfence_aso_include_extra').val() || '';
        formData.vmpfence_aso_force_ipv4 = $('#vmpfence_aso_force_ipv4').is(':checked') ? 1 : 0;
        formData.vmpfence_aso_max_resume = $('#vmpfence_aso_max_resume').val() || 3;

        // Live Traffic Options
        formData.vmpfence_lt_logging_mode = $('#vmpfence_lt_logging_mode').val() || 'security_only';
        formData.vmpfence_lt_ignore_publishing = $('#vmpfence_lt_ignore_publishing').is(':checked') ? 1 : 0;
        formData.vmpfence_lt_ignore_usernames = $('#vmpfence_lt_ignore_usernames').val() || '';
        formData.vmpfence_lt_ignore_ips = $('#vmpfence_lt_ignore_ips').val() || '';
        formData.vmpfence_lt_ignore_ua = $('#vmpfence_lt_ignore_ua').val() || '';
        formData.vmpfence_lt_max_rows = $('#vmpfence_lt_max_rows').val() || 2000;
        formData.vmpfence_lt_max_days = $('#vmpfence_lt_max_days').val() || 30;

        // Audit Log Options
        formData.vmpfence_al_logging_mode = $('#vmpfence_al_logging_mode').val() || 'preview';
        formData.vmpfence_al_display_menu = $('#vmpfence_al_display_menu').is(':checked') ? 1 : 0;

        $.ajax({
            url: vmpfenceAllOptions.ajax_url,
            type: 'POST',
            data: formData,
            success: function(response) {                
                if (response.success) {
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showSuccess(response.data.message);
                    }
                    // Reload page after short delay to show notification
                    setTimeout(function() {
                        location.reload();
                    }, 800);
                } else {
                    console.error('Failed to save settings:', response.data.message);
                    $button.prop('disabled', false).text(originalText);
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showError(response.data.message || 'Failed to save settings');
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', {
                    status: status,
                    error: error,
                    response: xhr.responseText,
                    statusCode: xhr.status
                });
                
                $button.prop('disabled', false).text(originalText);
                
                if (typeof VMPFenceNotifications !== 'undefined') {
                    VMPFenceNotifications.showError('Error saving settings: ' + error);
                }
            }
        });
    });
    
    // Accordion functionality
    $('.vmpfence-accordion-header').on('click', function() {
        var $item = $(this).closest('.vmpfence-accordion-item');
        var $content = $item.find('.vmpfence-accordion-content');
        
        // Toggle active class
        $item.toggleClass('active');
        
        // Slide toggle content
        $content.slideToggle(300);
    });
    
    // Expand/Collapse All functionality
    $('#vmpfence-expand-all').on('click', function() {
        var $button = $(this);
        var $items = $('.vmpfence-accordion-item');
        var isExpanding = $button.text() === 'EXPAND ALL';
        
        if (isExpanding) {
            $items.addClass('active');
            $('.vmpfence-accordion-content').slideDown(300);
            $button.text('COLLAPSE ALL');
        } else {
            $items.removeClass('active');
            $('.vmpfence-accordion-content').slideUp(300);
            $button.text('EXPAND ALL');
        }
    });
    
    // Handle hash navigation (scroll to section)
    if (window.location.hash) {
        var hash = window.location.hash;
        var $target = $(hash);
        
        if ($target.length) {
            // If navigating to global options, automatically open the first accordion (License)
            if (hash === '#vmpfence-global-options') {
                var $firstAccordion = $target.find('.vmpfence-accordion-item').first();
                if ($firstAccordion.length && !$firstAccordion.hasClass('active')) {
                    $firstAccordion.addClass('active');
                    $firstAccordion.find('.vmpfence-accordion-content').show();
                }
            }
            
            // Scroll to the section
            setTimeout(function() {
                $('html, body').animate({
                    scrollTop: $target.offset().top - 100
                }, 500);
            }, 100);
        }
    }

    // Trusted proxies toggle under IP detection
    $(document).on('click', '.vmpfence-edit-trusted-proxies', function(e) {
        e.preventDefault();

        var $link = $(this);
        var $panel = $link.closest('.vmpfence-option-note').find('.vmpfence-trusted-proxies-panel').first();
        if (!$panel.length) {
            return;
        }

        var willShow = !$panel.is(':visible');
        $panel.stop(true, true).slideToggle(200);

        $link.attr('aria-expanded', willShow ? 'true' : 'false');
        $panel.attr('aria-hidden', willShow ? 'false' : 'true');
        $link.text(willShow ? '- Hide trusted proxies' : '+ Edit trusted proxies');
    });
    
    /* ==========================================================================
     * License Change Modal Handlers
       ========================================================================== */
    
    // Open modal when either button is clicked
    $('#vmpfence-change-license-btn-premium, #vmpfence-change-license-btn-free').on('click', function() {
        // Clear form fields from previous use
        $('#vmpfence-license-email').val('');
        $('#vmpfence-modal-license-key').val('');
        $('#vmpfence-license-error').hide();
        
        $('#vmpfence-license-change-modal').fadeIn(200);
        $('body').css('overflow', 'hidden');
    });
    
    // Close modal handlers
    $('.vmpfence-license-modal-close, .vmpfence-license-modal-overlay, #vmpfence-license-cancel-btn').on('click', function() {
        $('#vmpfence-license-change-modal').fadeOut(200);
        $('body').css('overflow', 'auto');
        
        // Reset form state
        $('#vmpfence-license-email').val('');
        $('#vmpfence-modal-license-key').val('');
        $('#vmpfence-license-error').hide();
        $('#vmpfence-license-submit-btn').prop('disabled', false).text('Activate License');
    });
    
    // Auto-uppercase license key
    $('#vmpfence-modal-license-key').on('input', function() {
        this.value = this.value.toUpperCase();
    });
    
    // Form submission
    $('#vmpfence-license-change-form').on('submit', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var $submitBtn = $('#vmpfence-license-submit-btn');
        var $errorDiv = $('#vmpfence-license-error');
        
        // Get form data
        var email = $('#vmpfence-license-email').val().trim();
        var licenseKey = $('#vmpfence-modal-license-key').val().trim();
        var emailAlerts = $('#vmpfence-email-alerts').is(':checked') ? '1' : '0';
        var nonce = $form.find('input[name=\"vmpfence_change_license_nonce\"]').val();
        
        // Client-side validation
        $errorDiv.hide();
        
        if (!email || !licenseKey) {
            $errorDiv.html('Please fill in all required fields.').show();
            return;
        }
        
        // Email validation
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            $errorDiv.html('Please enter a valid email address.').show();
            return;
        }
        
        // License key validation
        var keyRegex = /^(FREE|PREM)-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;
        if (!keyRegex.test(licenseKey)) {
            $errorDiv.html('Invalid license key format. Expected: FREE-XXXX-XXXX-XXXX or PREM-XXXX-XXXX-XXXX').show();
            return;
        }
        
        // Disable submit button and show loading
        $submitBtn.prop('disabled', true).text('Activating...');
        
        // AJAX request
        $.ajax({
            url: vmpfenceAllOptions.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_change_license',
                email: email,
                license_key: licenseKey,
                email_alerts: emailAlerts,
                nonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    // Show success toast (with fallback)
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        VMPFenceNotifications.showToast(
                            response.data.message || 'License activated successfully!',
                            'success'
                        );
                    }
                    
                    // Close modal
                    $('#vmpfence-license-change-modal').fadeOut(200);
                    $('body').css('overflow', 'auto');
                    
                    // Reload page after 1 second
                    setTimeout(function() {
                        window.location.reload();
                    }, 1000);
                } else {
                    // Check for specific error types
                    var errorMessage = response.data.message || 'License activation failed. Please try again.';
                    
                    if (response.data.error_type === 'license_already_registered') {
                        // Build detailed error message with deactivation instructions
                        errorMessage = '<strong>Premium License Already Registered</strong><br><br>' +
                            'Registered to: <code>' + $('<span>').text(response.data.registered_site).html() + '</code><br>' +
                            'Current site: <code>' + $('<span>').text(response.data.current_site).html() + '</code><br><br>' +
                            '<div style="background: #f0f0f1; padding: 10px; border-left: 4px solid #191970; margin-top: 10px;">' +
                            '<strong>To use this license here:</strong><br>' +
                            '1. Log in to your <a href="https://vmpsecurity.com/login-page/" target="_blank" style="color: #191970;">Web Portal</a><br>' +
                            '2. Click "Deactivate License" next to this license<br>' +
                            '3. Return here and activate again' +
                            '</div>';
                    }
                    
                    $errorDiv.html(errorMessage).show();
                    
                    if (typeof VMPFenceNotifications !== 'undefined') {
                        // For toast, always use plain text (no HTML) since toast renders as text
                        var toastMessage = response.data.error_type === 'license_already_registered' 
                            ? 'Premium license is already active on another site. See details below.'
                            : (response.data.message || 'License activation failed. Please try again.');
                        VMPFenceNotifications.showToast(toastMessage, 'error');
                    }
                    
                    // Re-enable submit button
                    $submitBtn.prop('disabled', false).text('Activate License');
                }
            },
            error: function(xhr, status, error) {
                var errorMessage = 'An error occurred. Please try again.';
                $errorDiv.html(errorMessage).show();
                
                if (typeof VMPFenceNotifications !== 'undefined') {
                    VMPFenceNotifications.showToast(errorMessage, 'error');
                }
                
                // Re-enable submit button
                $submitBtn.prop('disabled', false).text('Activate License');
            }
        });
    });
});

