<?php
/**
 * All Options AJAX Handler
 *
 * @package VMPFence
 * @since 2.2.2
 * @since 2.2.4 - Added Basic Firewall Ooptions, Handling JSON error response from server
 * @since 2.2.5 - Added Advanced Firewall Options, Brute Force Protection Options, Rate Limiting Options, Allowlisted URLs, Advanced Country Blocking Options, Scan Scheduling Options, Basic Scan Type Option, General Scan Options, Performance Scan Options, Advanced Scan Options, Live Traffic Options, Audit Log Options, Enhanced Audit Log integration
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * AJAX handler for saving all options
 */
function vmpfence_save_all_options_ajax() {
    // error_log('VMP All Options: AJAX save handler called');
    // error_log('VMP All Options: POST data: ' . print_r($_POST, true));
    
    check_ajax_referer('vmpfence_all_options_save', 'nonce');
    // error_log('VMP All Options: Nonce verified');
    
    if (!current_user_can('manage_options')) {
        // error_log('VMP All Options: User lacks permissions');
        wp_send_json_error(array('message' => 'Insufficient permissions'));
    }
    
    // View Customization options
    $display_all_options = isset($_POST['display_all_options_menu']) ? '1' : '0';
    $display_blocking = isset($_POST['display_blocking_menu']) ? '1' : '0';
    $display_live_traffic = isset($_POST['display_live_traffic_menu']) ? '1' : '0';
    $display_audit_log = isset($_POST['display_audit_log_menu']) ? '1' : '0';
    
    // General Options
    $auto_update = isset($_POST['vmpfence_auto_update']) ? '1' : '0';
    $hide_wp_version = isset($_POST['vmpfence_hide_wp_version']) ? '1' : '0';
    $pause_live_updates = isset($_POST['vmpfence_pause_live_updates']) ? '1' : '0';
    $enable_deactivation_choice = isset($_POST['vmpfence_enable_deactivation_choice']) ? '1' : '0';
    $update_interval = isset($_POST['vmpfence_update_interval']) ? intval($_POST['vmpfence_update_interval']) : 10;
    
    // Dashboard Notification Options
    $notify_updates = isset($_POST['vmpfence_notify_updates_needed']) ? '1' : '0';
    $notify_scan_status = isset($_POST['vmpfence_notify_scan_status']) ? '1' : '0';
    $notify_security_alerts = isset($_POST['vmpfence_notify_security_alerts']) ? '1' : '0';
    $notify_promotions = isset($_POST['vmpfence_notify_promotions']) ? '1' : '0';
    $notify_blog_highlights = isset($_POST['vmpfence_notify_blog_highlights']) ? '1' : '0';
    $notify_product_updates = isset($_POST['vmpfence_notify_product_updates']) ? '1' : '0';
    
    // Email Alert Preferences
    $alert_on_auto_update = isset($_POST['vmpfence_alert_on_auto_update']) ? '1' : '0';
    $alert_on_deactivation = isset($_POST['vmpfence_alert_on_deactivation']) ? '1' : '0';
    $alert_on_waf_disabled = isset($_POST['vmpfence_alert_on_waf_disabled']) ? '1' : '0';
    $alert_on_scan_results = isset($_POST['vmpfence_alert_on_scan_results']) ? '1' : '0';
    $alert_scan_severity = isset($_POST['vmpfence_alert_scan_severity']) ? sanitize_text_field($_POST['vmpfence_alert_scan_severity']) : 'low';
    $alert_on_ip_blocked = isset($_POST['vmpfence_alert_on_ip_blocked']) ? '1' : '0';
    $alert_on_lockout = isset($_POST['vmpfence_alert_on_lockout']) ? '1' : '0';
    $alert_on_breached_password = isset($_POST['vmpfence_alert_on_breached_password']) ? '1' : '0';
    $alert_on_lost_password = isset($_POST['vmpfence_alert_on_lost_password']) ? '1' : '0';
    $alert_on_admin_login = isset($_POST['vmpfence_alert_on_admin_login']) ? '1' : '0';
    $alert_admin_login_new_device = isset($_POST['vmpfence_alert_admin_login_new_device']) ? '1' : '0';
    $alert_on_user_login = isset($_POST['vmpfence_alert_on_user_login']) ? '1' : '0';
    $alert_user_login_new_device = isset($_POST['vmpfence_alert_user_login_new_device']) ? '1' : '0';
    $alert_on_attack_increase = isset($_POST['vmpfence_alert_on_attack_increase']) ? '1' : '0';
    $max_email_alerts_per_hour = isset($_POST['vmpfence_max_email_alerts_per_hour']) ? intval($_POST['vmpfence_max_email_alerts_per_hour']) : 0;
    
    // Activity Report Options
    $enable_email_summary = isset($_POST['vmpfence_enable_email_summary']) ? '1' : '0';
    $email_summary_frequency = isset($_POST['vmpfence_email_summary_frequency']) ? sanitize_text_field($_POST['vmpfence_email_summary_frequency']) : 'weekly';
    $exclude_directories = isset($_POST['vmpfence_exclude_directories']) ? wp_unslash($_POST['vmpfence_exclude_directories']) : '';
    $enable_activity_widget = isset($_POST['vmpfence_enable_activity_widget']) ? '1' : '0';
    
    // Get alert email - don't sanitize yet to preserve commas
    $alert_email_raw = isset($_POST['vmpfence_alert_email']) ? wp_unslash($_POST['vmpfence_alert_email']) : '';
    
    // Get IP detection method
    $ip_method = isset($_POST['vmpfence_ip_method']) ? sanitize_text_field($_POST['vmpfence_ip_method']) : 'auto';
    
    // Get trusted proxies
    $trusted_proxies = isset($_POST['vmpfence_trusted_proxies']) ? wp_unslash($_POST['vmpfence_trusted_proxies']) : '';
    
    // Get trusted proxy preset
    $trusted_proxy_preset = isset($_POST['vmpfence_trusted_proxy_preset']) ? sanitize_text_field($_POST['vmpfence_trusted_proxy_preset']) : '';
    
    // error_log('VMP All Options: Received alert email - ' . $alert_email_raw);
    // error_log('VMP All Options: Saving settings - All Options: ' . $display_all_options . ', Blocking: ' . $display_blocking . ', Live Traffic: ' . $display_live_traffic . ', Audit Log: ' . $display_audit_log);
    
    // Save options
    VMPFence_Config::set('display_all_options_menu', $display_all_options === '1' ? 1 : 0);
    VMPFence_Config::set('blocking_menu_display', $display_blocking === '1' ? 1 : 0);
    VMPFence_Config::set('display_live_traffic_menu', $display_live_traffic === '1' ? 1 : 0);
    VMPFence_Config::set('display_audit_log_menu', $display_audit_log === '1' ? 1 : 0);
    
    // Save General Options
    VMPFence_Config::set('auto_update', $auto_update === '1' ? 1 : 0);
    VMPFence_Config::set('hide_wp_version', $hide_wp_version === '1' ? 1 : 0);
    VMPFence_Config::set('pause_live_updates', $pause_live_updates === '1' ? 1 : 0);
    update_option('vmpfence_enable_deactivation_choice', $enable_deactivation_choice);
    VMPFence_Config::set('update_interval', max(1, $update_interval)); // Minimum 1 second
    
    // Save IP detection method
    $valid_methods = array('auto', 'REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CF_CONNECTING_IP');
    if (in_array($ip_method, $valid_methods)) {
        VMPFence_Config::set('ip_detection_method', $ip_method);
        // error_log('VMP All Options: IP detection method saved - ' . $ip_method);
    }
    
    // Save trusted proxies
    if (isset($_POST['vmpfence_trusted_proxies'])) {
        VMPFence_Config::set('trusted_proxies', sanitize_textarea_field($trusted_proxies));
        // error_log('VMP All Options: Trusted proxies saved');
    }
    
    // Save trusted proxy preset
    if (isset($_POST['vmpfence_trusted_proxy_preset'])) {
        // Validate preset exists
        require_once VMPFENCE_PLUGIN_DIR . 'all-options/class-proxy-presets.php';
        $valid_presets = array_keys(VMPFence_Proxy_Presets::get_presets());
        $valid_presets[] = ''; // Allow empty/none
        
        if (in_array($trusted_proxy_preset, $valid_presets)) {
            VMPFence_Config::set('trusted_proxy_preset', $trusted_proxy_preset);
            // error_log('VMP All Options: Trusted proxy preset saved - ' . ($trusted_proxy_preset ?: 'none'));
        }
    }
    
    // Save alert email (supports comma-separated emails)
    if (!empty($alert_email_raw)) {
        // Split by comma and sanitize each email individually
        $emails = array_map('trim', explode(',', $alert_email_raw));
        $valid_emails = array();
        $invalid_emails = array();
        
        foreach ($emails as $email) {
            // Sanitize individual email
            $sanitized_email = sanitize_email($email);
            if (!empty($sanitized_email) && is_email($sanitized_email)) {
                $valid_emails[] = $sanitized_email;
            } else {
                $invalid_emails[] = $email;
            }
        }
        
        if (!empty($valid_emails)) {
            // Join with comma and space
            $validated_email = implode(', ', $valid_emails);
            VMPFence_Config::set('notification_email', $validated_email);
            // error_log('VMP All Options: Alert email saved - ' . $validated_email);
            
            if (!empty($invalid_emails)) {
                // error_log('VMP All Options: Invalid emails skipped - ' . implode(', ', $invalid_emails));
            }
        } else {
            // error_log('VMP All Options: No valid emails found - ' . $alert_email_raw);
        }
    }
    
    // Save Dashboard Notification Options
    VMPFence_Config::set('notify_updates_needed', $notify_updates === '1' ? 1 : 0);
    VMPFence_Config::set('notify_scan_status', $notify_scan_status === '1' ? 1 : 0);
    VMPFence_Config::set('notify_security_alerts', $notify_security_alerts === '1' ? 1 : 0);
    VMPFence_Config::set('notify_promotions', $notify_promotions === '1' ? 1 : 0);
    VMPFence_Config::set('notify_blog_highlights', $notify_blog_highlights === '1' ? 1 : 0);
    VMPFence_Config::set('notify_product_updates', $notify_product_updates === '1' ? 1 : 0);
    
    // Save Email Alert Preferences
    VMPFence_Config::set('alert_on_auto_update', $alert_on_auto_update === '1' ? 1 : 0);
    VMPFence_Config::set('alert_on_deactivation', $alert_on_deactivation === '1' ? 1 : 0);
    VMPFence_Config::set('alert_on_waf_disabled', $alert_on_waf_disabled === '1' ? 1 : 0);
    VMPFence_Config::set('alert_on_scan_results', $alert_on_scan_results === '1' ? 1 : 0);
    
    // Validate and save alert scan severity
    $valid_severities = array('critical', 'high', 'medium', 'low');
    if (in_array($alert_scan_severity, $valid_severities)) {
        VMPFence_Config::set('alert_scan_severity', $alert_scan_severity);
    }
    
    VMPFence_Config::set('alert_on_ip_blocked', $alert_on_ip_blocked === '1' ? 1 : 0);
    VMPFence_Config::set('alert_on_lockout', $alert_on_lockout === '1' ? 1 : 0);
    VMPFence_Config::set('alert_on_breached_password', $alert_on_breached_password === '1' ? 1 : 0);
    VMPFence_Config::set('alert_on_lost_password', $alert_on_lost_password === '1' ? 1 : 0);
    VMPFence_Config::set('alert_on_admin_login', $alert_on_admin_login === '1' ? 1 : 0);
    VMPFence_Config::set('alert_admin_login_new_device', $alert_admin_login_new_device === '1' ? 1 : 0);
    VMPFence_Config::set('alert_on_user_login', $alert_on_user_login === '1' ? 1 : 0);
    VMPFence_Config::set('alert_user_login_new_device', $alert_user_login_new_device === '1' ? 1 : 0);
    VMPFence_Config::set('alert_on_attack_increase', $alert_on_attack_increase === '1' ? 1 : 0);
    VMPFence_Config::set('max_email_alerts_per_hour', max(0, $max_email_alerts_per_hour));
        // Save Activity Report Options
    VMPFence_Config::set('enable_email_summary', $enable_email_summary === '1' ? 1 : 0);
    
    // Validate and save email summary frequency
    $valid_frequencies = array('daily', 'weekly', 'monthly');
    if (in_array($email_summary_frequency, $valid_frequencies)) {
        VMPFence_Config::set('email_summary_frequency', $email_summary_frequency);
    }
    
    // Save exclude directories
    VMPFence_Config::set('exclude_directories', sanitize_textarea_field($exclude_directories));
    VMPFence_Config::set('enable_activity_widget', $enable_activity_widget === '1' ? 1 : 0);

    // === Basic Firewall Options ===
    if (isset($_POST['vmpfence_waf_enabled'])) {
        VMPFence_Config::set('waf_enabled', intval($_POST['vmpfence_waf_enabled']) ? 1 : 0);
    }
    if (isset($_POST['vmpfence_realtime_ip_blocklist'])) {
        VMPFence_Config::set('realtime_ip_blocklist_enabled', intval($_POST['vmpfence_realtime_ip_blocklist']) ? 1 : 0);
    }

    // === Advanced Firewall Options ===
    if (isset($_POST['vmpfence_whitelisted_ips_bypass'])) {
        VMPFence_Config::set('whitelisted_ips_bypass', sanitize_textarea_field(wp_unslash($_POST['vmpfence_whitelisted_ips_bypass'])));
    }
    if (isset($_POST['vmpfence_blocked_urls'])) {
        VMPFence_Config::set('blocked_urls', sanitize_textarea_field(wp_unslash($_POST['vmpfence_blocked_urls'])));
    }
    if (isset($_POST['vmpfence_whitelisted_services'])) {
        $services_raw = wp_unslash($_POST['vmpfence_whitelisted_services']);
        $services = json_decode($services_raw, true);
        if (is_array($services)) {
            $clean_services = array();
            $valid_keys = array('sucuri', 'facebook', 'uptime', 'statuscake', 'managewp', 'seznam', 'google');
            foreach ($valid_keys as $key) {
                $clean_services[$key] = !empty($services[$key]);
            }
            VMPFence_Config::set('whitelisted_services', wp_json_encode($clean_services));
        }
    }

    // === WAF Category Toggles ===
    if (isset($_POST['vmpfence_category_toggles'])) {
        $toggles_raw = wp_unslash($_POST['vmpfence_category_toggles']);
        $toggles = json_decode($toggles_raw, true);
        if (is_array($toggles) && !empty($toggles)) {
            global $wpdb;
            $rules_table = $wpdb->prefix . 'vmpfence_waf_rules';
            $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$rules_table'") === $rules_table;
            if ($table_exists) {
                foreach ($toggles as $display_category => $change_data) {
                    $enable = intval($change_data['enabled']);
                    $db_categories = isset($change_data['db_categories']) ? $change_data['db_categories'] : array($display_category);
                    foreach ($db_categories as $db_category) {
                        $db_category = sanitize_text_field($db_category);
                        $wpdb->query($wpdb->prepare(
                            "UPDATE $rules_table SET enabled = %d WHERE LOWER(category) = LOWER(%s)",
                            $enable,
                            $db_category
                        ));
                    }
                    do_action('vmpfence_waf_category_toggled', $display_category, $enable);
                }
                wp_cache_delete('vmpfence_waf_enabled_rules');
                delete_transient('vmpfence_api_waf_rules');
            }
        }
    }

    // === Brute Force Protection ===
    if (isset($_POST['vmpfence_bf_enabled'])) {
        VMPFence_Config::set('brute_force_enabled', intval($_POST['vmpfence_bf_enabled']) ? 1 : 0);
    }
    if (isset($_POST['vmpfence_bf_max_login'])) {
        VMPFence_Config::set('max_login_attempts', intval($_POST['vmpfence_bf_max_login']));
    }
    if (isset($_POST['vmpfence_bf_max_forgot'])) {
        VMPFence_Config::set('max_forgot_password_attempts', intval($_POST['vmpfence_bf_max_forgot']));
    }
    if (isset($_POST['vmpfence_bf_failures_window'])) {
        VMPFence_Config::set('count_failures_window', intval($_POST['vmpfence_bf_failures_window']));
    }
    if (isset($_POST['vmpfence_bf_lockout_duration'])) {
        VMPFence_Config::set('lockout_duration', intval($_POST['vmpfence_bf_lockout_duration']));
    }
    VMPFence_Config::set('lock_invalid_usernames', isset($_POST['vmpfence_bf_lock_invalid']) ? 1 : 0);
    if (isset($_POST['vmpfence_bf_blocked_usernames'])) {
        $raw = sanitize_textarea_field(wp_unslash($_POST['vmpfence_bf_blocked_usernames']));
        $usernames = array_filter(array_map('trim', preg_split('/[\r\n]+/', $raw)));
        VMPFence_Config::set('blocked_usernames', $usernames);
    }
    VMPFence_Config::set('enforce_strong_passwords', isset($_POST['vmpfence_bf_enforce_strong']) ? 1 : 0);
    if (isset($_POST['vmpfence_bf_strong_scope'])) {
        $scope = sanitize_text_field($_POST['vmpfence_bf_strong_scope']);
        if (in_array($scope, array('recommended', 'all'))) {
            VMPFence_Config::set('strong_passwords_scope', $scope);
        }
    }
    VMPFence_Config::set('dont_reveal_users', isset($_POST['vmpfence_bf_dont_reveal']) ? 1 : 0);
    VMPFence_Config::set('prevent_admin_username', isset($_POST['vmpfence_bf_prevent_admin']) ? 1 : 0);
    VMPFence_Config::set('prevent_username_discovery', isset($_POST['vmpfence_bf_prevent_discovery']) ? 1 : 0);
    VMPFence_Config::set('disable_app_passwords', isset($_POST['vmpfence_bf_disable_app_pw']) ? 1 : 0);
    VMPFence_Config::set('block_post_requests', isset($_POST['vmpfence_bf_block_post']) ? 1 : 0);
    if (isset($_POST['vmpfence_bf_custom_block_text'])) {
        VMPFence_Config::set('custom_block_text', sanitize_textarea_field(wp_unslash($_POST['vmpfence_bf_custom_block_text'])));
    }
    VMPFence_Config::set('check_password_strength', isset($_POST['vmpfence_bf_check_pw_strength']) ? 1 : 0);
    VMPFence_Config::set('participate_security_network', isset($_POST['vmpfence_bf_participate_network']) ? 1 : 0);

    // === Rate Limiting ===
    if (isset($_POST['vmpfence_rl_enabled'])) {
        VMPFence_Config::set('rate_limiting_enabled', intval($_POST['vmpfence_rl_enabled']) ? 1 : 0);
    }
    if (isset($_POST['vmpfence_rl_google_crawler'])) {
        $gc = sanitize_text_field($_POST['vmpfence_rl_google_crawler']);
        if (in_array($gc, array('verified_google', 'no_verification', 'treat_as_crawler'))) {
            VMPFence_Config::set('google_crawler_treatment', $gc);
        }
    }
    if (isset($_POST['vmpfence_rl_global_limit'])) {
        VMPFence_Config::set('global_rate_limit', sanitize_text_field($_POST['vmpfence_rl_global_limit']));
    }
    if (isset($_POST['vmpfence_rl_global_action'])) {
        $act = sanitize_text_field($_POST['vmpfence_rl_global_action']);
        if (in_array($act, array('throttle', 'block'))) {
            VMPFence_Config::set('global_rate_action', $act);
        }
    }
    if (isset($_POST['vmpfence_rl_crawler_limit'])) {
        VMPFence_Config::set('crawler_rate_limit', sanitize_text_field($_POST['vmpfence_rl_crawler_limit']));
    }
    if (isset($_POST['vmpfence_rl_crawler_action'])) {
        $act = sanitize_text_field($_POST['vmpfence_rl_crawler_action']);
        if (in_array($act, array('throttle', 'block'))) {
            VMPFence_Config::set('crawler_rate_action', $act);
        }
    }
    if (isset($_POST['vmpfence_rl_crawler_404_limit'])) {
        VMPFence_Config::set('crawler_404_limit', sanitize_text_field($_POST['vmpfence_rl_crawler_404_limit']));
    }
    if (isset($_POST['vmpfence_rl_crawler_404_action'])) {
        $act = sanitize_text_field($_POST['vmpfence_rl_crawler_404_action']);
        if (in_array($act, array('throttle', 'block'))) {
            VMPFence_Config::set('crawler_404_action', $act);
        }
    }
    if (isset($_POST['vmpfence_rl_human_limit'])) {
        VMPFence_Config::set('human_rate_limit', sanitize_text_field($_POST['vmpfence_rl_human_limit']));
    }
    if (isset($_POST['vmpfence_rl_human_action'])) {
        $act = sanitize_text_field($_POST['vmpfence_rl_human_action']);
        if (in_array($act, array('throttle', 'block'))) {
            VMPFence_Config::set('human_rate_action', $act);
        }
    }
    if (isset($_POST['vmpfence_rl_human_404_limit'])) {
        VMPFence_Config::set('human_404_limit', sanitize_text_field($_POST['vmpfence_rl_human_404_limit']));
    }
    if (isset($_POST['vmpfence_rl_human_404_action'])) {
        $act = sanitize_text_field($_POST['vmpfence_rl_human_404_action']);
        if (in_array($act, array('throttle', 'block'))) {
            VMPFence_Config::set('human_404_action', $act);
        }
    }
    if (isset($_POST['vmpfence_rl_block_duration'])) {
        VMPFence_Config::set('rate_block_duration', intval($_POST['vmpfence_rl_block_duration']));
    }
    if (isset($_POST['vmpfence_rl_throttle_behavior'])) {
        $tb = sanitize_text_field($_POST['vmpfence_rl_throttle_behavior']);
        if (in_array($tb, array('slow_down', 'show_503'))) {
            VMPFence_Config::set('throttle_behavior', $tb);
        }
    }
    if (isset($_POST['vmpfence_rl_throttle_delay'])) {
        VMPFence_Config::set('throttle_delay_duration', max(1, min(100, intval($_POST['vmpfence_rl_throttle_delay']))));
    }
    if (isset($_POST['vmpfence_rl_allowlisted_404'])) {
        $raw = sanitize_textarea_field(wp_unslash($_POST['vmpfence_rl_allowlisted_404']));
        $urls = array_filter(array_map('trim', preg_split('/[\r\n]+/', $raw)));
        VMPFence_Config::set('allowlisted_404_urls', $urls);
    }

    // ── Blocking Options: Advanced Country Blocking ──
    if (isset($_POST['vmpfence_cb_action'])) {
        $cb_action = sanitize_text_field($_POST['vmpfence_cb_action']);
        if (in_array($cb_action, array('message', 'redirect'))) {
            VMPFence_Config::set('country_block_action', $cb_action);
        }
    }
    if (isset($_POST['vmpfence_cb_redirect_url'])) {
        update_option('vmpfence_country_block_redirect', esc_url_raw($_POST['vmpfence_cb_redirect_url']));
    }
    if (isset($_POST['vmpfence_cb_block_logged_in'])) {
        VMPFence_Config::set('country_block_logged_in', intval($_POST['vmpfence_cb_block_logged_in']));
    }
    if (isset($_POST['vmpfence_cb_bypass_field'])) {
        update_option('vmpfence_country_bypass_field', sanitize_text_field($_POST['vmpfence_cb_bypass_field']));
    }
    if (isset($_POST['vmpfence_cb_bypass_value'])) {
        update_option('vmpfence_country_bypass_value', sanitize_text_field($_POST['vmpfence_cb_bypass_value']));
    }
    if (isset($_POST['vmpfence_cb_bypass_cookie'])) {
        update_option('vmpfence_country_bypass_cookie', sanitize_text_field($_POST['vmpfence_cb_bypass_cookie']));
    }

    // ── Scan Options: Scan Scheduling ──
    if (isset($_POST['vmpfence_so_sched_enabled'])) {
        VMPFence_Config::set('scheduledScansEnabled', intval($_POST['vmpfence_so_sched_enabled']));
    }
    if (isset($_POST['vmpfence_so_sched_mode'])) {
        $sched_mode = sanitize_text_field($_POST['vmpfence_so_sched_mode']);
        if (in_array($sched_mode, array('auto', 'manual'))) {
            VMPFence_Config::set('schedMode', $sched_mode);
        }
    }
    if (isset($_POST['vmpfence_so_manual_pattern'])) {
        $pattern = sanitize_text_field($_POST['vmpfence_so_manual_pattern']);
        $valid_patterns = array('once_daily', 'twice_daily', 'every_other_day', 'weekdays', 'weekends', 'odd_days_weekends');
        if (in_array($pattern, $valid_patterns)) {
            VMPFence_Config::set('manualScanType', $pattern);
        }
    }
    if (isset($_POST['vmpfence_so_start_hour'])) {
        $hour = intval($_POST['vmpfence_so_start_hour']);
        if ($hour >= 0 && $hour <= 23) {
            VMPFence_Config::set('schedStartHour', $hour);
        }
    }
    if (isset($_POST['vmpfence_so_timezone'])) {
        $tz = sanitize_text_field($_POST['vmpfence_so_timezone']);
        if (in_array($tz, timezone_identifiers_list())) {
            VMPFence_Config::set('scheduleTimezone', $tz);
        }
    }
    if (isset($_POST['vmpfence_so_random_offset'])) {
        VMPFence_Config::set('randomOffset', sanitize_text_field($_POST['vmpfence_so_random_offset']));
    }

    // ── Scan Options: Basic Scan Type ──
    if (isset($_POST['vmpfence_so_scan_type'])) {
        $scan_type = sanitize_text_field($_POST['vmpfence_so_scan_type']);
        if (in_array($scan_type, array('limited', 'standard', 'high_sensitivity', 'custom'))) {
            VMPFence_Config::set('scanType', $scan_type);
        }
    }

    // ── Scan Options: General Options ──
    $go_keys = array(
        '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'
    );
    foreach ($go_keys as $go_key) {
        $post_key = 'vmpfence_go_' . $go_key;
        if (isset($_POST[$post_key])) {
            VMPFence_Config::set($go_key, intval($_POST[$post_key]));
        }
    }

    // ── Scan Options: Performance Options ──
    if (isset($_POST['vmpfence_po_low_resource'])) {
        VMPFence_Config::set('lowResourceScansEnabled', intval($_POST['vmpfence_po_low_resource']));
    }
    if (isset($_POST['vmpfence_po_max_issues'])) {
        VMPFence_Config::set('scan_maxIssues', intval($_POST['vmpfence_po_max_issues']));
    }
    if (isset($_POST['vmpfence_po_max_duration'])) {
        VMPFence_Config::set('scan_maxDuration', intval($_POST['vmpfence_po_max_duration']));
    }
    if (isset($_POST['vmpfence_po_max_mem'])) {
        $max_mem = intval($_POST['vmpfence_po_max_mem']);
        if ($max_mem >= 64) {
            VMPFence_Config::set('maxMem', $max_mem);
        }
    }
    if (isset($_POST['vmpfence_po_max_exec_time'])) {
        VMPFence_Config::set('scan_maxExecTime', intval($_POST['vmpfence_po_max_exec_time']));
    }

    // Advanced Scan Options
    if (isset($_POST['vmpfence_aso_exclude'])) {
        VMPFence_Config::set('scan_exclude', sanitize_textarea_field($_POST['vmpfence_aso_exclude']));
    }
    if (isset($_POST['vmpfence_aso_include_extra'])) {
        VMPFence_Config::set('scan_include_extra', sanitize_textarea_field($_POST['vmpfence_aso_include_extra']));
    }
    if (isset($_POST['vmpfence_aso_force_ipv4'])) {
        VMPFence_Config::set('scan_force_ipv4_start', intval($_POST['vmpfence_aso_force_ipv4']));
    }
    if (isset($_POST['vmpfence_aso_max_resume'])) {
        VMPFence_Config::set('scan_max_resume_attempts', intval($_POST['vmpfence_aso_max_resume']));
    }

    // Live Traffic Options
    if (isset($_POST['vmpfence_lt_logging_mode'])) {
        $mode = sanitize_text_field($_POST['vmpfence_lt_logging_mode']);
        if (in_array($mode, array('security_only', 'all_traffic'))) {
            update_option('vmpfence_traffic_logging_mode', $mode);
        }
    }
    if (isset($_POST['vmpfence_lt_ignore_publishing'])) {
        update_option('vmpfence_ignore_publishing_users', intval($_POST['vmpfence_lt_ignore_publishing']) ? '1' : '0');
    }
    if (isset($_POST['vmpfence_lt_ignore_usernames'])) {
        update_option('vmpfence_ignore_usernames', sanitize_textarea_field($_POST['vmpfence_lt_ignore_usernames']));
    }
    if (isset($_POST['vmpfence_lt_ignore_ips'])) {
        update_option('vmpfence_ignore_ips', sanitize_textarea_field($_POST['vmpfence_lt_ignore_ips']));
    }
    if (isset($_POST['vmpfence_lt_ignore_ua'])) {
        update_option('vmpfence_ignore_user_agent', sanitize_text_field($_POST['vmpfence_lt_ignore_ua']));
    }
    if (isset($_POST['vmpfence_lt_max_rows'])) {
        $rows = intval($_POST['vmpfence_lt_max_rows']);
        if ($rows >= 100 && $rows <= 50000) {
            update_option('vmpfence_max_traffic_rows', $rows);
        }
    }
    if (isset($_POST['vmpfence_lt_max_days'])) {
        $days = intval($_POST['vmpfence_lt_max_days']);
        if ($days >= 1 && $days <= 30) {
            update_option('vmpfence_max_traffic_days', $days);
        }
    }

    // Audit Log Options
    if (isset($_POST['vmpfence_al_logging_mode'])) {
        $old_al_mode = get_option('vmpfence_audit_log_logging_mode', 'significant');
        $al_mode = sanitize_text_field($_POST['vmpfence_al_logging_mode']);
        if (in_array($al_mode, array('disabled', 'preview', 'significant', 'all'))) {
            update_option('vmpfence_audit_log_logging_mode', $al_mode);
            if ($old_al_mode !== $al_mode) {
                do_action('vmpfence_audit_log_mode_changed', $old_al_mode, $al_mode);
            }
        }
    }
    if (isset($_POST['vmpfence_al_display_menu'])) {
        VMPFence_Config::set('display_audit_log_menu', intval($_POST['vmpfence_al_display_menu']) ? 1 : 0);
    }

    wp_send_json_success(array('message' => 'Settings saved successfully!'));
}

