<?php
/*
 *	Plugin Name: FormShield
 *	Plugin URI: https://wpsupporting.com/plugins/formshield/
 *	Description: FormShield е мощен плъгин за защита на формуляри, който използва разширени шаблони и поведенчески анализ за борба със спам и ботове. Включва проследяване на местоположението на формите и интеграция с 14+ form плагина.
 *	Version: 1.1.6
 *	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.1.6');
}

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

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

if (!class_exists('FormShield')) {

    final class FormShield {
        private static $instance;
        private $version = '1.1.6';
        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');
            }

            // Автоматично сканирай сайта за форми
            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() {
            delete_option('formshield_options');
            delete_option('formshield_version');
        }

        /**
         * 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
         */
        public function check_session() {
            // Check if we have behavioral data from frontend
            $behavioral_data = $this->get_behavioral_data();
            
            if (empty($behavioral_data)) {
                // No behavioral data - assume bot
                return array(
                    'signal' => 'BOT',
                    'confidence' => 10
                );
            }
            
            // Analyze behavioral patterns
            $confidence = $this->analyze_behavior($behavioral_data);
            
            if ($confidence >= 70) {
                return array(
                    'signal' => 'HUMAN',
                    'confidence' => $confidence
                );
            } else {
                return array(
                    'signal' => 'BOT',
                    'confidence' => $confidence
                );
            }
        }
        
        /**
         * Recursively sanitize array data
         * 
         * @param mixed $value
         * @return mixed
         */
        private function fs_recursive_sanitize($value) {
            if (is_array($value)) {
                foreach ($value as $k => $v) {
                    $value[$k] = $this->fs_recursive_sanitize($v);
                }
                return $value;
            }
            if (is_string($value)) {
                return sanitize_text_field($value);
            }
            if (is_numeric($value)) {
                // Return number in correct type
                return strpos((string)$value, '.') !== false ? floatval($value) : intval($value);
            }
            return '';
        }

        /**
         * Get behavioral data from frontend
         * 
         * @return array
         */
        private function get_behavioral_data() {
            // Check for behavioral data in POST or session
            $data = array();
            
            // Check POST data for behavioral metrics
            if (isset($_POST['formshield_behavioral_data'])) {
                // Verify nonce for security
                $nonce = isset($_POST['formshield_nonce']) ? sanitize_text_field(wp_unslash($_POST['formshield_nonce'])) : '';
                if (!wp_verify_nonce($nonce, 'formshield_behavioral_data')) {
                    return array();
                }
                
                $behavioral_json = sanitize_text_field(wp_unslash($_POST['formshield_behavioral_data']));
                $data = json_decode($behavioral_json, true);
            }
            
            // Check session for stored behavioral data
            if (empty($data)) {
                // Get and sanitize session data safely
                $raw = array();
                if (isset($_SESSION) && is_array($_SESSION) && isset($_SESSION['formshield_behavioral_data'])) {
                    $session_data = sanitize_text_field(wp_unslash($_SESSION['formshield_behavioral_data']));
                    $raw = json_decode($session_data, true);
                    $raw = is_array($raw) ? $raw : array();
                }
                
                $clean = $this->fs_recursive_sanitize($raw);
                
                // Whitelist / normalization
                $data = array(
                    'time_on_page' => isset($clean['time_on_page']) ? absint($clean['time_on_page']) : 0,
                    'mouse_moves'  => isset($clean['mouse_moves'])  ? absint($clean['mouse_moves'])  : 0,
                    'keystrokes'   => isset($clean['keystrokes'])   ? absint($clean['keystrokes'])   : 0,
                    'referrer'     => isset($clean['referrer'])     ? sanitize_text_field($clean['referrer']) : '',
                    'form_fill_time' => isset($clean['form_fill_time']) ? absint($clean['form_fill_time']) : 0,
                    'scroll_events' => isset($clean['scroll_events']) ? absint($clean['scroll_events']) : 0,
                    'click_events' => isset($clean['click_events']) ? absint($clean['click_events']) : 0,
                );
            }
            
            return is_array($data) ? $data : array();
        }
        
        /**
         * Analyze behavioral data to determine if human
         * 
         * @param array $data Behavioral data
         * @return int Confidence score (0-100)
         */
        private function analyze_behavior($data) {
            $confidence = 50; // Start with neutral score
            
            // Check mouse movements (from JavaScript: mouseMovements)
            $mouse_moves = isset($data['mouse_moves']) ? intval($data['mouse_moves']) : 0;
            if ($mouse_moves > 5) {
                $confidence += 20;
            } elseif ($mouse_moves < 2) {
                $confidence -= 20; // Very few mouse movements - suspicious
            }
            
            // Check keyboard events (from JavaScript: keyboardEvents)
            $keystrokes = isset($data['keystrokes']) ? intval($data['keystrokes']) : 0;
            if ($keystrokes > 10) {
                $confidence += 15;
            } elseif ($keystrokes < 3) {
                $confidence -= 15; // Very few keystrokes - suspicious
            }
            
            // Check form fill time (from JavaScript: formStartTime -> form_fill_time)
            $form_fill_time = isset($data['form_fill_time']) ? intval($data['form_fill_time']) : 0;
            if ($form_fill_time > 5 && $form_fill_time < 300) { // 5 seconds to 5 minutes
                $confidence += 15;
            } elseif ($form_fill_time < 2) { // Too fast - likely bot
                $confidence -= 30;
            }
            
            // Check time on page (from JavaScript: time_on_page)
            $time_on_page = isset($data['time_on_page']) ? intval($data['time_on_page']) : 0;
            if ($time_on_page > 10) { // At least 10 seconds on page
                $confidence += 10;
            } elseif ($time_on_page < 3) { // Too quick - suspicious
                $confidence -= 20;
            }
            
            // Check for honeypot field interaction
            if (isset($data['honeypot_touched']) && $data['honeypot_touched']) {
                $confidence -= 50; // Honeypot was touched - likely bot
            }
            
            // Check for copy/paste behavior
            if (isset($data['paste_count']) && $data['paste_count'] > 3) {
                $confidence -= 10; // Too much pasting - suspicious
            }
            
            // Check scroll events
            $scroll_events = isset($data['scroll_events']) ? intval($data['scroll_events']) : 0;
            if ($scroll_events > 2) {
                $confidence += 5; // Some scrolling is good
            }
            
            // Check click events
            $click_events = isset($data['click_events']) ? intval($data['click_events']) : 0;
            if ($click_events > 1) {
                $confidence += 5; // Some clicking is good
            }
            
            // Ensure confidence is within bounds
            return max(0, min(100, $confidence));
        }
        
        /**
         * Регистрира 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() {
            // Verify nonce
            formshield_verify_nonce_or_bail('formshield_rescan_divi');
            
            // Стартираме 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-js', '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() {
            // Verify nonce
            formshield_verify_nonce_or_bail('formshield_scan_all');
            
            // Стартираме сканиране на всички форми
            $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() {
            // Verify nonce
            formshield_verify_nonce_or_bail('formshield_update_protected');
            
            // Обновяваме защитените форми
            $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() {
            // Verify nonce
            formshield_verify_nonce_or_bail('formshield_toggle_protection');
            
            $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() {
            // Verify nonce
            formshield_verify_nonce_or_bail('formshield_save_toggle_changes');
            
            // Verify nonce for form data processing
            $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
            if (!wp_verify_nonce($nonce, 'formshield_save_toggle_changes')) {
                wp_send_json_error(array('message' => 'Invalid nonce'));
                return;
            }
            
            $changes = isset($_POST['changes']) ? json_decode(sanitize_text_field(wp_unslash($_POST['changes'])), true) : array();
            
            if (empty($changes)) {
                wp_send_json_error(array('message' => 'No changes provided'));
                return;
            }
            
            // Вземаме текущите опции
            $options = $this->get_options();
            
            $updated_count = 0;
            foreach ($changes as $form_id => $enabled) {
                // Проверяваме дали формата съществува в опциите
                if (isset($options['formshield_forms'][$form_id])) {
                    $options['formshield_forms'][$form_id]['form_enabled'] = $enabled ? 1 : 0;
                    $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' => $enabled ? 1 : 0,
                        'updated_at' => current_time('mysql'),
                        'created_at' => current_time('mysql')
                    );
                    $updated_count++;
                }
            }
            
            // Запазваме опциите
            update_option('formshield_options', $options);
            
            wp_send_json_success(array(
                'message' => "Updated $updated_count forms",
                'updated_count' => $updated_count
            ));
        }
        
        /**
         * AJAX handler за повторно сканиране на форми
         */
        public function ajax_rescan_forms() {
            // Verify nonce
            formshield_verify_nonce_or_bail('formsh_rescan_forms');
            
            // Стартираме повторно сканиране на всички форми
            $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() {
            // Verify nonce
            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;
            }
            
            // 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;
                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();