<?php
/*
 *	Plugin Name: FormShield
 *	Plugin URI: https://wpsupporting.com/plugins/formshield/
 *	Description: FormShield е мощен плъгин за защита на формуляри, който използва разширени шаблони и поведенчески анализ за борба със спам и ботове. Включва проследяване на местоположението на формите и интеграция с 14+ form плагина.
 *	Version: 1.2.0
 *	Author: wpsupporting
 *	Author URI: https://wpsupporting.com/
 *  Text Domain: formshield
 *  Domain Path: /languages
 *	License: GPL2
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

// Get plugin directory and basename
$formshield_plugin_dir = plugin_dir_path(__FILE__);
$formshield_basename = plugin_basename(__FILE__);

// Include sanitizer helpers
if (file_exists($formshield_plugin_dir . 'includes/sanitizers.php')) {
	require_once $formshield_plugin_dir . 'includes/sanitizers.php';
}

// Include safe HTML helper
if (file_exists($formshield_plugin_dir . 'classes/class-formshield-safe.php')) {
	require_once $formshield_plugin_dir . 'classes/class-formshield-safe.php';
}

// Define plugin constants
if (!defined('FORMSHIELD_VERSION')) {
    define('FORMSHIELD_VERSION', '1.2.0');
}

if (!defined('FORMSHIELD_PARTNER')) {
    define('FORMSHIELD_PARTNER', '');
}

if (!defined('FORMSHIELD_LOG_LIMIT')) {
    define('FORMSHIELD_LOG_LIMIT', 100);
}

/** Divi 4/5 integration: true = disabled (forms not shown as protected). Set to false when stable. */
if (!defined('FORMSHIELD_DIVI_IN_DEVELOPMENT')) {
    define('FORMSHIELD_DIVI_IN_DEVELOPMENT', true);
}