add_action('wp_ajax_vmpfence_save_all_options', 'vmpfence_save_all_options_ajax');

/**
 * Handle license change AJAX request
 * 
 * @since 2.2.2
 */
function vmpfence_handle_license_change_ajax() {
    // Security checks
    if (!check_ajax_referer('vmpfence_change_license', 'nonce', false)) {
        wp_send_json_error(array('message' => 'Security verification failed. Please refresh the page and try again.'));
    }
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'Insufficient permissions.'));
    }
    
    // Get and sanitize inputs
    $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
    $license_key = isset($_POST['license_key']) ? sanitize_text_field(wp_unslash($_POST['license_key'])) : '';
    $email_alerts = isset($_POST['email_alerts']) ? sanitize_text_field(wp_unslash($_POST['email_alerts'])) : '0';
    
    // Validate inputs
    if (empty($email) || empty($license_key)) {
        wp_send_json_error(array('message' => 'Email and license key are required.'));
    }
    
    if (!is_email($email)) {
        wp_send_json_error(array('message' => 'Invalid email address.'));
    }
    
    // Validate license key format
    if (!preg_match('/^(FREE|PREM)-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/', $license_key)) {
        wp_send_json_error(array('message' => 'Invalid license key format. Expected format: FREE-XXXX-XXXX-XXXX or PREM-XXXX-XXXX-XXXX'));
    }
    
    // Rate limiting: 3 attempts per 5 minutes per email
    $rate_limit_key = 'vmpfence_license_attempt_' . md5($email);
    $attempts = get_transient($rate_limit_key);
    
    if ($attempts === false) {
        $attempts = 0;
    }
    
    if ($attempts >= 3) {
        $timeout = get_option('_transient_timeout_' . $rate_limit_key);
        if ($timeout && $timeout > time()) {
            $time_left = $timeout - time();
            $minutes = ceil($time_left / 60);
            wp_send_json_error(array(
                'message' => "Too many attempts. Please try again in {$minutes} minute(s)."
            ));
        } else {
            // Transient expired but wasn't cleaned up - reset it
            delete_transient($rate_limit_key);
            $attempts = 0;
        }
    }
    
    // Increment attempts
    set_transient($rate_limit_key, $attempts + 1, 300); // 5 minutes
    
    // Load API client
    require_once VMPFENCE_PLUGIN_DIR . 'lib/class-api-client.php';
    $api_client = new VMPFence_API_Client();
    
    // Attempt license activation
    $result = $api_client->activate_license($license_key, home_url(), $email);
    
    // Check for errors
    if (is_wp_error($result)) {
        // Extract error context from WP_Error data (parse_response stores full server JSON)
        $error_context = null;
        $wp_error_data = $result->get_error_data();
        if (isset($wp_error_data['data']) && is_array($wp_error_data['data'])) {
            $error_context = $wp_error_data['data'];
        }

        // Check for specific error types to return structured responses
        if ($error_context && 
            isset($error_context['registered_site']) && 
            isset($error_context['current_site']) &&
            isset($error_context['license_type']) && 
            $error_context['license_type'] === 'premium') {
            // Premium license locked to different site
            wp_send_json_error(array(
                'message' => $result->get_error_message(),
                'error_type' => 'license_already_registered',
                'registered_site' => $error_context['registered_site'],
                'current_site' => $error_context['current_site'],
                'detailed_message' => isset($error_context['message']) ? $error_context['message'] : $result->get_error_message()
            ));
        }

        // Check for email mismatch (server returns specific error message)
        if ($error_context && isset($error_context['message'])) {
            wp_send_json_error(array(
                'message' => $error_context['message']
            ));
        }

        // Generic WP_Error
        wp_send_json_error(array(
            'message' => $result->get_error_message()
        ));
    }
    
    if (!isset($result['success']) || !$result['success']) {
        $error_message = isset($result['message']) ? $result['message'] : 'License activation failed. Please check your email and license key.';
        wp_send_json_error(array('message' => $error_message));
    }
    
    // Verify response has required fields
    if (!isset($result['license_key']) || !isset($result['api_key'])) {
        // error_log('VMP License Change Error: Missing required fields in API response');
        wp_send_json_error(array('message' => 'Invalid response from server. Please try again.'));
    }
    
    // Get license type from API response (not from user input)
    $license_type = isset($result['license_type']) ? $result['license_type'] : 'FREE';
    $api_key = $result['api_key'];
    $activated_license_key = $result['license_key']; // Use key from API response
    
    // Clear rate limit on success
    delete_transient($rate_limit_key);
    
    // IMPORTANT: activate_license() already called update_license_settings() with basic data
    // We need to add the additional fields that weren't in the API response
    if (class_exists('VMPFence_Config')) {
        VMPFence_Config::set('central_api_key', $api_key);
        VMPFence_Config::set('license_email', $email);
        VMPFence_Config::set('vmpfence_email_alerts_enabled', $email_alerts === '1');
    } else {
        // Fallback to wp_options
        update_option('vmpfence_api_key', $api_key);
        update_option('vmpfence_license_email', $email);
        update_option('vmpfence_email_alerts_enabled', $email_alerts === '1');
    }
    
    // Clear license refresh transient (already done by activate_license but double-check)
    delete_transient('vmpfence_license_last_refresh');
    delete_transient('vmpfence_is_premium');
    
    // Sync WAF rules from API
    if (class_exists('VMPFence_WAF_Rule') && method_exists('VMPFence_WAF_Rule', 'sync_from_api')) {
        try {
            $sync_result = VMPFence_WAF_Rule::sync_from_api();
            if ($sync_result) {
                update_option('vmpfence_waf_last_sync', time());
                // error_log('VMP License Change: WAF rules synced successfully');
            }
        } catch (Exception $e) {
            // Don't fail the license activation if WAF sync fails
            // error_log('VMP License Change: WAF sync failed - ' . $e->getMessage());
        }
    }
    
    // Log successful activation
    if (class_exists('VMPFence_Secure_Logger')) {
        VMPFence_Secure_Logger::log(
            'license',
            'License changed successfully',
            array(
                'license_type' => $license_type,
                'license_key' => substr($activated_license_key, 0, 9) . '...',
                'email' => $email
            )
        );
    }

    // Fire hook for audit log observer (license changed)
    do_action('vmpfence_license_changed', '', $activated_license_key);

    // Return success
    wp_send_json_success(array(
        'message' => 'License activated successfully! Page will reload to show updated license.',
        'license_type' => $license_type
    ));
}

add_action('wp_ajax_vmpfence_change_license', 'vmpfence_handle_license_change_ajax');
