<?php
/**
 * VMPFence Setup Wizard
 * First-time setup for external service consent
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.2.2 - Added license setup step
 * @since 2.2.3 - Improved setup overlay logic
 * @since 2.2.4 - Updated styles for Activation modal, Added License Success/Error Modals
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * VMPFence Setup Wizard Class
 */
class VMPFence_Setup_Wizard {
    
    /**
     * Initialize setup wizard
     * @since 1.0.0
     * @since 2.2.2 - Added license setup step
     */
    public static function init() {
        add_action('admin_menu', array(__CLASS__, 'add_setup_page'));
        add_action('admin_init', array(__CLASS__, 'process_setup_form'));
        add_action('admin_init', array(__CLASS__, 'redirect_setup_page'), 20);
        add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_setup_scripts'));
        add_action('admin_notices', array(__CLASS__, 'show_setup_incomplete_notice'), 1);
        add_action('admin_notices', array(__CLASS__, 'show_plugins_page_license_card'), 20);
        add_action('wp_ajax_vmpfence_dismiss_activation_modal', array(__CLASS__, 'ajax_dismiss_activation_modal'));
        add_action('wp_ajax_vmpfence_dismiss_plugins_card', array(__CLASS__, 'ajax_dismiss_plugins_card'));
        add_action('wp_ajax_vmpfence_remind_later', array(__CLASS__, 'ajax_remind_later'));
        add_action('wp_ajax_vmpfence_activate_license', array(__CLASS__, 'ajax_activate_license'));
        add_action('admin_footer', array(__CLASS__, 'render_license_result_modal'));
    }
    
    /**
     * Show setup incomplete notice on all admin pages (except setup page)
     */
    public static function show_setup_incomplete_notice() {
        // Only show for admin users
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Don't show during AJAX or cron
        if (wp_doing_ajax() || wp_doing_cron()) {
            return;
        }
        
        // Check if setup is needed
        if (!get_option('vmpfence_needs_setup', false)) {
            return;
        }
        
        // Check if user clicked "Remind Later" (skip for 12 hours)
        $remind_time = get_user_meta(get_current_user_id(), 'vmpfence_setup_remind_time', true);
        
        // ⏱️ TESTING: 2-minute reminder (remove after testing)
        // if ($remind_time && (time() - $remind_time) < (2 * MINUTE_IN_SECONDS)) {
        //     return;
        // }
        
        // 🚀 PRODUCTION: 12-hour reminder (uncomment after testing)
        if ($remind_time && (time() - $remind_time) < (12 * HOUR_IN_SECONDS)) {
            return;
        }
        
        // Don't show on setup page itself
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking GET parameter for display logic only
        if (isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'vmpfence-setup') {
            return;
        }
        
        // Check if we're on plugins page
        $screen = get_current_screen();
        $is_plugins_page = $screen && $screen->id === 'plugins';
        
        $setup_url = admin_url('admin.php?page=vmpfence-help&forced=1');
        ?>
        <style>
            .resume-btn {
                background-color: #fff !important;
                border-color: #191970 !important;
                color: #191970 !important;
                font-size: 16px !important;
                margin-right: 10px !important;
            }
            .resume-btn:hover {
                background-color: #bbbbbb !important;
            }
        </style>
        <?php if ($is_plugins_page) : ?>
        <div class="vmpfence-setup-bar" style="background-color: #fcb214; border:0; padding: 12px 15px; display: flex; align-items: center; max-width: 98% !important; margin: 15px 0;">
            <!-- <span style="font-size: 20px;">⚠️</span> -->
            <div style="flex: 1;">
                <strong style="font-size: 16px;"><?php esc_html_e('VMP Security installation is incomplete', 'vmpfence-security'); ?></strong>
            </div>
            
            <a href="#" id="vmpfence-remind-later-btn" class="button button-primary resume-btn" style="white-space: nowrap;">
                <?php esc_html_e('REMIND ME LATER', 'vmpfence-security'); ?>
            </a>
            
            <a href="<?php echo esc_url($setup_url); ?>" class="button button-primary resume-btn" style="white-space: nowrap;">
                <?php esc_html_e('RESUME INSTALLATION', 'vmpfence-security'); ?>
            </a>
        </div>
        <?php endif; ?>
        
        <?php if ($is_plugins_page) : ?>
        <script>
        jQuery(document).ready(function($) {
            $('#vmpfence-remind-later-btn').on('click', function(e) {
                e.preventDefault();
                
                // Send AJAX to set reminder
                $.post(ajaxurl, {
                    action: 'vmpfence_remind_later',
                    nonce: '<?php echo wp_create_nonce('vmpfence_remind_later'); ?>'
                }, function() {
                    // Show modal
                    var modal = $('<div class="vmpfence-remind-modal-overlay" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 100000; display: flex; align-items: center; justify-content: center;">' +
                        '<div style="background: #fff; padding: 0; border-radius: 2px; max-width: 460px; width: 100%; box-shadow: 0 3px 9px rgba(0,0,0,0.5);">' +
                        '<h2 style="margin: 0; font-size: 22px; font-weight: 600; color: #1d2327; line-height: 1.4; border-bottom: 1px solid #e2e2e2; padding: 16px;"><?php esc_html_e('Notice Dismissed', 'vmpfence-security'); ?></h2>' +
                        // '<p style="margin: 0 0 1rem; color: #1d2327; font-size: 13px; line-height: 1.5; border-bottom: 1px solid #e2e2e2; padding: 16px;"><?php esc_html_e('You will be reminded again in 2 minutes.', 'vmpfence-security'); ?></p>' +
                        // ⏱️ TESTING: Shows "2 minutes" (change to "12 hours" for production)
                        // 🚀 PRODUCTION: Uncomment below line and comment out the line above
                        '<p style="margin: 0 0 1rem; color: #1d2327; font-size: 13px; line-height: 1.5; border-bottom: 1px solid #e2e2e2; padding: 16px;"><?php esc_html_e('You will be reminded again in 12 hours.', 'vmpfence-security'); ?></p>' +
                        '<div style="text-align: right; padding: 0 1rem 1rem 1rem">' +
                        '<button class="button button-primary" style="background: #191970; border-color: #191970; padding: 4px 16px; height: auto; font-size: 13px; line-height: 1.5; box-shadow: none; text-shadow: none;"><?php esc_html_e('CLOSE', 'vmpfence-security'); ?></button>' +
                        '</div>' +
                        '</div>' +
                    '</div>');
                    
                    $('body').append(modal);
                    
                    // Close modal and hide notice
                    modal.find('button').on('click', function() {
                        modal.fadeOut(300, function() {
                            $(this).remove();
                        });
                        $('.vmpfence-setup-bar').fadeOut(300);
                    });
                });
            });
        });
        </script>
        <?php endif; ?>
        <?php
    }
    
    /**
     * Add setup page to admin menu
     * Note: Menu item is added by dashboard class when setup is needed
     * This just registers the page for direct access
     * @since 1.0.0
     * @since 2.2.2 - Always register page for direct URL access
     */
    public static function add_setup_page() {
        // Always register page for direct URL access
        // Menu visibility is controlled by dashboard class
        add_submenu_page(
            null, // Hidden from submenu (dashboard class handles menu item)
            __('VMP Security Setup', 'vmpfence-security'),
            __('VMP Security Setup', 'vmpfence-security'),
            'manage_options',
            'vmpfence-setup',
            array(__CLASS__, 'render_setup_page')
        );
    }
    