if (!class_exists('FormShield')) {

    final class FormShield {
        private static $instance;
        private $version = '1.2.0';
        public $settings;
        public $file;
        public $basename;
        public $plugin_dir;
        public $plugin_url;
        public $admin_url;
        public $menu_slug = 'formshield';

        public static function get_instance() {
            if (!isset(self::$instance) && !(self::$instance instanceof FormShield)) {
                self::$instance = new FormShield;
                self::$instance->init();
            }
            return self::$instance;
        }

        public function init() {
            $this->setup_constants();
            $this->_include_files();
            $this->_settings();
            $this->_hooks();
            $this->_activation_hooks();
            $this->_load_textdomain();
        }

        private function setup_constants() {
            // Plugin version
            if (!defined('FORMSHIELD_VERSION')) {
                define('FORMSHIELD_VERSION', $this->version);
            }

            // Plugin file
            self::$instance->file = __FILE__;
            self::$instance->basename = plugin_basename(self::$instance->file);
            self::$instance->plugin_dir = plugin_dir_path(self::$instance->file);
            self::$instance->plugin_url = plugin_dir_url(self::$instance->file);
            self::$instance->admin_url = admin_url('admin.php?page=' . self::$instance->menu_slug);
        }

        private function _include_files() {
            // Verify plugin directory exists before including files
            if (empty(self::$instance->plugin_dir) || !file_exists(self::$instance->plugin_dir)) {
                // Log error but don't stop plugin loading completely
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('FormShield: Plugin directory not found: ' . self::$instance->plugin_dir);
                }
                return; // Prevent fatal errors if directory doesn't exist
            }
            
            $required_files = array(
                'classes/class-formshield-utils.php',
                'classes/class-formshield-protected-forms-list-table.php',
                'classes/class-formshield-settings.php',
                'classes/class-formshield-auto-protect.php',
                'classes/class-formshield-forms.php',
                'classes/class-formshield-form-detector.php',
                'classes/class-formshield-advanced-protection.php',
                'classes/class-formshield-advanced-logging.php',
                'classes/class-formshield-spam-protection.php',
                'classes/class-formshield-email-notifications.php',
                'classes/class-formshield-ip-whitelist.php',
                'classes/class-integration.php',
                'integrations/wordpress-comments.php',
            );
            
            foreach ($required_files as $file) {
                $file_path = self::$instance->plugin_dir . $file;
                if (file_exists($file_path)) {
                    require_once($file_path);
                }
            }
            
            // Optional integration files
            $optional_files = array(
                'integrations/ninja-forms.php',
                'integrations/formidable-forms.php',
                'integrations/gravity-forms.php',
                'integrations/contact-form-7-forms.php',
                'integrations/ws-form.php',
                'integrations/we-forms.php',
                'integrations/quform-forms.php',
                'integrations/fluent-forms.php',
                'integrations/wp-forms.php',
                'integrations/elementor-forms.php',
                'integrations/happy-forms.php',
                'integrations/divi-forms.php',
            );
            
            foreach ($optional_files as $file) {
                $file_path = self::$instance->plugin_dir . $file;
                if (file_exists($file_path)) {
                    include_once($file_path);
                }
            }
        }

        public function _settings() {
            self::$instance->settings = new FormShieldSettings();
        }

        private function _activation_hooks() {
            // Деактивирай стария плъгин ако съществува
            if (is_plugin_active('ellipsis-human-presence-technology/wp-human-presence.php')) {
                deactivate_plugins('ellipsis-human-presence-technology/wp-human-presence.php');
            }

            register_activation_hook(__FILE__, array(__CLASS__, 'activate'));
            register_deactivation_hook(__FILE__, array(__CLASS__, 'deactivate'));
            register_uninstall_hook(__FILE__, array(__CLASS__, 'uninstall'));
        }

        private function _load_textdomain() {
            // WordPress will automatically load translations for plugins hosted on WordPress.org
            // No need to manually call load_plugin_textdomain() since WordPress 4.6
        }

        		private function _hooks() {
			add_action('admin_menu', array(self::$instance, 'menu'));
			add_filter('plugin_action_links_' . self::$instance->basename, array(self::$instance, 'settings_link'));
			add_action('wp_ajax_formshield_record_activity', array('FormShieldForms', 'record_suspicious_activity_ajax'));
			add_action('wp_ajax_nopriv_formshield_record_activity', array('FormShieldForms', 'record_suspicious_activity_ajax'));
			
			// AJAX handler for validation logging
			add_action('wp_ajax_formshield_log_validation', array($this, 'ajax_log_validation'));
			add_action('wp_ajax_nopriv_formshield_log_validation', array($this, 'ajax_log_validation'));
			
			// Auto-save settings AJAX handler
			add_action('wp_ajax_formshield_auto_save_setting', array(self::$instance, 'auto_save_setting'));
			
			// Enqueue admin scripts
			add_action('admin_enqueue_scripts', array(self::$instance, 'enqueue_admin_scripts'));
            
            // REST API endpoints за Divi детекция
            add_action('rest_api_init', array($this, 'register_rest_routes'));
            
            // WP-CLI команди
            if (defined('WP_CLI') && WP_CLI) {
                WP_CLI::add_command('divi:detect-contact-form', array('FormShieldFormDetector', 'cli_detect'));
            }
            
            // AJAX handler за Divi rescan
            add_action('wp_ajax_formshield_rescan_divi', array($this, 'ajax_rescan_divi'));
            
            // AJAX handler за сканиране на всички форми
            add_action('wp_ajax_formshield_scan_all_forms', array($this, 'ajax_scan_all_forms'));
            
            // AJAX handler за обновяване на защитените форми
            add_action('wp_ajax_formshield_update_protected_forms', array($this, 'ajax_update_protected_forms'));
            

            
            // AJAX handler за включване/изключване на защитата
            add_action('wp_ajax_formshield_toggle_protection', array($this, 'ajax_toggle_protection'));
            
            // AJAX handler за запазване на промените в toggle-овете
            add_action('wp_ajax_formshield_save_toggle_changes', array($this, 'ajax_save_toggle_changes'));
        add_action('wp_ajax_formshield_get_form_stats', array($this, 'ajax_get_form_stats'));
            
            // AJAX handler за повторно сканиране на форми
            add_action('wp_ajax_formsh_rescan_forms', array($this, 'ajax_rescan_forms'));
            
            // Регистрирай CSS файла
            add_action('admin_enqueue_scripts', function($hook) {
                if (strpos($hook, 'formshield') !== false) {
                    wp_enqueue_style('formshield-admin', plugins_url('css/formshield.css', __FILE__), array(), FORMSHIELD_VERSION);
                }
            });
            
            // Enqueue frontend scripts and styles
            add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
            add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_styles'));
        }

        public function menu() {
            // Ensure we have proper instance
            if (!isset($this->menu_slug) || empty($this->menu_slug)) {
                $this->menu_slug = 'formshield';
            }
            
            add_menu_page(
                __('FormShield', 'formshield'),
                __('FormShield', 'formshield'),
                'manage_options',
                $this->menu_slug,
                array($this, 'options_page'),
                'dashicons-shield'
            );

            add_submenu_page(
                $this->menu_slug,
                __('FormShield', 'formshield'),
                __('FormShield', 'formshield'),
                'manage_options',
                $this->menu_slug,
                array($this, 'options_page')
            );

            add_submenu_page(
                $this->menu_slug,
                __('Settings', 'formshield'),
                __('Settings', 'formshield'),
                'manage_options',
                $this->menu_slug . '-settings',
                array($this, 'settings_page')
            );

            add_submenu_page(
                $this->menu_slug,
                __('About', 'formshield'),
                __('About', 'formshield'),
                'manage_options',
                $this->menu_slug . '-about',
                array($this, 'about_page')
            );
        }

        public function options_page() {
            include_once(self::$instance->plugin_dir . 'templates/protected-forms-table.php');
        }

        public function about_page() {
            include_once(self::$instance->plugin_dir . 'templates/about-page.php');
        }

        public function settings_page() {
            include_once(self::$instance->plugin_dir . 'templates/settings-page.php');
        }

        public function protected_forms_page() {
            include_once(self::$instance->plugin_dir . 'templates/protected-forms-table.php');
        }

        public function settings_link($links) {
            // Only add Settings link if user has proper capabilities
            if (!current_user_can('manage_options')) {
                return $links;
            }
            
            // Add Settings link pointing to Settings page
            $settings_url = admin_url('admin.php?page=' . $this->menu_slug . '-settings');
            $settings_link = '<a href="' . esc_url($settings_url) . '">' . esc_html__('Настройки', 'formshield') . '</a>';
            array_unshift($links, $settings_link);
            return $links;
        }

        public static function get_default_options() {
            return array(
                'blocked_attempts' => 0,
                'last_attack' => '',
                'attack_types' => array(
                    'spam' => 0,
                    'bot' => 0,
                    'injection' => 0,
                    'other' => 0
                ),
                'settings' => array(
                    'protection_level' => 'medium', // low, medium, high
                    'auto_protect' => true,
                    'notify_admin' => true,
                    'is_premium' => false
                ),
                'formshield_forms' => array(),
                'detected_forms' => array()
            );
        }

        public static function get_options() {
            $options = get_option('formshield_options', array());
            
            // Ако няма опции, върни default
            if (empty($options)) {
                return self::get_default_options();
            }
            
            // Слей само настройките, не и формите
            $default = self::get_default_options();
            
            // Запази formshield_forms и detected_forms
            $forms = isset($options['formshield_forms']) ? $options['formshield_forms'] : array();
            $detected = isset($options['detected_forms']) ? $options['detected_forms'] : array();
            
            // Слей останалите опции
            $options = array_merge($default, $options);
            
            // Възстанови формите
            $options['formshield_forms'] = $forms;
            $options['detected_forms'] = $detected;
            
            return $options;
        }

        public static function update_options($options) {
            update_option('formshield_options', $options);
            return $options;
        }

        public static function activate() {
            // Мигрирай настройките от стария плъгин
            $old_options = get_option('wp-human-presence');
            if ($old_options) {
                update_option('formshield_options', self::get_default_options());
                delete_option('wp-human-presence');
            }

            // Създай/обнови activity log таблицата при активиране
            if (class_exists('FormShieldAdvancedLogging')) {
                FormShieldAdvancedLogging::get_instance()->maybe_create_log_table();
            }

            // Автоматично сканирай сайта за форми
            if (class_exists('FormShieldFormDetector')) {
                FormShieldFormDetector::auto_scan_on_activation();
            }

            // Обнови версията
            update_option('formshield_version', FORMSHIELD_VERSION);
        }

        public static function deactivate() {
            // Cleanup code here
        }

        public static function uninstall() {
            global $wpdb;

            delete_option('formshield_options');
            delete_option('formshield_version');
            delete_option('formshield_ip_blacklist');
            delete_option('formshield_db_version');

            $table = $wpdb->prefix . 'formshield_activity_log';
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query( "DROP TABLE IF EXISTS {$table}" );
        }

        /**
         * Check if using community version (always true for free version)
         * 
         * @return boolean
         */
        public static function is_community_static() {
            return true;
        }

        /**
         * Check if using premium version (always false for free version)
         * 
         * @return boolean
         */
        public static function is_premium_static() {
            return false;
        }

        /**
         * Instance method for checking community version
         * 
         * @return boolean
         */
        public function is_community() {
            return self::is_community_static();
        }

        /**
         * Instance method for checking premium version (always false for free version)
         * 
         * @return boolean
         */
        public function is_premium() {
            return false;
        }
        
        /**
         * Check if current user should see the protected badge
         * 
         * @return boolean
         */
        public static function should_show_badge() {
            // Показвай badge само за логнати администратори
            if (!is_user_logged_in() || !current_user_can('manage_options')) {
                return false;
            }
            
            // Винаги показвай badge за администратори (коментари и скенер винаги са активни)
            return true;
        }
        
        /**
         * Generate protected badge HTML
         * 
         * @param string $form_name Optional form name for context
         * @return string HTML for the badge
         */
        public static function badge_html($form_name = '') {
            if (!self::should_show_badge()) {
                return '';
            }
            
            // Get badge text based on form type - using translation functions
            $default_text = __('🛡️ Тази форма е защитена от FormShield - видима само за администратори', 'formshield');
            
            if ($form_name === 'Contact Form 7') {
                $default_text = __('📧 Contact Form 7 защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'WordPress Comments') {
                $default_text = __('💬 Коментарите са защитени от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'Divi Contact Form') {
                $default_text = __('🎨 Divi форма защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'Ninja Forms') {
                $default_text = __('🥷 Ninja Forms защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'WPForms') {
                $default_text = __('📝 WPForms защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'Gravity Forms') {
                $default_text = __('⚡ Gravity Forms защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'Elementor Forms') {
                $default_text = __('🎨 Elementor Forms защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'Fluent Forms') {
                $default_text = __('💧 Fluent Forms защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'Formidable Forms') {
                $default_text = __('💪 Formidable Forms защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'Happy Forms') {
                $default_text = __('😊 Happy Forms защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'Quform') {
                $default_text = __('❓ Quform защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'WeForms') {
                $default_text = __('👥 WeForms защитена от FormShield - видима само за администратори', 'formshield');
            } elseif ($form_name === 'WS Form') {
                $default_text = __('🌐 WS Form защитена от FormShield - видима само за администратори', 'formshield');
            }
            
            // Get badge text from filter with more descriptive text
            $badge_text = apply_filters('formshield_badge_text', $default_text, $form_name);
            
            // Generate unique ID for this badge instance
            $badge_id = 'formshield-badge-' . uniqid();
            
            // Translate subtitle text
            $badge_subtitle = __('Защита от спам, ботове и злонамерени атаки', 'formshield');
            
            $html = sprintf(
                '<div id="%s" class="formshield-protected-badge"><div class="formshield-badge-content"><div class="formshield-badge-main">%s</div><div class="formshield-badge-sub">%s</div></div></div>',
                esc_attr($badge_id),
                esc_html($badge_text),
                esc_html($badge_subtitle)
            );
            
            return $html;
        }
        
        /**
         * Check session for human presence validation
         * 
         * @return array|false
         */
        /**
         * Kept for backward compatibility only. No longer used for blocking.
         * Bot detection is now handled via honeypot + content analysis in FormShieldForms.
         *
         * @return array
         */
        public function check_session() {
            return array( 'signal' => 'CLEAN', 'confidence' => 100 );
        }
        
        /**
         * Регистрира REST API routes
         */
        public function register_rest_routes() {
            register_rest_route('formshield/v1', '/has-form', array(
                array(
                    'methods' => WP_REST_Server::READABLE,
                    'callback' => array('FormShieldFormDetector', 'rest_has_form'),
                    'permission_callback' => '__return_true',
                    'args' => array(
                        'url' => array(
                            'type' => 'string',
                            'required' => true,
                            'validate_callback' => function( $param ) {
                                return (bool) wp_http_validate_url( $param );
                            },
                            'sanitize_callback' => 'esc_url_raw',
                        ),
                    ),
                ),
            ));
            
            register_rest_route('formshield/v1', '/locations', array(
                array(
                    'methods' => WP_REST_Server::READABLE,
                    'callback' => array('FormShieldFormDetector', 'rest_locations'),
                    'permission_callback' => '__return_true', // публичен по замисъл
                    'args' => array(
                        'url' => array(
                            'type' => 'string',
                            'required' => false,
                            'validate_callback' => function( $param ) {
                                return empty( $param ) || (bool) wp_http_validate_url( $param );
                            },
                            'sanitize_callback' => 'esc_url_raw',
                        ),
                    ),
                ),
            ));
        }
        
        /**
         * AJAX handler за Divi rescan
         */
        public function ajax_rescan_divi() {
            formshield_verify_nonce_or_bail('formshield_rescan_divi');
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'formshield' ) ), 403 );
            }
            
            // Стартираме rescan
            $result = FormShieldFormDetector::admin_rescan();
            
            if ($result['success']) {
                wp_send_json_success(array(
                    'forms_found' => $result['forms_found'],
                    'message' => $result['message'],
                    'forms' => FormShieldFormDetector::dcd_find_divi_forms()
                ));
            } else {
                wp_send_json_error(array('message' => $result['message']));
            }
        }
        
        		/**
		 * Enqueue admin scripts and styles
		 */
		public function enqueue_admin_scripts($hook) {
			// Only load on FormShield admin pages
			if (strpos($hook, 'formshield') === false) {
				return;
			}
			
			wp_enqueue_script(
				'formshield-admin',
				$this->plugin_url . 'js/ajax-settings.js',
				array('jquery'),
				$this->version,
				true
			);
			
			// Localize script with AJAX URL and nonce
			wp_localize_script('formshield-admin', 'ajaxConfig', array(
				'url' => admin_url('admin-ajax.php'),
				'nonce' => wp_create_nonce('formshield_form_enabled_change'),
				'rescanNonce' => wp_create_nonce('formsh_rescan_forms'),
				'toggleNonce' => wp_create_nonce('formshield_toggle_protection'),
				'autoSaveNonce' => wp_create_nonce('formshield_auto_save'),
				'saveToggleNonce' => wp_create_nonce('formshield_save_toggle_changes'),
				'isPremium' => false,
				'protectedFormsCt' => 0 // TODO: Get actual count
			));
		}
		
		/**
		 * Enqueue frontend scripts and styles
		 */
	public function enqueue_frontend_scripts() {
		// Enqueue CSS for badge styling
		wp_enqueue_style(
			'formshield-frontend',
			$this->plugin_url . 'css/formshield.css',
			array(),
			$this->version
		);
		
		// Enqueue protection script
		wp_enqueue_script(
			'formshield-protection',
			$this->plugin_url . 'js/formshield-protection.js',
			array('jquery'),
			$this->version,
			true
		);
		
		// Localize script with AJAX data
		wp_localize_script('formshield-protection', 'formshieldData', array(
			'ajaxurl' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce('formshield_protection'),
	
			'isLoggedIn' => is_user_logged_in(),
			'isAdmin' => current_user_can('manage_options')
		));
	}

		/**
		 * Enqueue frontend styles for protected badges
		 */
		public function enqueue_frontend_styles() {
			// Always enqueue styles, but only show badges to allowed users
			// Add inline CSS for protected badges
			$css = '
			.formshield-protected-badge {
				display: inline-block !important;
				background: linear-gradient(135deg, #2563EB 0%, #1D4ED8 100%) !important;
				color: white !important;
				font-size: 14px !important;
				font-weight: 500 !important;
				padding: 12px 16px !important;
				border-radius: 8px !important;
				margin: 16px 0 !important;
				font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
				line-height: 1.4 !important;
				vertical-align: middle !important;
				opacity: 0.9 !important;
				transition: all 0.3s ease !important;
				box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3) !important;
				border: 1px solid rgba(255, 255, 255, 0.2) !important;
				text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;
				max-width: 100% !important;
			}
			
			.formshield-badge-content {
				text-align: center !important;
			}
			
			.formshield-badge-main {
				font-size: 14px !important;
				font-weight: 600 !important;
				margin-bottom: 4px !important;
			}
			
			.formshield-badge-sub {
				font-size: 12px !important;
				font-weight: 400 !important;
				opacity: 0.9 !important;
				font-style: italic !important;
			}
			
			.formshield-protected-badge:hover {
				opacity: 1 !important;
				transform: translateY(-1px) !important;
				box-shadow: 0 4px 12px rgba(37, 99, 235, 0.4) !important;
			}
			
			/* Ensure badge doesn\'t interfere with form layout */
			.wpcf7-form + .formshield-protected-badge,
			.et_pb_contact_form + .formshield-protected-badge,
			.comment-form + .formshield-protected-badge {
				display: block !important;
				margin-top: 20px !important;
				text-align: center !important;
			}
			';
			
		// Always add CSS to head
		add_action('wp_head', function() use ($css) {
			wp_enqueue_style( 'formshield-frontend', plugins_url( 'css/formshield.css', __FILE__ ), array(), FORMSHIELD_VERSION );
			if ( ! empty( $css ) ) {
				$sanitized_css = wp_strip_all_tags( $css );
				wp_add_inline_style( 'formshield-frontend', $sanitized_css );
			}
		});
		}

		/**
		 * AJAX handler за сканиране на всички форми
		 */
		public function ajax_scan_all_forms() {
            formshield_verify_nonce_or_bail('formshield_scan_all');
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'formshield' ) ), 403 );
            }
            
            // Стартираме сканиране на всички форми
            $forms = FormShieldFormDetector::scan_site_for_forms();
            
            wp_send_json_success(array(
                'forms_found' => count($forms),
                'message' => 'Scan completed successfully',
                'forms' => $forms
            ));
        }
        
        /**
         * AJAX handler за обновяване на защитените форми
         */
        public function ajax_update_protected_forms() {
            formshield_verify_nonce_or_bail('formshield_update_protected');
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'formshield' ) ), 403 );
            }
            
            // Обновяваме защитените форми
            $options = $this->get_options();
            $forms = FormShieldForms::get_forms();
            
            $updated_count = 0;
            foreach ($forms as $form) {
                if (!isset($options['protected_forms'][$form['id']])) {
                    $options['protected_forms'][$form['id']] = array(
                        'enabled' => 1,
                        'protected_at' => current_time('mysql')
                    );
                    $updated_count++;
                }
            }
            
            update_option('formshield_options', $options);
            
            wp_send_json_success(array(
                'message' => "Updated $updated_count forms to protected status"
            ));
        }


        
        /**
         * AJAX handler за включване/изключване на защитата
         */
        public function ajax_toggle_protection() {
            formshield_verify_nonce_or_bail('formshield_toggle_protection');
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'formshield' ) ), 403 );
            }
            
            $form_id = formshield_get_post_string('form_id');
            if (!$form_id) {
                wp_send_json_error(array('message' => 'Invalid form ID'));
                return;
            }
            
            // Вземаме текущите опции
            $options = $this->get_options();
            
            // Проверяваме дали формата съществува
            if (!isset($options['protected_forms'][$form_id])) {
                wp_send_json_error(array('message' => 'Form not found'));
                return;
            }
            
            // Превключваме статуса
            $current_status = $options['protected_forms'][$form_id]['enabled'];
            $new_status = $current_status ? 0 : 1;
            
            $options['protected_forms'][$form_id]['enabled'] = $new_status;
            $options['protected_forms'][$form_id]['updated_at'] = current_time('mysql');
            
            // Запазваме опциите
            update_option('formshield_options', $options);
            
            wp_send_json_success(array(
                'enabled' => $new_status,
                'message' => $new_status ? 'Protection enabled' : 'Protection disabled'
            ));
        }
        
        /**
         * AJAX handler за получаване на статистика за форма
         */
        public function ajax_get_form_stats() {
            // Verify nonce
            $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
            if (!wp_verify_nonce($nonce, 'formshield_protection')) {
                wp_send_json_error(array('message' => 'Invalid nonce'));
                return;
            }
            
            $form_id = isset($_POST['form_id']) ? sanitize_text_field(wp_unslash($_POST['form_id'])) : '';
            if (empty($form_id)) {
                wp_send_json_error(array('message' => 'Form ID is required'));
                return;
            }
            
            $options = FormShield::get_options();
            
            // Get form-specific statistics
            $stats = array(
                'blocked_attempts' => 0,
                'total_submissions' => 0,
                'human_submissions' => 0,
                'suspicious_submissions' => 0,
                'last_activity' => '',
                'last_attack' => ''
            );
            
            // Get form-specific blocked attempts
            if (isset($options['formshield_forms'][$form_id]['blocked_attempts'])) {
                $stats['blocked_attempts'] = intval($options['formshield_forms'][$form_id]['blocked_attempts']);
            }
            
            // Get form-specific submission data
            if (isset($options['formshield_forms'][$form_id]['total_submissions'])) {
                $stats['total_submissions'] = intval($options['formshield_forms'][$form_id]['total_submissions']);
            }
            if (isset($options['formshield_forms'][$form_id]['human_submissions'])) {
                $stats['human_submissions'] = intval($options['formshield_forms'][$form_id]['human_submissions']);
            }
            if (isset($options['formshield_forms'][$form_id]['suspicious_submissions'])) {
                $stats['suspicious_submissions'] = intval($options['formshield_forms'][$form_id]['suspicious_submissions']);
            }
            
            // Get last activity
            if (isset($options['formshield_forms'][$form_id]['last_activity'])) {
                $stats['last_activity'] = $options['formshield_forms'][$form_id]['last_activity'];
            }
            
            // Get last attack
            if (isset($options['formshield_forms'][$form_id]['last_attack'])) {
                $stats['last_attack'] = $options['formshield_forms'][$form_id]['last_attack'];
            }
            
            wp_send_json_success($stats);
        }

        /**
         * AJAX handler за запазване на промените в toggle-овете
         */
        public function ajax_save_toggle_changes() {
            formshield_verify_nonce_or_bail('formshield_save_toggle_changes');
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'formshield' ) ), 403 );
            }
            
            $raw_changes = isset($_POST['changes']) ? wp_unslash($_POST['changes']) : '';
            $changes = is_string($raw_changes) ? json_decode($raw_changes, true) : array();
            
            if (empty($changes) || !is_array($changes)) {
                wp_send_json_error(array('message' => 'No changes provided'));
                return;
            }

            if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                error_log( '[FormShield DEBUG] ajax_save_toggle_changes incoming: ' . wp_json_encode( $changes ) );
            }
            
            // Вземаме текущите опции
            $options = $this->get_options();
            
            $updated_count = 0;
            foreach ($changes as $form_id_raw => $enabled) {
                // Keep form IDs intact (including encoded slugs) and only strip invalid UTF-8.
                $form_id = trim( wp_check_invalid_utf8( (string) $form_id_raw ) );
                if ( '' === $form_id ) {
                    continue;
                }

                $normalized_enabled = filter_var($enabled, FILTER_VALIDATE_BOOLEAN) ? 1 : 0;
                // Проверяваме дали формата съществува в опциите
                if (isset($options['formshield_forms'][$form_id])) {
                    $options['formshield_forms'][$form_id]['form_enabled'] = $normalized_enabled;
                    $options['formshield_forms'][$form_id]['updated_at'] = current_time('mysql');
                    $updated_count++;
                } else {
                    // Try to create the form entry if it doesn't exist
                    if (!isset($options['formshield_forms'])) {
                        $options['formshield_forms'] = array();
                    }
                    $options['formshield_forms'][$form_id] = array(
                        'form_enabled' => $normalized_enabled,
                        'updated_at' => current_time('mysql'),
                        'created_at' => current_time('mysql')
                    );
                    $updated_count++;
                }

                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                    error_log(
                        sprintf(
                            '[FormShield DEBUG] ajax_save_toggle_changes saved form_id=%s enabled=%d has_key_after_save=%s',
                            (string) $form_id,
                            (int) $normalized_enabled,
                            isset( $options['formshield_forms'][ $form_id ] ) ? 'yes' : 'no'
                        )
                    );
                }
            }

            if ( ! isset( $options['formshield_forms'] ) || ! is_array( $options['formshield_forms'] ) ) {
                $options['formshield_forms'] = array();
            }
            
            // Запазваме опциите
            update_option('formshield_options', $options);

            if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                $saved_options = get_option( 'formshield_options', array() );
                $cf7_keys = array();
                if ( isset( $saved_options['formshield_forms'] ) && is_array( $saved_options['formshield_forms'] ) ) {
                    foreach ( array_keys( $saved_options['formshield_forms'] ) as $saved_key ) {
                        if ( strpos( (string) $saved_key, 'cf7-' ) === 0 ) {
                            $cf7_keys[] = (string) $saved_key;
                        }
                    }
                }
                error_log( '[FormShield DEBUG] ajax_save_toggle_changes persisted cf7 keys: ' . implode( ', ', $cf7_keys ) );
            }
            
            wp_send_json_success(array(
                'message' => "Updated $updated_count forms",
                'updated_count' => $updated_count
            ));
        }
        
        /**
         * AJAX handler за повторно сканиране на форми
         */
        public function ajax_rescan_forms() {
            formshield_verify_nonce_or_bail('formsh_rescan_forms');
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'formshield' ) ), 403 );
            }
            
            // Стартираме повторно сканиране на всички форми
            $forms = FormShieldFormDetector::scan_site_for_forms();
            
            wp_send_json_success(array(
                'forms_found' => count($forms),
                'message' => 'Rescan completed successfully',
                'forms' => $forms
            ));
        }

        /**
         * AJAX handler for validation logging
         */
        public function ajax_log_validation() {
            if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'formshield_protection')) {
                wp_send_json_error(array('message' => 'Invalid nonce'));
                return;
            }

            // Rate-limit nopriv callers: max 30 requests per IP per hour.
            if ( ! is_user_logged_in() ) {
                $ip       = formshield_get_validated_ip('unknown');
                $rate_key = 'formshield_log_rate_' . md5( $ip );
                $count    = (int) get_transient( $rate_key );
                if ( $count >= 30 ) {
                    wp_send_json_error( array( 'message' => 'Rate limit exceeded.' ), 429 );
                    return;
                }
                set_transient( $rate_key, $count + 1, HOUR_IN_SECONDS );
            }
            
            // Get log data
            $log_data = isset($_POST['log_data']) ? json_decode(sanitize_text_field(wp_unslash($_POST['log_data'])), true) : array();
            
            if (empty($log_data)) {
                wp_send_json_error(array('message' => 'No log data provided'));
                return;
            }
            
            // Log the validation attempt
            $this->log_validation_attempt($log_data);
            
            wp_send_json_success(array('message' => 'Validation logged successfully'));
        }
        
        /**
         * Log validation attempt
         */
        private function log_validation_attempt($log_data) {
            // Store in options for now (can be moved to custom table later)
            $options = get_option('formshield_options', array());
            
            if (!isset($options['validation_logs'])) {
                $options['validation_logs'] = array();
            }
            
            // Add new log entry
            $options['validation_logs'][] = array(
                'timestamp' => current_time('mysql'),
                'form_id' => isset($log_data['formId']) ? sanitize_text_field($log_data['formId']) : 'unknown',
                'validation_result' => isset($log_data['validationResult']) ? $log_data['validationResult'] : array(),
                'user_agent' => isset($log_data['userAgent']) ? sanitize_text_field($log_data['userAgent']) : '',
                'screen_resolution' => isset($log_data['screenResolution']) ? sanitize_text_field($log_data['screenResolution']) : '',
                'time_zone' => isset($log_data['timeZone']) ? sanitize_text_field($log_data['timeZone']) : ''
            );
            
            // Keep only last 100 entries
            if (count($options['validation_logs']) > 100) {
                $options['validation_logs'] = array_slice($options['validation_logs'], -100);
            }
            
            update_option('formshield_options', $options);
        }

        /**
         * Disable comments on all existing content
         */
        private static function disable_comments_on_all_content() {
            global $wpdb;
            
            // Close comments on all posts
            $wpdb->query("UPDATE {$wpdb->posts} SET comment_status = 'closed', ping_status = 'closed' WHERE post_status = 'publish'");
            
            // Also close for future posts
            update_option('default_comment_status', 'closed');
            update_option('default_ping_status', 'closed');
        }
        
        /**
         * Auto-save settings via AJAX
         */
        public function auto_save_setting() {
            // Verify nonce
            formshield_verify_nonce_or_bail('formshield_auto_save');

            // Check user permissions
            if (!current_user_can('manage_options')) {
                wp_die('Insufficient permissions');
            }

            $setting_name = formshield_get_post_string('setting_name');
            $setting_value = formshield_get_post_string('setting_value');
            
            // Handle boolean values properly
            if ($setting_value === 'true' || $setting_value === '1') {
                $setting_value = true;
            } elseif ($setting_value === 'false' || $setting_value === '0' || $setting_value === '') {
                $setting_value = false;
            } else {
                $setting_value = sanitize_text_field($setting_value);
            }

            // Handle different setting types
            $options = get_option('formshield_options', array());

            switch ($setting_name) {
                case 'admin_email':
                case 'email':
                    $options['admin_email'] = sanitize_email($setting_value);
                    break;
                case 'attack_notifications':
                    $options['attack_notifications'] = (bool) $setting_value;
                    break;
                case 'form_detection_notifications':
                    $options['form_detection_notifications'] = (bool) $setting_value;
                    break;
                case 'periodic_reports':
                    $options['periodic_reports'] = (bool) $setting_value;
                    break;
                case 'protection_level':
                    $allowed_levels = array('low', 'medium', 'high');
                    $options['protection_level'] = in_array($setting_value, $allowed_levels) ? $setting_value : 'medium';
                    break;
                case 'auto_protect_forms':
                    $options['auto_protect_forms'] = (bool) $setting_value;
                    break;
                case 'block_suspicious_ips':
                    $options['block_suspicious_ips'] = (bool) $setting_value;
                    break;
                case 'rate_limiting':
                    $options['rate_limiting'] = (bool) $setting_value;
                    break;
                case 'debug_mode':
                    $options['debug_mode'] = (bool) $setting_value;
                    break;
                case 'whitelist-ips':
                    $options['whitelist_ips'] = sanitize_textarea_field($setting_value);
                    break;
                case 'whitelist-enabled':
                    $options['whitelist_enabled'] = (bool) $setting_value;
                    break;
                case 'protect_comments':
                    $options['protect_comments'] = (bool) $setting_value;
                    break;
                case 'disable_comments_completely':
                    $options['disable_comments_completely'] = (bool) $setting_value;
                    // Apply the setting immediately
                    if ($setting_value) {
                        // Disable comments globally
                        update_option('default_comment_status', 'closed');
                        update_option('default_ping_status', 'closed');
                        // Close comments on all existing posts/pages
                        self::disable_comments_on_all_content();
                    } else {
                        // Re-enable comments (but don't force open on existing content)
                        update_option('default_comment_status', 'open');
                        update_option('default_ping_status', 'open');
                    }
                    break;
                case 'report_frequency':
                    $allowed_frequencies = array('15_days', '30_days');
                    $options['report_frequency'] = in_array($setting_value, $allowed_frequencies) ? $setting_value : '15_days';
                    break;
                case 'spam_custom_blacklist':
                    $raw = isset($_POST['setting_value']) ? wp_unslash($_POST['setting_value']) : '';
                    $options['spam_custom_blacklist'] = sanitize_textarea_field($raw);
                    break;
                case 'spam_custom_whitelist':
                    $raw = isset($_POST['setting_value']) ? wp_unslash($_POST['setting_value']) : '';
                    $options['spam_custom_whitelist'] = sanitize_textarea_field($raw);
                    break;
                case 'abuseipdb_api_key':
                    $raw = isset($_POST['setting_value']) ? wp_unslash($_POST['setting_value']) : '';
                    $options['abuseipdb_api_key'] = sanitize_text_field($raw);
                    break;
                default:
                    // Generic setting save with sanitization
                    $options[$setting_name] = sanitize_text_field($setting_value);
                    break;
            }

            // Save to database
            $result = update_option('formshield_options', $options);

            // update_option returns false if the value didn't change, but that's not an error
            // We consider it successful if we got this far without errors
            wp_send_json_success(array(
                'message' => 'Setting saved successfully',
                'setting_name' => $setting_name,
                'setting_value' => $setting_value
            ));
        }
    }
    
    /**
     * AJAX handler за зареждане на логове за форма
     */
}

function form_shield() {
    return FormShield::get_instance();
}

$form_shield = form_shield();