    /**
     * Process setup form submission
     * @since 1.0.0
     * @since 2.2.2 - Added license activation handling form
     */
    public static function process_setup_form() {
        // Handle license activation first (if submitted)
        if (isset($_POST['activate_license_setup']) && 
            isset($_POST['vmpfence_license_setup_nonce']) &&
            wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['vmpfence_license_setup_nonce'])), 'vmpfence_license_setup')) {
            
            if (!current_user_can('manage_options')) {
                return;
            }
            
            // Get license details from form
            $license_key = isset($_POST['license_key']) ? sanitize_text_field(wp_unslash($_POST['license_key'])) : '';
            $license_email = isset($_POST['license_email']) ? sanitize_email(wp_unslash($_POST['license_email'])) : '';
            $email_alerts = isset($_POST['email_alerts']) ? intval($_POST['email_alerts']) : 1;
            
            if (empty($license_key) || empty($license_email)) {
                self::redirect_with_license_error(__('Please enter both email and license key.', 'vmpfence-security'));
            }
            
            // Validate email format
            if (!is_email($license_email)) {
                self::redirect_with_license_error(__('VMP Security API error: The email address you\'re using is not valid.', 'vmpfence-security'));
            }
            
            // Validate license key format (FREE-XXXX-XXXX-XXXX or PREM-XXXX-XXXX-XXXX)
            if (!preg_match('/^(FREE|PREM)-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/i', $license_key)) {
                self::redirect_with_license_error(__('VMP Security API error: The VMP Security key you\'re using is not in a valid format.', 'vmpfence-security'));
            }
            
            // Rate limiting: Check if too many activation attempts
            $rate_limit_key = 'vmpfence_license_attempt_' . md5($license_email);
            $attempts = get_transient($rate_limit_key);
            if ($attempts !== false && $attempts >= 3) {
                // Get remaining time
                $transient_timeout = get_option('_transient_timeout_' . $rate_limit_key);
                $remaining_seconds = $transient_timeout ? max(0, $transient_timeout - time()) : 300;
                $remaining_minutes = ceil($remaining_seconds / 60);
                
                $error_msg = sprintf(
                    /* translators: %d: number of minutes remaining */
                    _n(
                        'Too many activation attempts. Please wait %d minute before trying again.',
                        'Too many activation attempts. Please wait %d minutes before trying again.',
                        $remaining_minutes,
                        'vmpfence-security'
                    ),
                    $remaining_minutes
                );
                
                self::redirect_with_license_error($error_msg);
            }
            
            // Increment attempt counter (expires in 5 minutes)
            set_transient($rate_limit_key, ($attempts ? $attempts + 1 : 1), 300);
            
            // Activate license via API
            if (class_exists('VMPFence_API_Client')) {
                $api_client = new VMPFence_API_Client();
                $result = $api_client->activate_license($license_key, home_url(), $license_email);
                
                // Check for successful activation (not just api_key presence)
                // Re-activations may not return api_key if it already exists
                if (!is_wp_error($result) && !empty($result['success'])) {
                    
                    // Validate required response fields
                    if (empty($result['license_type'])) {
                        if (class_exists('VMPFence_Secure_Logger')) {
                            VMPFence_Secure_Logger::log('error', 'Invalid activation response - missing license_type', array(
                                'response' => $result
                            ));
                        }
                        self::redirect_with_license_error(__('Invalid server response: missing license type. Please try again.', 'vmpfence-security'));
                    }
                    
                    // License activation successful - clear rate limit
                    delete_transient($rate_limit_key);
                    
                    // Store license data atomically - verify all saves succeed
                    $save_success = true;
                    try {
                        if (class_exists('VMPFence_Config')) {
                            // Only update API key if it's returned (new installations)
                            // Re-activations won't have api_key field, preserving existing key
                            if (isset($result['api_key'])) {
                                $save_success = $save_success && VMPFence_Config::set('central_api_key', $result['api_key']);
                            }
                            // ✅ CRITICAL FIX: Save license_key from API response, not form input
                            // For FREE users: form has generated key (FREE-XXXX-XXXX), but API returns actual DB key
                            // For PREMIUM users: form has actual key, matches API response
                            $actual_license_key = isset($result['license_key']) ? $result['license_key'] : $license_key;
                            $save_success = $save_success && VMPFence_Config::set('license_key', $actual_license_key);
                            $save_success = $save_success && VMPFence_Config::set('license_type', $result['license_type']);
                            $save_success = $save_success && VMPFence_Config::set('firewall_license_tier', $result['license_type']);
                            $save_success = $save_success && VMPFence_Config::set('license_email', $license_email);
                            $save_success = $save_success && VMPFence_Config::set('vmpfence_email_alerts_enabled', $email_alerts);
                        } else {
                            // Config class not available - fallback to direct option updates
                            // Note: update_option returns false if value unchanged, so we can't rely on return value
                            // Just ensure data is valid before saving
                            if (isset($result['api_key']) && is_string($result['api_key']) && !empty($result['api_key'])) {
                                update_option('vmpfence_central_api_key', $result['api_key']);
                            }
                            // ✅ CRITICAL FIX: Save license_key from API response, not form input
                            $actual_license_key = isset($result['license_key']) ? $result['license_key'] : $license_key;
                            if (is_string($actual_license_key) && !empty($actual_license_key)) {
                                update_option('vmpfence_license_key', $actual_license_key);
                            }
                            if (is_string($result['license_type']) && !empty($result['license_type'])) {
                                update_option('vmpfence_license_type', $result['license_type']);
                                update_option('vmpfence_firewall_license_tier', $result['license_type']);
                            }
                            if (is_email($license_email)) {
                                update_option('vmpfence_license_email', $license_email);
                            }
                            update_option('vmpfence_email_alerts_enabled', intval($email_alerts));
                        }
                    } catch (Exception $e) {
                        // Log error and mark save as failed
                        $save_success = false;
                        if (class_exists('VMPFence_Secure_Logger')) {
                            VMPFence_Secure_Logger::log('error', 'Failed to save some license config locally', array(
                                'error' => $e->getMessage()
                            ));
                        }
                    }
                    
                    // If save failed, show error instead of redirecting
                    if (!$save_success) {
                        self::redirect_with_license_error(__('License activated on server but failed to save locally. Please refresh the page and try again.', 'vmpfence-security'));
                    }
                    
                    // ✅ Mark setup as complete immediately (GSB consent removed - user can enable in Scan Options)
                    delete_option('vmpfence_needs_setup');
                    
                    // Sync WAF rules now that we have a valid license
                    // Check both WAF Rule class and Config class availability
                    if (class_exists('VMPFence_WAF_Rule') && class_exists('VMPFence_Config')) {
                        $waf_sync_result = VMPFence_WAF_Rule::sync_from_api();
                        if (!is_wp_error($waf_sync_result) && !empty($waf_sync_result['success'])) {
                            if (class_exists('VMPFence_Config')) {
                                VMPFence_Config::set('last_waf_sync_time', time());
                            } else {
                                update_option('vmpfence_last_waf_sync_time', time());
                            }
                            
                            // Log successful WAF sync
                            if (class_exists('VMPFence_Secure_Logger')) {
                                VMPFence_Secure_Logger::log('info', 'WAF rules synced after license activation', array(
                                    'total_rules' => isset($waf_sync_result['total']) ? $waf_sync_result['total'] : 0
                                ));
                            }
                        } else {
                            // WAF sync failed but don't block license activation
                            if (class_exists('VMPFence_Secure_Logger')) {
                                $waf_error = is_wp_error($waf_sync_result) ? $waf_sync_result->get_error_message() : 'Unknown WAF sync error';
                                VMPFence_Secure_Logger::log('warning', 'WAF sync failed after license activation', array(
                                    'error' => $waf_error
                                ));
                            }
                            // Schedule backup WAF sync for later
                            wp_schedule_single_event(time() + 60, 'vmpfence_hourly_waf_sync');
                        }
                    }
                    
                    // Log successful activation
                    if (class_exists('VMPFence_Secure_Logger')) {
                        VMPFence_Secure_Logger::log('info', 'License activated via setup wizard', array(
                            'license_type' => $result['license_type'],
                            'email' => $license_email
                        ));
                    }
                    
                    // Clear activation modal transient so it doesn't show anymore
                    delete_transient('vmpfence_show_activation_modal');
                    
                    // Mark setup as completed for future recovery scenarios
                    update_option('vmpfence_setup_completed', true);
                    
                    // Clear modal dismissal flags
                    delete_user_meta(get_current_user_id(), 'vmpfence_dismissed_activation_modal');
                    delete_user_meta(get_current_user_id(), 'vmpfence_dismissed_plugins_card');
                    
                    // Set success modal transient (shown on referer page via admin_footer)
                    $license_type_label = ucfirst($result['license_type']); // 'Free' or 'Premium'
                    set_transient('vmpfence_setup_success_modal', $license_type_label, 60);
                    
                    // Set success notice for dashboard (shown after user clicks GO TO DASHBOARD)
                    set_transient('vmpfence_setup_complete_notice', array(
                        'message' => __('Setup completed successfully! Your site is now protected.', 'vmpfence-security'),
                        'type' => 'success'
                    ), 60);
                    
                    // Redirect back to the same page (plugins/help) - success modal shows there
                    // User clicks "GO TO DASHBOARD" in the modal to navigate to dashboard
                    $referer = wp_get_referer();
                    wp_safe_redirect($referer ? $referer : admin_url('plugins.php'));
                    exit;
                } else {
                    // License activation failed
                    // Extract error context from WP_Error data or raw array response
                    // parse_response() stores full server JSON in WP_Error data['data']
                    $error_context = null;
                    if (is_wp_error($result)) {
                        $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'];
                        }
                    } elseif (is_array($result)) {
                        $error_context = $result;
                    }

                    // Check if this is a "license already registered" error (PREMIUM only)
                    // Server returns registered_site + current_site (aliases for active_site_url + requested_site_url)
                    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 - show deactivation instructions
                        $error_html = sprintf(
                            '<strong>%s</strong><br><br>' .
                            '%s: <code>%s</code><br>' .
                            '%s: <code>%s</code><br><br>' .
                            '<div style="background: #f0f0f1; padding: 10px; border-left: 4px solid #0073aa; margin-top: 10px;">' .
                            '<strong>%s:</strong><br>' .
                            '1. %s<br>' .
                            '2. %s<br>' .
                            '3. %s' .
                            '</div>',
                            __('Premium License Already Registered', 'vmpfence-security'),
                            __('Registered to', 'vmpfence-security'),
                            esc_html($error_context['registered_site']),
                            __('Current site', 'vmpfence-security'),
                            esc_html($error_context['current_site']),
                            __('To use this license here', 'vmpfence-security'),
                            sprintf(
                                __('Log in to your <a href="%s" target="_blank" style="color: #0073aa;">Web Portal</a>', 'vmpfence-security'),
                                'https://newton-security.com/login'
                            ),
                            __('Click "Deactivate License" next to this license', 'vmpfence-security'),
                            __('Return here and activate again', 'vmpfence-security')
                        );
                        
                        add_settings_error(
                            'vmpfence_license', 
                            'license_already_registered', 
                            $error_html, 
                            'error'
                        );
                        
                        $error_message = isset($error_context['error']) ? $error_context['error'] : 'Premium license already active on another site'; // For logging
                    } else {
                        // Generic error - get the best available message
                        if (is_wp_error($result)) {
                            $error_message = $result->get_error_message();
                        } elseif (is_array($result) && isset($result['error'])) {
                            $error_message = $result['error'];
                        } elseif ($error_context && isset($error_context['message'])) {
                            $error_message = $error_context['message'];
                        } elseif ($error_context && isset($error_context['error'])) {
                            $error_message = $error_context['error'];
                        } else {
                            $error_message = __('Unknown error during license activation', 'vmpfence-security');
                        }
                        add_settings_error('vmpfence_license', 'activation_failed', esc_html($error_message), 'error');
                    }
                    
                    if (class_exists('VMPFence_Secure_Logger')) {
                        VMPFence_Secure_Logger::log('error', 'License activation failed in setup wizard', array(
                            'error' => $error_message
                        ));
                    }
                    self::redirect_with_license_error($error_message);
                }
            } else {
                // API Client class not loaded - critical error
                if (class_exists('VMPFence_Secure_Logger')) {
                    VMPFence_Secure_Logger::log('critical', 'API Client class not available during license activation');
                }
                self::redirect_with_license_error(__('Critical error: API Client not available. Please contact support.', 'vmpfence-security'));
            }
        }
        
        /*
         * GSB CONSENT HANDLER - COMMENTED OUT (v2.2.4)
         * GSB is disabled by default and can be enabled in Scan Options.
         * No consent form needed - disclosed in readme.txt per WordPress guidelines.
         * Setup now completes immediately after license activation.
         *
        if (!isset($_POST['complete_setup'])) {
            return;
        }
        
        if (!isset($_POST['vmpfence_setup_nonce']) || 
            !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['vmpfence_setup_nonce'])), 'vmpfence_setup')) {
            return;
        }
        
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Process Google Safe Browsing consent
        $gsb_consent = isset($_POST['enable_google_safe_browsing']) ? true : false;
        
        // Update scan configuration based on consent
        if (class_exists('VMPFence_Config')) {
            VMPFence_Config::set('scansEnabled_checkGSB', $gsb_consent ? 1 : 0);
            VMPFence_Config::set('scansEnabled_fileContentsGSB', $gsb_consent ? 1 : 0);
        } else {
            update_option('vmpfence_scansEnabled_checkGSB', $gsb_consent ? 1 : 0);
            update_option('vmpfence_scansEnabled_fileContentsGSB', $gsb_consent ? 1 : 0);
        }
        
        update_option('vmpfence_gsb_consent', $gsb_consent ? 'yes' : 'no');
        update_option('vmpfence_gsb_consent_date', time());
        
        delete_option('vmpfence_needs_setup');
        
        // Set success transient for dashboard
        set_transient('vmpfence_setup_complete_notice', array(
            'message' => __('Setup completed successfully! Your site is now protected.', 'vmpfence-security'),
            'type' => 'success'
        ), 60);
        
        wp_safe_redirect(admin_url('admin.php?page=vmpfence-dashboard'));
        exit;
        */
    }
    
    /**
     * Redirect from setup page before headers are sent.
     *
     * Runs on admin_init at priority 20 (after process_setup_form at priority 10).
     * This ensures all redirects happen BEFORE admin-header.php outputs HTML.
     * Without this, render_setup_page() tries wp_safe_redirect() after headers
     * are already sent, which silently fails and exit kills the page — producing
     * a blank content area with no error display and no activation modal.
     *
     * @since 2.2.4
     */
    public static function redirect_setup_page() {
        // Only apply to the setup page
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking GET parameter for redirect logic only
        if ( ! isset( $_GET['page'] ) || sanitize_text_field( wp_unslash( $_GET['page'] ) ) !== 'vmpfence-setup' ) {
            return;
        }

        // If setup is already complete, redirect to dashboard
        if ( ! get_option( 'vmpfence_needs_setup', false ) ) {
            wp_safe_redirect( admin_url( 'admin.php?page=vmpfence-dashboard' ) );
            exit;
        }

        // Skip if license was just activated (allow setup page to show GSB consent)
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking GET parameter for redirect logic only
        if ( isset( $_GET['license_activated'] ) ) {
            return;
        }

        // If there's a pending license error, redirect to show it in the forced modal
        $has_errors = get_transient( 'vmpfence_license_error' );
        if ( ! empty( $has_errors ) && is_array( $has_errors ) ) {
            wp_safe_redirect( admin_url( 'admin.php?page=vmpfence-help&forced=1' ) );
            exit;
        }

        // Setup needed but no license — redirect to forced activation modal
        // (Prevents blank setup page that occurred when render_setup_page tried to redirect after headers)
        $has_license = false;
        if ( class_exists( 'VMPFence_Config' ) ) {
            $api_key = VMPFence_Config::get( 'central_api_key', '' );
            $has_license = is_string( $api_key ) && strlen( trim( $api_key ) ) > 0;
        } else {
            $api_key = get_option( 'vmpfence_central_api_key', '' );
            $has_license = is_string( $api_key ) && strlen( trim( $api_key ) ) > 0;
        }

        if ( ! $has_license ) {
            wp_safe_redirect( admin_url( 'admin.php?page=vmpfence-help&forced=1' ) );
            exit;
        }
    }

    /**
     * Enqueue setup wizard scripts
     * @since 1.0.0
     * @since 2.2.2 -- Added license form handling scripts
     */
    public static function enqueue_setup_scripts($hook) {
        if ($hook !== 'admin_page_vmpfence-setup') {
            return;
        }
        
        wp_enqueue_style('vmpfence-setup', VMPFENCE_PLUGIN_URL . 'admin/assets/css/setup-wizard.css', array(), VMPFENCE_VERSION);
        
        // Add inline JavaScript for form handling
        $inline_js = "
        (function() {
            // Prevent double submission
            var licenseForm = document.getElementById('vmpfence-license-form');
            if (licenseForm) {
                var form = licenseForm.querySelector('form');
                if (form) {
                    form.addEventListener('submit', function(e) {
                        var submitBtn = document.getElementById('vmpfence-license-submit');
                        if (submitBtn && submitBtn.disabled) {
                            e.preventDefault();
                            return false;
                        }
                        if (submitBtn) {
                            submitBtn.disabled = true;
                            var textSpan = submitBtn.querySelector('.vmpfence-submit-text');
                            var spinnerSpan = submitBtn.querySelector('.vmpfence-submit-spinner');
                            if (textSpan) textSpan.style.display = 'none';
                            if (spinnerSpan) spinnerSpan.style.display = 'inline';
                        }
                    });
                }
            }
        })();
        ";
        wp_add_inline_script('jquery', $inline_js);
    }
    
    /**
     * Render setup wizard page
     * @since 1.0.0
     * @since 2.0.0 Renamed to VMP WordPress Security
     * @since 2.2.2 Renamed to VMP Security, Added license setup step
     */
    public static function render_setup_page() {
        // Primary redirects (setup complete, no license, errors) are handled by
        // redirect_setup_page() on admin_init priority 20 — before headers are sent.
        // These fallback checks use return (NOT exit) so admin_footer can still
        // fire and show the activation modal overlay if somehow reached.
        if (!get_option('vmpfence_needs_setup', false)) {
            return; // Setup complete — admin_init should have redirected to dashboard
        }
        
        // Check if license is activated
        $has_license = false;
        if (class_exists('VMPFence_Config')) {
            $api_key = VMPFence_Config::get('central_api_key', '');
            $has_license = is_string($api_key) && strlen(trim($api_key)) > 0;
        } else {
            wp_cache_delete('vmpfence_central_api_key', 'options');
            $api_key = get_option('vmpfence_central_api_key', '');
            $has_license = is_string($api_key) && strlen(trim($api_key)) > 0;
        }
        
        // If no license, redirect to help page with forced modal
        if (!$has_license) {
            wp_safe_redirect(admin_url('admin.php?page=vmpfence-help&forced=1'));
            exit;
        }
        
        // License exists but setup not marked complete — fix it and redirect to dashboard
        // (GSB consent step removed — setup completes immediately after license activation)
        delete_option('vmpfence_needs_setup');
        wp_safe_redirect(admin_url('admin.php?page=vmpfence-dashboard'));
        exit;
        
        // NOTE: Code below is unreachable — kept for reference only.
        // The setup page now redirects immediately after license check.
        // GSB consent form was removed (v2.2.4) — users can enable GSB in Scan Options.
        ?>
        <div class="wrap vmpfence-setup-wizard">
            <div class="vmpfence-setup-container">
                <div class="vmpfence-setup-header">
                    <h1><?php esc_html_e('Welcome to VMP Security', 'vmpfence-security'); ?></h1>
                    <p class="description">
                        <?php esc_html_e('Let\'s configure your security settings to protect your WordPress site.', 'vmpfence-security'); ?>
                    </p>
                </div>
                
                <div class="vmpfence-setup-content">
                    <!-- LICENSE SETUP STEP (NEW - Added in v3.4) -->
                    <?php
                    // Check if license is already activated
                    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking GET parameter for display logic only
                    $has_license = false;
                    if (class_exists('VMPFence_Config')) {
                        $api_key = VMPFence_Config::get('central_api_key', '');
                        // Strict validation: must be non-empty string with actual content
                        $has_license = is_string($api_key) && strlen(trim($api_key)) > 0;
                    } else {
                        // Fallback to direct option check if Config class not available
                        // Clear cache to get fresh value after redirect
                        wp_cache_delete('vmpfence_central_api_key', 'options');
                        $api_key = get_option('vmpfence_central_api_key', '');
                        $has_license = is_string($api_key) && strlen(trim($api_key)) > 0;
                    }
                    
                    /*
                    // LICENSE SETUP SECTION COMMENTED OUT - Using activation modal instead
                    // Show license setup if no license exists
                    if (!$has_license) :
                    ?>
                    <div class="vmpfence-setup-step vmpfence-license-setup-step">
                        <h2><?php esc_html_e('License Setup', 'vmpfence-security'); ?></h2>
                        
                        <?php
                        // Display license activation errors
                        $license_errors = get_transient('vmpfence_license_error');
                        if ($license_errors && is_array($license_errors)) {
                            foreach ($license_errors as $error) {
                                ?>
                                <div class="notice notice-error is-dismissible" style="margin: 20px 0;">
                                    <p><strong><?php echo esc_html($error['message']); ?></strong></p>
                                </div>
                                <?php
                            }
                            delete_transient('vmpfence_license_error');
                        }
                        
                        // Display license activation success
                        $license_success = get_transient('vmpfence_license_success');
                        if ($license_success && is_array($license_success)) {
                            foreach ($license_success as $success) {
                                ?>
                                <div class="notice notice-success is-dismissible" style="margin: 20px 0;">
                                    <p><strong><?php echo esc_html($success['message']); ?></strong></p>
                                </div>
                                <?php
                            }
                            delete_transient('vmpfence_license_success');
                        }
                        ?>
                        
                        <?php
                        // Check if user is returning from pricing page
                        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking GET parameter for display logic only
                        $show_license_form = isset($_GET['show_license_form']) && $_GET['show_license_form'] === '1';
                        ?>
                        
                        <div class="vmpfence-license-prompt" style="text-align: center; padding: 40px 20px; background: #f9f9f9; border-radius: 12px; margin-bottom: 30px; <?php echo $show_license_form ? 'display: none;' : ''; ?>">
                            <div style="font-size: 48px; margin-bottom: 20px;">✓</div>
                            <h3 style="margin: 0 0 16px; color: #191970; font-size: 24px;"><?php esc_html_e('VMP Security Successfully Installed', 'vmpfence-security'); ?></h3>
                            <p style="margin: 0 0 24px; color: #646970; font-size: 16px;">
                                <?php esc_html_e('Register with VMP Security to secure your site with the latest threat intelligence.', 'vmpfence-security'); ?>
                            </p>
                            
                            <a href="https://vmpsecurity.com/pricing/" 
                               target="_blank"
                               onclick="document.getElementById('vmpfence-license-form').style.display='block'; document.querySelector('.vmpfence-license-prompt').style.display='none';"
                               class="button button-primary" 
                               style="background: #191970; border-color: #191970; box-shadow: none; text-shadow: none; font-size: 16px; padding: 12px 36px; height: auto; margin-bottom: 20px;">
                                🎫 <?php esc_html_e('GET YOUR VMP SECURITY LICENSE', 'vmpfence-security'); ?>
                            </a>
                            
                            <div style="margin-top: 24px;">
                                <p style="margin: 0 0 12px; color: #646970; font-size: 14px;"><?php esc_html_e('Already have a license?', 'vmpfence-security'); ?></p>
                                <button type="button" 
                                        onclick="document.getElementById('vmpfence-license-form').style.display='block'; document.querySelector('.vmpfence-license-prompt').style.display='none'; return false;"
                                        class="button vmpfence-show-license-form"
                                        style="font-size: 14px;">
                                    <?php esc_html_e('Install an existing license', 'vmpfence-security'); ?>
                                </button>
                                <noscript>
                                    <p style="margin-top: 12px; padding: 12px; background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; color: #856404; font-size: 13px;">
                                        ⚠️ <?php esc_html_e('JavaScript is disabled. Please enable JavaScript or scroll down to view the license form.', 'vmpfence-security'); ?>
                                    </p>
                                </noscript>
                            </div>
                        </div>
                        
                        <noscript><style>.vmpfence-license-prompt { display: none !important; }</style></noscript>
                        <div id="vmpfence-license-form" class="vmpfence-license-form-container" style="<?php echo $show_license_form ? 'display: block;' : 'display: none;'; ?> max-width: 600px; margin: 0 auto;">
                            <form method="post" action="" style="background: #fff; padding: 30px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                <?php wp_nonce_field('vmpfence_license_setup', 'vmpfence_license_setup_nonce'); ?>
                                
                                <h3 style="margin: 0 0 20px; color: #191970;"><?php esc_html_e('Enter Your License Information', 'vmpfence-security'); ?></h3>
                                
                                <div style="margin-bottom: 20px;">
                                    <label for="license_email" style="display: block; margin-bottom: 8px; font-weight: 600; color: #1d2327;">
                                        <?php esc_html_e('Email Address', 'vmpfence-security'); ?>
                                    </label>
                                    <input type="email" 
                                           id="license_email" 
                                           name="license_email" 
                                           class="regular-text"
                                           style="width: 100%; height: 48px; border-radius: 8px; border: 1px solid #8c8f94; padding: 0 16px;"
                                           placeholder="your@email.com"
                                           required />
                                    <p class="description" style="margin: 8px 0 0; color: #646970; font-size: 13px;">
                                        <?php esc_html_e('Security alerts will be sent to this email address.', 'vmpfence-security'); ?>
                                    </p>
                                </div>
                                
                                <div style="margin-bottom: 20px;">
                                    <label for="license_key" style="display: block; margin-bottom: 8px; font-weight: 600; color: #1d2327;">
                                        <?php esc_html_e('License Key', 'vmpfence-security'); ?>
                                    </label>
                                    <input type="text" 
                                           id="license_key" 
                                           name="license_key" 
                                           class="regular-text"
                                           style="width: 100%; height: 48px; border-radius: 8px; border: 1px solid #8c8f94; padding: 0 16px; font-family: monospace;"
                                           placeholder="XXXX-XXXX-XXXX-XXXX"
                                           required />
                                    <p class="description" style="margin: 8px 0 0; color: #646970; font-size: 13px;">
                                        <?php esc_html_e('Enter the license key you received via email.', 'vmpfence-security'); ?>
                                    </p>
                                </div>
                                
                                <div style="margin-bottom: 24px;">
                                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #1d2327;">
                                        <?php esc_html_e('Security Email Alerts', 'vmpfence-security'); ?>
                                    </label>
                                    <label style="display: block; margin-bottom: 8px;">
                                        <input type="radio" name="email_alerts" value="1" checked /> 
                                        <?php esc_html_e('YES - Send me email alerts for threats', 'vmpfence-security'); ?>
                                    </label>
                                    <label style="display: block;">
                                        <input type="radio" name="email_alerts" value="0" /> 
                                        <?php esc_html_e('NO - Don\'t send email alerts', 'vmpfence-security'); ?>
                                    </label>
                                </div>
                                
                                <button type="submit" 
                                        name="activate_license_setup"
                                        id="vmpfence-license-submit"
                                        class="button button-primary"
                                        style="width: 100%; background: #191970; border-color: #191970; box-shadow: none; text-shadow: none; font-size: 16px; padding: 12px; height: auto;">
                                    <span class="vmpfence-submit-text">🔑 <?php esc_html_e('ACTIVATE LICENSE', 'vmpfence-security'); ?></span>
                                    <span class="vmpfence-submit-spinner" style="display:none;">⏳ <?php esc_html_e('Activating...', 'vmpfence-security'); ?></span>
                                </button>
                                
                                <p style="margin: 16px 0 0; text-align: center;">
                                    <button type="button" 
                                            onclick="document.getElementById('vmpfence-license-form').style.display='none'; document.querySelector('.vmpfence-license-prompt').style.display='block';"
                                            class="button"
                                            style="font-size: 13px;">
                                        ← <?php esc_html_e('Back', 'vmpfence-security'); ?>
                                    </button>
                                    <span style="margin: 0 8px; color: #c3c4c7;">|</span>
                                    <a href="https://vmpsecurity.com/pricing/" 
                                       target="_blank"
                                       style="font-size: 13px; color: #007AFF; text-decoration: none;">
                                        <?php esc_html_e('Get a new license', 'vmpfence-security'); ?>
                                    </a>
                                </p>
                            </form>
                        </div>
                        
                        <p style="text-align: center; margin-top: 30px; color: #646970; font-size: 13px;">
                            <?php esc_html_e('You must activate a license (FREE or PREMIUM) to continue setup.', 'vmpfence-security'); ?>
                        </p>
                    </div>
                    <?php 
                    endif; 
                    */
                    ?>
                    <!-- END LICENSE SETUP STEP -->
                    
                    <!-- GOOGLE SAFE BROWSING CONSENT STEP (Existing) -->
                    <?php
                    // Show GSB consent ONLY if license is activated
                    // After successful license activation, page reloads and $has_license becomes true
                    if ($has_license) :
                    ?>
                    <div class="vmpfence-setup-step">
                        <h2><?php esc_html_e('External Security Services', 'vmpfence-security'); ?></h2>
                        
                        <form method="post" action="">
                            <?php wp_nonce_field('vmpfence_setup', 'vmpfence_setup_nonce'); ?>
                            
                            <div class="vmpfence-setup-option">
                                <div class="vmpfence-setup-option-header">
                                    <label for="enable_google_safe_browsing">
                                        <input type="checkbox" 
                                               id="enable_google_safe_browsing" 
                                               name="enable_google_safe_browsing" 
                                               value="1"/>
                                        <strong><?php esc_html_e('Enable Google Safe Browsing Protection', 'vmpfence-security'); ?></strong>
                                    </label>
                                </div>
                                
                                <div class="vmpfence-setup-option-description">
                                    <p><?php esc_html_e('Google Safe Browsing helps protect your site by checking URLs against Google\'s database of known malicious websites, phishing sites, and malware distribution points.', 'vmpfence-security'); ?></p>
                                    
                                    <div class="vmpfence-privacy-info">
                                        <h4><?php esc_html_e('Privacy Information:', 'vmpfence-security'); ?></h4>
                                        <ul>
                                            <li><?php esc_html_e('URLs found in your content, posts, and comments will be sent to Google\'s servers for analysis', 'vmpfence-security'); ?></li>
                                            <li><?php esc_html_e('No personal information, user data, or site content is transmitted beyond the URLs', 'vmpfence-security'); ?></li>
                                            <li><?php esc_html_e('Results are cached locally for 1 hour to reduce external API calls', 'vmpfence-security'); ?></li>
                                            <li><?php esc_html_e('You can disable this feature at any time in the scan settings', 'vmpfence-security'); ?></li>
                                        </ul>
                                        
                                        <p class="vmpfence-privacy-links">
                                            <a href="https://developers.google.com/safe-browsing/v4/usage-limits" target="_blank" rel="noopener noreferrer">
                                                <?php esc_html_e('Google Safe Browsing API Terms', 'vmpfence-security'); ?>
                                            </a> | 
                                            <a href="https://policies.google.com/privacy" target="_blank" rel="noopener noreferrer">
                                                <?php esc_html_e('Google Privacy Policy', 'vmpfence-security'); ?>
                                            </a>
                                        </p>
                                    </div>
                                    
                                    <div class="vmpfence-recommendation">
                                        <p><strong><?php esc_html_e('Recommendation:', 'vmpfence-security'); ?></strong> 
                                        <?php esc_html_e('We recommend enabling this feature for enhanced protection against malicious URLs and malware. This service significantly improves your site\'s security detection capabilities.', 'vmpfence-security'); ?></p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="vmpfence-setup-actions">
                                <button type="submit" 
                                        name="complete_setup"
                                        class="button button-primary button-large">
                                    <?php esc_html_e('Continue Setup', 'vmpfence-security'); ?>
                                </button>
                                
                                <!-- <p class="description">
                                    <?php esc_html_e('You can change these settings later in VMPFence > Scan Options', 'vmpfence-security'); ?>
                                </p> -->
                            </div>
                        </form>
                    </div>
                    <?php endif; ?>
                    <!-- END GOOGLE SAFE BROWSING CONSENT STEP -->
                </div>
                
                <div class="vmpfence-setup-footer">
                    <!-- <p class="description">
                        <?php 
                        printf(
                            /* translators: %1$s: opening strong tag, %2$s: closing strong tag */
                            esc_html__('VMPFence respects your privacy. External services are optional and %1$sonly enabled with your explicit consent%2$s.', 'vmpfence-security'),
                            '<strong>',
                            '</strong>'
                        ); 
                        ?>
                    </p> -->
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Show license setup card on plugins page (inline card, not overlay)
     * @since 2.2.4
     */
    public static function show_plugins_page_license_card() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        if (wp_doing_ajax() || wp_doing_cron()) {
            return;
        }
        
        // Only show when setup is needed
        if (!get_option('vmpfence_needs_setup', false)) {
            return;
        }
        
        // Only show on plugins page
        $screen = get_current_screen();
        if (!$screen || $screen->id !== 'plugins') {
            return;
        }
        
        // Check if permanently dismissed
        $dismissed = get_user_meta(get_current_user_id(), 'vmpfence_dismissed_plugins_card', true);
        if ($dismissed) {
            return;
        }
        
        $dismiss_nonce = wp_create_nonce('vmpfence_dismiss_plugins_card');
        ?>
        <div id="vmpfence-plugins-license-card" class="notice" style="background: #fff; border: 1px solid #e4e4e4; padding: 0; margin: 15px 0; position: relative;">
            <div style="background: #191970; padding: 12px 16px; display: flex; align-items: center; justify-content: space-between;">
                <span style="color: #fff; font-size: 14px; font-weight: 600;"><?php esc_html_e('Please Complete VMP Security Installation', 'vmpfence-security'); ?></span>
                <button type="button" id="vmpfence-plugins-card-close" style="background: transparent; border: none; cursor: pointer; padding: 0; color: #fff; font-size: 20px; line-height: 1; display: flex; align-items: center;" aria-label="<?php esc_attr_e('Dismiss', 'vmpfence-security'); ?>">
                    <span class="dashicons dashicons-no-alt" style="width: 20px; height: 20px; font-size: 20px;"></span>
                </button>
            </div>
            <div style="padding: 1rem 2rem; display: block; margin: 0 auto; max-width: 600px;">
                <div class="vmpfence-ac-modal-body">
                    <!-- Step 1: License Prompt -->
                    <div id="vmpfence-card-license-prompt" style="text-align: center; border-radius: 12px;">
                        <!-- <div style="display: flex; align-items: center; justify-content: center; padding-bottom: 1rem;">
                            <img src="<?php echo esc_url(VMPFENCE_PLUGIN_URL . 'admin/assets/images/VMP-logo.svg'); ?>" alt="VMP Security" width="60" height="60" style="margin-right: 15px; flex-shrink: 0;">
                            <div style="display: flex; flex-direction: column;">
                                <span style="font-size: 36px; font-weight: 700; color: #191970; line-height: 1.2; margin-bottom: 3px;">VMP Security</span>
                                <span style="font-size: 14px; color: #666; line-height: 1.3;"><?php esc_html_e('Securing your', 'vmpfence-security'); ?> <span style="font-weight: 600; color: #191970;">WordPress</span> <?php esc_html_e('website', 'vmpfence-security'); ?></span>
                            </div>
                        </div>
                        <h3 style="margin: 0; color: #2d2d2d; font-size: 15px; font-weight:700; font-family: 'Roboto', sans-serif; padding: 0.25rem 0;">
                            <?php 
                            printf(
                                esc_html__('You have successfully installed VMP Security %s', 'vmpfence-security'),
                                esc_html(VMPFENCE_VERSION)
                            ); 
                            ?>
                        </h3> -->
                        <p style="margin: 1rem 0; color: #3c434a; font-size: 13px; font-weight: 700;">
                            <?php esc_html_e('Register with VMP Security to secure your site with the latest threat intelligence.', 'vmpfence-security'); ?>
                        </p>
                        
                        <a href="https://vmpsecurity.com/pricing/" 
                           target="_blank"
                           onclick="document.getElementById('vmpfence-card-license-form').style.display='block'; document.getElementById('vmpfence-card-license-prompt').style.display='none'; return true;"
                           class="button button-primary" 
                           style="background: #191970; border-color: #191970; box-shadow: none; text-shadow: none; font-size: 14px; font-weight: 400; height: auto; padding: 0.5rem 1.25rem; border-radius: 4px;">
                            <?php esc_html_e('GET YOUR VMP SECURITY LICENSE', 'vmpfence-security'); ?>
                        </a>
                        
                        <div style="margin-top: 1rem;">
                            <button type="button" 
                                    id="vmpfence-card-show-license-form"
                                    class="button"
                                    style="border:0; background: none; text-decoration: underline; color:#191970; font-size: 13px; font-weight: 400; padding: 0 0 1rem 0;">
                                <?php esc_html_e('Install an existing license', 'vmpfence-security'); ?>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Step 2: License Installation Form (Hidden by default) -->
                    <div id="vmpfence-card-license-form" style="display: none;">
                        <div style="text-align: center; border-radius: 12px;">
                            <!-- <div style="display: flex; align-items: center; justify-content: center; padding: 0 0 1rem 0;">
                                <img src="<?php echo esc_url(VMPFENCE_PLUGIN_URL . 'admin/assets/images/VMP-logo.svg'); ?>" alt="VMP Security" width="60" height="60" style="margin-right: 15px; flex-shrink: 0;">
                                <div style="display: flex; flex-direction: column;">
                                    <span style="font-size: 36px; font-weight: 700; color: #191970; line-height: 1.2; margin-bottom: 3px;">VMP Security</span>
                                    <span style="font-size: 14px; color: #666; line-height: 1.3;"><?php esc_html_e('Securing your', 'vmpfence-security'); ?> <span style="font-weight: 600; color: #191970;">WordPress</span> <?php esc_html_e('website', 'vmpfence-security'); ?></span>
                                </div>
                            </div>
                            <h3 style="margin: 0; color: #2d2d2d; font-size: 15px; font-family: 'Roboto', sans-serif; padding: 0.25rem 0;">
                                <?php 
                                printf(
                                    esc_html__('You have successfully installed VMP Security %s', 'vmpfence-security'),
                                    esc_html(VMPFENCE_VERSION)
                                ); 
                                ?>
                            </h3> -->
                            <p style="margin: 1rem 0; color: #3c434a; font-size: 13px; font-weight: 700;">
                                <?php esc_html_e('Register with VMP Security to secure your site with the latest threat intelligence.', 'vmpfence-security'); ?>
                            </p>
                        </div>
                        
                        <form method="post" id="vmpfence-card-license-form-el" style="padding: 0;">
                            <?php wp_nonce_field('vmpfence_license_setup', 'vmpfence_license_setup_nonce'); ?>
                            
                            <div style="margin-bottom: 1rem;">
                                <label for="card_license_email" style="display: block; font-weight: 400; color: #3c434a; font-size: 13px;">
                                    <?php esc_html_e('Email', 'vmpfence-security'); ?>
                                </label>
                                <input type="email" 
                                       id="card_license_email" 
                                       name="license_email" 
                                       class="regular-text"
                                       style="width: 100%; height: 38px; border-radius: 6px; border: 1px solid #8c8f94; padding: 0.25rem 0.5rem; font-size: 14px; font-weight: 400;"
                                       placeholder=""
                                       required />
                                <p style="color: #3c434a; font-size: 11px; font-weight: 400; margin: 0;">
                                    <?php esc_html_e('This is where future security alerts for your website will be sent. This can also be changed in Global Options.', 'vmpfence-security'); ?>
                                </p>
                            </div>
                            
                            <div style="margin-bottom: 1rem;">
                                <label for="card_license_key" style="display: block; font-weight: 400; color: #3c434a; font-size: 13px;">
                                    <?php esc_html_e('License Key — each VMP Security installation should have a unique key', 'vmpfence-security'); ?>
                                </label>
                                <input type="text" 
                                       id="card_license_key" 
                                       name="license_key" 
                                       class="regular-text"
                                       style="width: 100%; height: 70px; border-radius: 6px; border: 1px solid #8c8f94; padding: 0.25rem 0.5rem; font-family: monospace; font-size: 14px;"
                                       placeholder=""
                                       required />
                            </div>
                            
                            <div style="margin-bottom: 1rem;">
                                <p style="margin: 0; color: #3c434a; font-size: 13px; font-weight: 400;">
                                    <?php esc_html_e('Would you like WordPress security and vulnerability alerts sent to you via email?', 'vmpfence-security'); ?>
                                </p>
                                <style>
                                    .vmpfence-toggle-group { display: inline-flex; border: 1px solid #8c8f94; border-radius: 3px; overflow: hidden; margin-top: 0.25rem; }
                                    .vmpfence-toggle-group input[type="radio"] { position: absolute; opacity: 0; pointer-events: none; }
                                    .vmpfence-toggle-group label { padding: 6px 16px; font-size: 13px; cursor: pointer; background: #f6f7f7; color: #3c434a; margin: 0; line-height: 1.5; font-weight: 400; border-right: 1px solid #8c8f94; user-select: none; }
                                    .vmpfence-toggle-group label:last-child { border-right: none; }
                                    .vmpfence-toggle-group input[type="radio"]:checked + label { background: #191970; color: #fff; }
                                </style>
                                <div class="vmpfence-toggle-group">
                                    <input type="radio" name="email_alerts" id="card_email_yes" value="1" checked />
                                    <label for="card_email_yes"><?php esc_html_e('YES', 'vmpfence-security'); ?></label>
                                    <input type="radio" name="email_alerts" id="card_email_no" value="0" />
                                    <label for="card_email_no"><?php esc_html_e('NO', 'vmpfence-security'); ?></label>
                                </div>
                            </div>
                            
                            <button type="submit" 
                                    name="activate_license_setup"
                                    class="button button-primary"
                                    style="display: block; margin: 0 auto; background: #191970; border-color: #191970; box-shadow: none; text-shadow: none; font-size: 14px; height: auto; padding: 0.5rem 1.25rem; font-weight: 400; border-radius: 4px; line-height: 1.3125rem;">
                                <?php esc_html_e('INSTALL LICENSE', 'vmpfence-security'); ?>
                            </button>
                            
                            <p style="margin: 1rem 0 0; text-align: center; font-size: 13px; color: #191970; font-weight: 400; padding-bottom: 1rem;">
                                <button type="button" 
                                        id="vmpfence-card-back-to-prompt"
                                        class="button"
                                        style="border: 0; background: none; text-decoration: underline;">
                                    ← <?php esc_html_e('Back', 'vmpfence-security'); ?>
                                </button>
                                <span style="margin: 0 8px; color: #c3c4c7;">|</span>
                                <a href="https://vmpsecurity.com/pricing/" 
                                   target="_blank"
                                   style="color: #191970; text-decoration: underline;">
                                    <?php esc_html_e('Get a new license', 'vmpfence-security'); ?>
                                </a>
                            </p>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <style>
        #vmpfence-license-result-overlay {
            position: fixed;
            top: 32px;
            left: 160px;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 100002;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        @media screen and (max-width: 782px) {
            #vmpfence-license-result-overlay { top: 46px; left: 0; }
        }
        .folded #vmpfence-license-result-overlay { left: 36px; }
        </style>
        <script>
        jQuery(document).ready(function($) {
            var dashboardUrl = '<?php echo esc_url(admin_url('admin.php?page=vmpfence-dashboard')); ?>';
            var supportUrl = 'https://vmpsecurity.com/help/';
            var activateNonce = '<?php echo wp_create_nonce('vmpfence_license_setup'); ?>';

            // Toggle to license form
            $('#vmpfence-card-show-license-form').on('click', function() {
                $('#vmpfence-card-license-prompt').hide();
                $('#vmpfence-card-license-form').show();
            });
            // Toggle back to prompt
            $('#vmpfence-card-back-to-prompt').on('click', function() {
                $('#vmpfence-card-license-form').hide();
                $('#vmpfence-card-license-prompt').show();
            });
            // Close button - permanent dismiss
            $('#vmpfence-plugins-card-close').on('click', function() {
                $.post(ajaxurl, {
                    action: 'vmpfence_dismiss_plugins_card',
                    nonce: '<?php echo esc_js($dismiss_nonce); ?>'
                });
                $('#vmpfence-plugins-license-card').fadeOut(300, function() {
                    $(this).remove();
                });
            });
            // Hover effect for close button
            $('#vmpfence-plugins-card-close').hover(
                function() { $(this).css('opacity', '0.7'); },
                function() { $(this).css('opacity', '1'); }
            );

            // AJAX license activation
            $('#vmpfence-card-license-form-el').on('submit', function(e) {
                e.preventDefault();
                var $form = $(this);
                var $submitBtn = $form.find('button[name="activate_license_setup"]');
                var originalText = $submitBtn.text();
                $submitBtn.prop('disabled', true).text('<?php echo esc_js(__('Activating...', 'vmpfence-security')); ?>');

                $.post(ajaxurl, {
                    action: 'vmpfence_activate_license',
                    nonce: activateNonce,
                    license_key: $form.find('input[name="license_key"]').val(),
                    license_email: $form.find('input[name="license_email"]').val(),
                    email_alerts: $form.find('input[name="email_alerts"]:checked').val() || 1
                }, function(response) {
                    if (response.success) {
                        var licenseType = response.data.license_type;
                        var successModal = $(
                            '<div id="vmpfence-license-result-overlay">' +
                                '<div style="max-width:500px;width:100%;box-shadow:0 3px 30px rgba(0,0,0,0.3);border-radius:4px;overflow:hidden;">' +
                                '<div style="background:linear-gradient(135deg, #191970 0%, #192990 50%, #193390 100%);padding:4px;text-align:center;position:relative;">' +
                                    '<img src="data:image/svg+xml;charset=utf-8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA5MS42NSA3MC43OSI+PHBhdGggZD0iTTkwLjA4LDguNzMsODIuOTEsMS41N2E1LjE5LDUuMTksMCwwLDAtNy40MywwTDMzLjMxLDQzLjc0LDE2LjE2LDI2LjU5YTUuMiw1LjIsMCwwLDAtNy40MywwTDEuNTcsMzMuNzdhNS4xOSw1LjE5LDAsMCwwLDAsNy40M2wyOCwyOGE1LjIsNS4yLDAsMCwwLDcuNDMsMEw5MC4wOCwxNi4xN2E1LjE5LDUuMTksMCwwLDAsMC03LjQzWm0wLDAiIGZpbGw9IiMwMDdjYWMiLz48L3N2Zz4=" alt="" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:160px;height:160px;opacity:0.15; filter: brightness(0) invert(1);" />' +
                                    '<h2 style="margin:0; padding: 2rem 1rem 1rem 1rem; color:#fff; font-size:21px; font-weight:300; font-family:Roboto, sans-serif; position: relative; z-index: 1; line-height: 1.5rem;">' + licenseType + ' <?php echo esc_js(__('License Installed', 'vmpfence-security')); ?></h2>' +
                                    '<p style="margin:0;color: #fff; font-size: 13px; font-weight:400; position:relative; line-height: 1.4em; z-index:1; padding: 0 1.5rem 2rem 1.5rem;"><?php echo esc_js(__('Congratulations! VMP Security', 'vmpfence-security')); ?> ' + licenseType + ' <?php echo esc_js(__('is now active on your website.', 'vmpfence-security')); ?></p>' +
                                '</div>' +
                                '<div style="background: #ccc; padding: 1rem; text-align:right; border-top: 1px solid #bfbfbf;">' +
                                    '<a href="' + dashboardUrl + '" class="button button-primary" style="background: #191970;border:1px solid #191970;color: #fff; font-size:14px; font-family: Roboto, sans-serif; font-weight:400; padding: 0.5rem 1.25rem; height:auto; line-height:1.4em;box-shadow:none;text-shadow:none;border-radius:3px;text-decoration:none;"><?php echo esc_js(__('GO TO DASHBOARD', 'vmpfence-security')); ?></a>' +
                                '</div>' +
                            '</div>' +
                        '</div>'
                        );
                        $('body').append(successModal);
                    } else {
                        var errorMsg = response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Unknown error occurred.', 'vmpfence-security')); ?>';
                        var errorModal = $(
                                '<div id="vmpfence-license-result-overlay">' +
                                '<div style="background:#fff;max-width:460px;width:100%;border-radius:2px;box-shadow:0 3px 30px rgba(0,0,0,0.3);">' +
                                '<h2 style="margin:0; font-family: \'Roboto\', sans-serif; font-size:15px; font-weight:600; color: #333; padding:1rem; border-bottom:1px solid #d9d9d9; line-height: 1.4;"><?php echo esc_js(__('Error Installing License', 'vmpfence-security')); ?></h2>' +
                                '<div style="padding: 1rem;">' +
                                    '<p style="margin:0 0 1em 0; color: #333; font-family: \'Roboto\', sans-serif; font-size:13px; font-weight: 400; line-height:1.5; "><?php echo esc_js(__('We received an error while trying to activate the license with the VMP Security servers:', 'vmpfence-security')); ?> ' + $('<span>').text(errorMsg).html() + '</p>' +
                                    '<p style="margin:0 0 1em 0; color: #333; font-family: \'Roboto\', sans-serif; font-size:13px; font-weight: 400; line-height:1.5;"><?php echo esc_js(__('Please try again. If the problem persists, please', 'vmpfence-security')); ?> <a href="' + supportUrl + '" target="_blank" style="color:#0073aa;text-decoration:underline;"><?php echo esc_js(__('contact VMP Security Support', 'vmpfence-security')); ?></a>.</p>' +
                                '</div>' +
                                '<div style="padding: 1rem; border-top: 1px solid #d9d9d9; text-align: right; background: #f1f1f1">' +
                                    '<button type="button" class="button button-primary vmpfence-error-close" style="background:#191970;border-color:#191970; color:#fff; font-size:14px;font-weight:400; font-family: \'Roboto\', sans-serif; padding: 0.5rem 1.25rem; height:auto; line-height:1.3125rem; box-shadow:none;text-shadow:none;"><?php echo esc_js(__('CLOSE', 'vmpfence-security')); ?></button>' +
                                '</div>' +
                            '</div>' +
                        '</div>'
                        );
                        $('body').append(errorModal);
                        errorModal.find('.vmpfence-error-close').on('click', function() {
                            errorModal.fadeOut(300, function() { $(this).remove(); });
                        });
                        errorModal.on('click', function(ev) {
                            if (ev.target === this) { $(this).fadeOut(300, function() { $(this).remove(); }); }
                        });
                        $submitBtn.prop('disabled', false).text(originalText);
                    }
                }).fail(function() {
                    $submitBtn.prop('disabled', false).text(originalText);
                    alert('<?php echo esc_js(__('Network error. Please check your connection and try again.', 'vmpfence-security')); ?>');
                });
            });
        });
        </script>
        <?php
    }
    
    /**
     * AJAX handler for license activation (no page reload)
     * Returns JSON with success/error for client-side modal rendering
     * 
     * @since 2.2.4
     */
    public static function ajax_activate_license() {
        check_ajax_referer('vmpfence_license_setup', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied.', 'vmpfence-security')));
        }
        
        $license_key = isset($_POST['license_key']) ? sanitize_text_field(wp_unslash($_POST['license_key'])) : '';
        $license_email = isset($_POST['license_email']) ? sanitize_email(wp_unslash($_POST['license_email'])) : '';
        $email_alerts = isset($_POST['email_alerts']) ? intval($_POST['email_alerts']) : 1;
        
        if (empty($license_key) || empty($license_email)) {
            wp_send_json_error(array('message' => __('VMP Security API error: Please enter both email and license key.', 'vmpfence-security')));
        }
        
        if (!is_email($license_email)) {
            wp_send_json_error(array('message' => __('VMP Security API error: The email address you\'re using is not valid.', 'vmpfence-security')));
        }
        
        if (!preg_match('/^(FREE|PREM)-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/i', $license_key)) {
            wp_send_json_error(array('message' => __('VMP Security API error: The VMP Security key you\'re using is not in a valid format.', 'vmpfence-security')));
        }
        
        // Rate limiting
        $rate_limit_key = 'vmpfence_license_attempt_' . md5($license_email);
        $attempts = get_transient($rate_limit_key);
        if ($attempts !== false && $attempts >= 3) {
            $transient_timeout = get_option('_transient_timeout_' . $rate_limit_key);
            $remaining_seconds = $transient_timeout ? max(0, $transient_timeout - time()) : 300;
            $remaining_minutes = ceil($remaining_seconds / 60);
            $error_msg = sprintf(
                _n(
                    'Too many activation attempts. Please wait %d minute before trying again.',
                    'Too many activation attempts. Please wait %d minutes before trying again.',
                    $remaining_minutes,
                    'vmpfence-security'
                ),
                $remaining_minutes
            );
            wp_send_json_error(array('message' => $error_msg));
        }
        
        set_transient($rate_limit_key, ($attempts ? $attempts + 1 : 1), 300);
        
        if (!class_exists('VMPFence_API_Client')) {
            if (class_exists('VMPFence_Secure_Logger')) {
                VMPFence_Secure_Logger::log('critical', 'API Client class not available during license activation');
            }
            wp_send_json_error(array('message' => __('Critical error: API Client not available. Please contact support.', 'vmpfence-security')));
        }
        
        $api_client = new VMPFence_API_Client();
        $result = $api_client->activate_license($license_key, home_url(), $license_email);
        
        if (!is_wp_error($result) && !empty($result['success'])) {
            // Validate response
            if (empty($result['license_type'])) {
                if (class_exists('VMPFence_Secure_Logger')) {
                    VMPFence_Secure_Logger::log('error', 'Invalid activation response - missing license_type', array('response' => $result));
                }
                wp_send_json_error(array('message' => __('Invalid server response: missing license type. Please try again.', 'vmpfence-security')));
            }
            
            // Clear rate limit
            delete_transient($rate_limit_key);
            
            // Store license data
            $save_success = true;
            try {
                if (class_exists('VMPFence_Config')) {
                    if (isset($result['api_key'])) {
                        $save_success = $save_success && VMPFence_Config::set('central_api_key', $result['api_key']);
                    }
                    $actual_license_key = isset($result['license_key']) ? $result['license_key'] : $license_key;
                    $save_success = $save_success && VMPFence_Config::set('license_key', $actual_license_key);
                    $save_success = $save_success && VMPFence_Config::set('license_type', $result['license_type']);
                    $save_success = $save_success && VMPFence_Config::set('firewall_license_tier', $result['license_type']);
                    $save_success = $save_success && VMPFence_Config::set('license_email', $license_email);
                    $save_success = $save_success && VMPFence_Config::set('email_alerts_enabled', $email_alerts);
                } else {
                    if (isset($result['api_key']) && is_string($result['api_key']) && !empty($result['api_key'])) {
                        update_option('vmpfence_central_api_key', $result['api_key']);
                    }
                    $actual_license_key = isset($result['license_key']) ? $result['license_key'] : $license_key;
                    if (is_string($actual_license_key) && !empty($actual_license_key)) {
                        update_option('vmpfence_license_key', $actual_license_key);
                    }
                    if (is_string($result['license_type']) && !empty($result['license_type'])) {
                        update_option('vmpfence_license_type', $result['license_type']);
                        update_option('vmpfence_firewall_license_tier', $result['license_type']);
                    }
                    if (is_email($license_email)) {
                        update_option('vmpfence_license_email', $license_email);
                    }
                    update_option('vmpfence_email_alerts_enabled', intval($email_alerts));
                }
            } catch (Exception $e) {
                $save_success = false;
                if (class_exists('VMPFence_Secure_Logger')) {
                    VMPFence_Secure_Logger::log('error', 'Failed to save license config locally', array('error' => $e->getMessage()));
                }
            }
            
            if (!$save_success) {
                wp_send_json_error(array('message' => __('License activated on server but failed to save locally. Please refresh the page and try again.', 'vmpfence-security')));
            }
            
            // Complete setup
            delete_option('vmpfence_needs_setup');
            
            // Sync WAF rules
            if (class_exists('VMPFence_WAF_Rule') && class_exists('VMPFence_Config')) {
                $waf_sync_result = VMPFence_WAF_Rule::sync_from_api();
                if (!is_wp_error($waf_sync_result) && !empty($waf_sync_result['success'])) {
                    if (class_exists('VMPFence_Config')) {
                        VMPFence_Config::set('last_waf_sync_time', time());
                    } else {
                        update_option('vmpfence_last_waf_sync_time', time());
                    }
                } else {
                    wp_schedule_single_event(time() + 60, 'vmpfence_hourly_waf_sync');
                }
            }
            
            if (class_exists('VMPFence_Secure_Logger')) {
                VMPFence_Secure_Logger::log('info', 'License activated via AJAX', array(
                    'license_type' => $result['license_type'],
                    'email' => $license_email
                ));
            }
            
            // Cleanup
            delete_transient('vmpfence_show_activation_modal');
            update_option('vmpfence_setup_completed', true);
            delete_user_meta(get_current_user_id(), 'vmpfence_dismissed_activation_modal');
            delete_user_meta(get_current_user_id(), 'vmpfence_dismissed_plugins_card');
            
            // Set dashboard notice
            set_transient('vmpfence_setup_complete_notice', array(
                'message' => __('Setup completed successfully! Your site is now protected.', 'vmpfence-security'),
                'type' => 'success'
            ), 60);
            
            wp_send_json_success(array(
                'license_type' => ucfirst($result['license_type']),
                'dashboard_url' => admin_url('admin.php?page=vmpfence-dashboard')
            ));
        } else {
            // Activation failed
            $error_message = is_wp_error($result) 
                ? $result->get_error_message() 
                : (isset($result['error']) ? $result['error'] : __('Unknown error during license activation', 'vmpfence-security'));
            
            if (class_exists('VMPFence_Secure_Logger')) {
                VMPFence_Secure_Logger::log('error', 'License activation failed via AJAX', array('error' => $error_message));
            }
            
            wp_send_json_error(array('message' => $error_message));
        }
    }
    
    /**
     * Redirect back to referring page with an error modal transient
     * Used by license activation error paths to show error overlay
     * 
     * @since 2.2.4
     * @param string $error_message The error message to display in the modal
     */
    private static function redirect_with_license_error($error_message) {
        set_transient('vmpfence_setup_error_modal', $error_message, 60);
        $referer = wp_get_referer();
        wp_safe_redirect($referer ? $referer : admin_url('plugins.php'));
        exit;
    }
    
    /**
     * Render license activation result modal (success or error)
     * Hooked to admin_footer - shows on any admin page when transient exists
     * 
     * Success modal: Shown on dashboard after successful license activation
     *   - Blue gradient header with checkmark, "Free/Premium License Installed" heading
     *   - "GO TO DASHBOARD" button
     * 
     * Error modal: Shown on referring page after failed license activation
     *   - White modal with "Error Installing License" heading
     *   - Error message + support link
     *   - "CLOSE" button
     * 
     * @since 2.2.4
     */
    public static function render_license_result_modal() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Check for success modal
        $license_type = get_transient('vmpfence_setup_success_modal');
        if ($license_type) {
            delete_transient('vmpfence_setup_success_modal');
            $dashboard_url = admin_url('admin.php?page=vmpfence-dashboard');
            ?>
            <div id="vmpfence-license-result-overlay" style="animation: vmpfenceFadeIn 0.3s ease-in-out;">
                <div style="max-width: 500px; width: 100%; box-shadow: 0 3px 30px rgba(0,0,0,0.3); animation: vmpfenceSlideUp 0.3s ease-out;">
                    <!-- Blue gradient header -->
                    <div style="background: linear-gradient(135deg, #1a6b8a 0%, #2d8fad 50%, #3ba3c2 100%); padding: 40px 30px; text-align: center; position: relative;">
                        <!-- Checkmark watermark -->
                        <img src="data:image/svg+xml;charset=utf-8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA5MS42NSA3MC43OSI+PHBhdGggZD0iTTkwLjA4LDguNzMsODIuOTEsMS41N2E1LjE5LDUuMTksMCwwLDAtNy40MywwTDMzLjMxLDQzLjc0LDE2LjE2LDI2LjU5YTUuMiw1LjIsMCwwLDAtNy40MywwTDEuNTcsMzMuNzdhNS4xOSw1LjE5LDAsMCwwLDAsNy40M2wyOCwyOGE1LjIsNS4yLDAsMCwwLDcuNDMsMEw5MC4wOCwxNi4xN2E1LjE5LDUuMTksMCwwLDAsMC03LjQzWm0wLDAiIGZpbGw9IiMwMDdjYWMiLz48L3N2Zz4=" alt="" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 120px; height: 120px; opacity: 0.15;" />
                        <h2 style="margin: 0 0 10px; color: #fff; font-size: 22px; font-weight: 600; position: relative; z-index: 1;">
                            <?php 
                            printf(
                                /* translators: %s: license type (Free or Premium) */
                                esc_html__('%s License Installed', 'vmpfence-security'),
                                esc_html($license_type)
                            ); 
                            ?>
                        </h2>
                        <p style="margin: 0; color: rgba(255,255,255,0.9); font-size: 14px; font-weight: 400; position: relative; z-index: 1;">
                            <?php 
                            printf(
                                /* translators: %s: license type (Free or Premium) */
                                esc_html__('Congratulations! VMP Security %s is now active on your website.', 'vmpfence-security'),
                                esc_html($license_type)
                            ); 
                            ?>
                        </p>
                    </div>
                    <!-- Button area -->
                    <div style="background: #f0f0f1; padding: 20px 30px; text-align: right;">
                        <a href="<?php echo esc_url($dashboard_url); ?>" 
                           class="button button-primary"
                           style="background: #fff; border: 2px solid #191970; color: #191970; font-size: 13px; font-weight: 600; padding: 8px 24px; height: auto; line-height: 1.4; box-shadow: none; text-shadow: none; border-radius: 3px; text-decoration: none;">
                            <?php esc_html_e('GO TO DASHBOARD', 'vmpfence-security'); ?>
                        </a>
                    </div>
                </div>
            </div>
            <style>
            @keyframes vmpfenceFadeIn { from { opacity: 0; } to { opacity: 1; } }
            @keyframes vmpfenceSlideUp { from { transform: translateY(30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
            #vmpfence-license-result-overlay { position:fixed; top:32px; left:160px; right:0; bottom:0; background:rgba(0,0,0,0.5); z-index:100001; display:flex; align-items:center; justify-content:center; }
            @media screen and (max-width:782px) { #vmpfence-license-result-overlay { top:46px; left:0; } }
            .folded #vmpfence-license-result-overlay { left:36px; }
            </style>
            <?php
            return;
        }
        
        // Check for error modal
        $error_message = get_transient('vmpfence_setup_error_modal');
        if ($error_message) {
            delete_transient('vmpfence_setup_error_modal');
            ?>
            <div id="vmpfence-license-result-overlay" style="animation: vmpfenceFadeIn 0.3s ease-in-out;">
                <div style="background: #fff; max-width: 500px; width: 100%; border-radius: 2px; box-shadow: 0 3px 30px rgba(0,0,0,0.3); animation: vmpfenceSlideUp 0.3s ease-out;">
                    <h2 style="margin: 0; font-size: 20px; font-weight: 600; color: #1d2327; padding: 16px 20px; border-bottom: 1px solid #dcdcde;">
                        <?php esc_html_e('Error Installing License', 'vmpfence-security'); ?>
                    </h2>
                    <div style="padding: 20px;">
                        <p style="margin: 0 0 16px; color: #1d2327; font-size: 13px; line-height: 1.6;">
                            <?php 
                            printf(
                                /* translators: %s: error message from the API */
                                esc_html__('We received an error while trying to activate the license with the VMP Security servers: %s', 'vmpfence-security'),
                                esc_html($error_message)
                            ); 
                            ?>
                        </p>
                        <p style="margin: 0; color: #1d2327; font-size: 13px; line-height: 1.6;">
                            <?php 
                            printf(
                                /* translators: %1$s: opening anchor tag, %2$s: closing anchor tag */
                                esc_html__('Please try again. If the problem persists, please %1$scontact VMP Security Support%2$s.', 'vmpfence-security'),
                                '<a href="https://vmpsecurity.com/support/" target="_blank" style="color: #0073aa; text-decoration: underline;">',
                                '</a>'
                            ); 
                            ?>
                        </p>
                    </div>
                    <div style="padding: 12px 20px; border-top: 1px solid #dcdcde; text-align: right;">
                        <button type="button" id="vmpfence-error-modal-close" 
                                class="button button-primary"
                                style="background: #191970; border-color: #191970; color: #fff; font-size: 13px; font-weight: 600; padding: 6px 20px; height: auto; line-height: 1.5; box-shadow: none; text-shadow: none;">
                            <?php esc_html_e('CLOSE', 'vmpfence-security'); ?>
                        </button>
                    </div>
                </div>
            </div>
            <style>
            @keyframes vmpfenceFadeIn { from { opacity: 0; } to { opacity: 1; } }
            @keyframes vmpfenceSlideUp { from { transform: translateY(30px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
            #vmpfence-license-result-overlay { position:fixed; top:32px; left:160px; right:0; bottom:0; background:rgba(0,0,0,0.5); z-index:100001; display:flex; align-items:center; justify-content:center; }
            @media screen and (max-width:782px) { #vmpfence-license-result-overlay { top:46px; left:0; } }
            .folded #vmpfence-license-result-overlay { left:36px; }
            </style>
            <script>
            jQuery(document).ready(function($) {
                $('#vmpfence-error-modal-close').on('click', function() {
                    $('#vmpfence-license-result-overlay').fadeOut(300, function() {
                        $(this).remove();
                    });
                });
                // Also close on overlay click
                $('#vmpfence-license-result-overlay').on('click', function(e) {
                    if (e.target === this) {
                        $(this).fadeOut(300, function() { $(this).remove(); });
                    }
                });
            });
            </script>
            <?php
        }
    }
    
    /**
     * Handle AJAX dismissal of activation modal
     * @since 2.2.2
     */
    public static function ajax_dismiss_activation_modal() {
        check_ajax_referer('vmpfence_dismiss_activation_modal', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die();
        }
        
        // Clear the transient and set permanent dismissal flag
        delete_transient('vmpfence_show_activation_modal');
        update_user_meta(get_current_user_id(), 'vmpfence_dismissed_activation_modal', true);
        wp_send_json_success();
    }
    
    /**
     * Handle AJAX dismissal of plugins page license card
     * @since 2.2.4
     */
    public static function ajax_dismiss_plugins_card() {
        check_ajax_referer('vmpfence_dismiss_plugins_card', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die();
        }
        
        update_user_meta(get_current_user_id(), 'vmpfence_dismissed_plugins_card', true);
        wp_send_json_success();
    }
    
    /**
     * Handle AJAX reminder dismissal (12 hour snooze)
     * @since 2.2.4
     */
    public static function ajax_remind_later() {
        check_ajax_referer('vmpfence_remind_later', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die();
        }
        
        update_user_meta(get_current_user_id(), 'vmpfence_setup_remind_time', time());
        wp_send_json_success();
    }
}

// Initialize setup wizard
VMPFence_Setup_Wizard::init();