<?php
/**
 * VMPFence Content Safety Scanner
 *
 * Analyzes WordPress content for safety violations including inappropriate content,
 * spam, policy violations, and security risks using local processing.
 *
 * @package VMPFence
 * @since 1.0.0
 */

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

// Include centralized exclusion manager
require_once plugin_dir_path(__FILE__) . 'class-scan-exclusion-manager.php';

class VMPFence_Content_Safety_Scanner {
    
    /**
     * Scan type identifier
     * @var string
     */
    private $scan_type = 'content_safety';
    
    /**
     * Debug mode flag
     * @var bool
     */
    private $debug = false;
    
    /**
     * Debug log array
     * @var array
     */
    private $debug_log = [];
    
    /**
     * Scan options
     * @var array
     */
    private $scan_options = null;
    
    /**
     * Enhanced violation patterns with context and severity scoring
     * @var array
     */
    private $violation_patterns = [
        'adult_content' => [
            // Only flag obvious commercial adult content, not educational or artistic content
            'keywords' => ['xxx', 'porn', 'escort', 'hookup', 'webcam', 'camgirl'],
            'context_patterns' => [
                '/\b(free|live|hot)\s+(porn|xxx)\b/i',
                '/\b(adult|nude)\s+(webcam|cam|show)\b/i',
                '/\b(18\+\s*only|adults\s*only|nsfw\s*content)\b/i',
                '/\b(escort\s*service|call\s*girls|hookup\s*tonight)\b/i'
            ],
            'severity_multiplier' => 1.8,
            'severity' => 'high',
            'description' => 'Commercial adult content detected',
            'category' => 'inappropriate_content',
            'min_matches' => 2 // Require at least 2 matches to reduce false positives
        ],
        'violence' => [
            // Only flag direct threats or promotion of violence, not news or educational content
            'keywords' => [],
            'context_patterns' => [
                '/\b(i\s+(will|am\s+going\s+to|want\s+to)\s+(kill|hurt|destroy|bomb))\b/i',
                '/\b(going\s+to\s+(shoot|bomb|attack)\s+(you|them|everyone))\b/i',
                '/\b(how\s+to\s+make\s+(bomb|explosive|poison))\b/i',
                '/\b(buy\s+(gun|weapon|explosive)\s+(illegal|black\s+market))\b/i'
            ],
            'severity_multiplier' => 3.0,
            'severity' => 'critical',
            'description' => 'Direct violent threats detected',
            'category' => 'threatening_content',
            'min_matches' => 1 // Even one direct threat is serious
        ],
        'hate_speech' => [
            // Only flag clear hate speech, not political opinions or historical content
            'keywords' => [],
            'context_patterns' => [
                '/\b(kill\s+all\s+(jews|muslims|blacks|whites|gays))\b/i',
                '/\b((jews|muslims|blacks|whites)\s+(should\s+die|are\s+inferior|dont\s+belong))\b/i',
                '/\b(white\s+power|racial\s+purity|ethnic\s+cleansing)\b/i',
                '/\b(go\s+back\s+to\s+(africa|mexico|your\s+country))\b/i'
            ],
            'severity_multiplier' => 3.0,
            'severity' => 'critical',
            'description' => 'Clear hate speech detected',
            'category' => 'discriminatory_content',
            'min_matches' => 1
        ],
        'illegal_activities' => [
            // Only flag clear promotion of illegal sales or activities
            'keywords' => [],
            'context_patterns' => [
                '/\b(buy\s+(cocaine|heroin|meth|fentanyl)\s+(cheap|online|here))\b/i',
                '/\b(sell\s+(drugs|cocaine|heroin|pills)\s+(cheap|online|contact))\b/i',
                '/\b(fake\s+(passport|id|license)\s+(for\s+sale|cheap|order))\b/i',
                '/\b(stolen\s+(credit\s+cards|identities)\s+(for\s+sale|cheap))\b/i',
                '/\b(money\s+laundering\s+(service|help|cheap))\b/i'
            ],
            'severity_multiplier' => 2.5,
            'severity' => 'high',
            'description' => 'Promotion of illegal activities detected',
            'category' => 'illegal_content',
            'min_matches' => 1
        ],
        'spam_scam' => [
            // Only flag obvious get-rich-quick schemes and scams
            'keywords' => [],
            'context_patterns' => [
                '/\$\d+\s+(per\s+day|per\s+hour|guaranteed)\s+(no\s+experience|easy\s+money|work\s+from\s+home)/i',
                '/\b(make\s+\$\d+\s+(daily|weekly|monthly)\s+(guaranteed|easy|simple))\b/i',
                '/\b(limited\s+time\s+offer.*act\s+now.*\$\d+)\b/i',
                '/\b(you\s+won.*claim.*\$\d+.*urgent)\b/i'
            ],
            'severity_multiplier' => 1.5,
            'severity' => 'medium',
            'description' => 'Get-rich-quick scam patterns detected',
            'category' => 'spam_content',
            'min_matches' => 1
        ],
        'phishing' => [
            // Only flag clear phishing attempts
            'keywords' => [],
            'context_patterns' => [
                '/\b(paypal|amazon|microsoft|google)\s+(account\s+suspended|verify\s+now|click\s+here)\b/i',
                '/\b(urgent\s+action\s+required.*verify\s+account.*expires\s+(today|soon))\b/i',
                '/\b(security\s+alert.*click\s+link.*verify\s+identity)\b/i',
                '/\b(your\s+(bank|paypal|amazon)\s+account.*suspended.*verify\s+immediately)\b/i'
            ],
            'severity_multiplier' => 2.5,
            'severity' => 'critical',
            'description' => 'Phishing attempt detected',
            'category' => 'security_threat',
            'min_matches' => 1
        ]
    ];
    
    /**
     * Enhanced suspicious URL patterns with detailed analysis
     * @var array
     */
    private $suspicious_url_patterns = [
        'url_shorteners' => [
            'pattern' => '/(bit\.ly|tinyurl|t\.co|goo\.gl|ow\.ly|is\.gd|buff\.ly)\/[a-zA-Z0-9]+/',
            'severity' => 'medium',
            'description' => 'URL shortener detected - may hide destination'
        ],
        'ip_addresses' => [
            'pattern' => '/https?:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/',
            'severity' => 'high',
            'description' => 'Direct IP address URL - potentially suspicious'
        ],
        'suspicious_domains' => [
            'pattern' => '/[a-z0-9]{15,}\.(?:com|net|org|tk|ml|ga|cf)/',
            'severity' => 'medium',
            'description' => 'Randomly generated domain name detected'
        ],
        'free_hosting' => [
            'pattern' => '/(000webhost|freehostia|byethost|hostinger)\./',
            'severity' => 'low',
            'description' => 'Free hosting service detected'
        ],
        'suspicious_tlds' => [
            'pattern' => '/\.(?:tk|ml|ga|cf|pw|click|download|loan|review)(?:\/|$)/',
            'severity' => 'medium',
            'description' => 'Suspicious top-level domain detected'
        ]
    ];
    
    /**
     * Public API endpoints for reputation checking
     * @var array
     */
    private $api_endpoints = [
        'virustotal_public' => 'https://www.virustotal.com/vtapi/v2/url/report',
        'safe_browsing' => 'https://safebrowsing.googleapis.com/v4/threatMatches:find',
        'phishtank' => 'https://checkurl.phishtank.com/checkurl/',
        'urlvoid' => 'http://api.urlvoid.com/1000/scan/host/'
    ];
    
    /**
     * Sentiment analysis word lists for context understanding
     * @var array
     */
    private $sentiment_words = [
        'positive' => ['good', 'great', 'excellent', 'amazing', 'wonderful', 'fantastic', 'love', 'like', 'enjoy'],
        'negative' => ['bad', 'terrible', 'awful', 'hate', 'disgusting', 'horrible', 'worst', 'suck', 'crap'],
        'aggressive' => ['attack', 'destroy', 'kill', 'eliminate', 'crush', 'smash', 'beat', 'fight', 'war'],
        'suspicious' => ['secret', 'hidden', 'private', 'exclusive', 'members only', 'special offer', 'limited time']
    ];
    
    /**
     * Centralized exclusion manager for consistent exclusion logic
     */
    private $exclusion_manager;
    
    /**
     * Constructor with enhanced initialization
     */
    public function __construct() {
        $this->debug = defined('WP_DEBUG') && WP_DEBUG;
        
        // Initialize centralized exclusion manager
        $this->exclusion_manager = VMPFence_Scan_Exclusion_Manager::getInstance();
        
        // Add WordPress action hooks for real-time scanning
        add_action('save_post', [$this, 'scan_post_on_save'], 10, 2);
        add_action('wp_insert_comment', [$this, 'scan_comment_on_insert'], 10, 2);
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Enhanced Content Safety Scanner initialized';
    }
    
    /**
     * Run the content safety scan
     *
     * @param array $scan_options Optional scan configuration options
     * @return array Scan results
     */
    public function run_scan($scan_options = null) {
        // Initialize performance controls if available
        $use_performance_controls = false;
        if (class_exists('VMPFence_Performance_Manager')) {
            VMPFence_Performance_Manager::init();
            $use_performance_controls = true;
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Content Safety Scanner: Performance controls initialized';
        }
        
        $start_time = microtime(true);
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Starting Content Safety Scan';
        $this->log_debug("Starting content safety scan");
        
        // If scan options provided, respect them
        if ($scan_options) {
            $this->scan_options = $scan_options;
            
            // Initialize exclusion manager with scan options
            $this->exclusion_manager->initialize($scan_options);
            
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Content Safety Scanner: Scan options loaded';
        }
        
        try {
            // Clear previous scan data
            $this->clear_previous_scan_data();
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Previous content safety scan data cleared';
            
            $scan_results = [];
            $content_items_checked = 0;
            $violations_found = 0;
            
            // Check which content types to scan based on options
            $scan_posts = $this->scan_options['scansEnabled_posts'] ?? false;
            $scan_comments = $this->scan_options['scansEnabled_comments'] ?? false;
            
            $this->debug_log[] = '[Content Safety] Scan configuration: Posts=' . ($scan_posts ? 'YES' : 'NO') . ', Comments=' . ($scan_comments ? 'YES' : 'NO');
            
            // 1. Scan Posts and Pages (CONDITIONAL based on scansEnabled_posts)
            if ($scan_posts) {
                $this->debug_log[] = '[Content Safety] Starting posts and pages scan';
                $post_results = $this->scan_posts_and_pages();
                $content_items_checked += $post_results['items_checked'];
                $violations_found += count($post_results['violations']);
                $scan_results = array_merge($scan_results, $post_results['violations']);
            } else {
                $this->debug_log[] = '[Content Safety] Skipping posts and pages scan (disabled in options)';
            }
            
            // 2. Scan Comments (CONDITIONAL based on scansEnabled_comments)  
            if ($scan_comments) {
                $this->debug_log[] = '[Content Safety] Starting comments scan';
                $comment_results = $this->scan_comments();
                $content_items_checked += $comment_results['items_checked'];
                $violations_found += count($comment_results['violations']);
                $scan_results = array_merge($scan_results, $comment_results['violations']);
            } else {
                $this->debug_log[] = '[Content Safety] Skipping comments scan (disabled in options)';
            }
            
            // Apply performance controls to limit issues if enabled
            if (class_exists('VMPFence_Performance_Manager')) {
                $scan_results = VMPFence_Performance_Manager::limit_issues($scan_results);
                $this->debug_log[] = '[' . current_time('H:i:s') . '] Performance Manager: Limited violations to ' . count($scan_results);
            }
            
            // Save scan results
            $this->save_scan_results($scan_results);
            $this->debug_log[] = '[Content Safety] Saved ' . count($scan_results) . ' content safety violations to database';
            
            $scan_time = round((microtime(true) - $start_time), 2);
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Content Safety Scan Complete - Checked ' . $content_items_checked . ' items, found ' . $violations_found . ' violations in ' . $scan_time . 's';
            $this->log_debug("Content safety scan completed in {$scan_time} seconds");
            
            $result = [
                'success' => true,
                'items_checked' => $content_items_checked,
                'issues_found' => $violations_found,
                'scan_time' => $scan_time,
                'scan_type' => 'content_safety',
                'debug_log' => $this->debug_log
            ];
            
            return $result;
            
        } catch (Exception $e) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] SCAN ERROR: ' . $e->getMessage();
            $this->log_debug("Content safety scan error: " . $e->getMessage());
            return [
                'success' => false,
                'error' => $e->getMessage(),
                'scan_type' => 'content_safety',
                'issues_found' => 0,
                'debug_log' => $this->debug_log
            ];
        }
    }
    
    /**
     * Scan posts and pages for content violations
     *
     * @return array Scan results
     */
    private function scan_posts_and_pages() {
        $violations = [];
        $items_checked = 0;
        
        // Get all published posts and pages
        $posts = get_posts([
            'post_type' => ['post', 'page'],
            'post_status' => 'publish',
            'numberposts' => -1,
            'fields' => 'ids'
        ]);
        
        $this->debug_log[] = '[Content Safety] Found ' . count($posts) . ' posts and pages to scan';
        
        $processed_posts = 0;
        foreach ($posts as $post_id) {
            // Performance throttling for post processing
            if (class_exists('VMPFence_Performance_Manager')) {
                VMPFence_Performance_Manager::throttle_processing($processed_posts);
            }
            $processed_posts++;
            
            $post = get_post($post_id);
            $items_checked++;
            
            // Analyze standard post content
            $content_violations = $this->analyze_content($post->post_content, 'post', $post_id, $post->post_title);
            $title_violations = $this->analyze_content($post->post_title, 'post_title', $post_id, $post->post_title);
            
            $violations = array_merge($violations, $content_violations, $title_violations);
            
            // Check for suspicious URLs in content
            $url_violations = $this->check_suspicious_urls($post->post_content, 'post', $post_id, $post->post_title);
            $violations = array_merge($violations, $url_violations);
            
            // Enhanced content scanning: Check page builder and custom field content
            $enhanced_violations = $this->scan_enhanced_content($post_id, $post->post_title);
            $violations = array_merge($violations, $enhanced_violations);
            
            if ($items_checked % 50 == 0) {
                $this->debug_log[] = '[Content Safety] Processed ' . $items_checked . ' posts/pages...';
            }
        }
        
        $this->debug_log[] = '[Content Safety] Posts/Pages scan complete: ' . $items_checked . ' items checked, ' . count($violations) . ' violations found';
        
        return [
            'items_checked' => $items_checked,
            'violations' => $violations
        ];
    }
    
    /**
     * Scan comments for content violations
     *
     * @return array Scan results
     */
    private function scan_comments() {
        $violations = [];
        $items_checked = 0;
        
        // Get all approved comments
        $comments = get_comments([
            'status' => 'approve',
            'number' => 1000, // Limit to prevent timeout
            'fields' => 'ids'
        ]);
        
        $this->debug_log[] = '[Content Safety] Found ' . count($comments) . ' comments to scan';
        
        $processed_comments = 0;
        foreach ($comments as $comment_id) {
            // Performance throttling for comment processing
            if (class_exists('VMPFence_Performance_Manager')) {
                VMPFence_Performance_Manager::throttle_processing($processed_comments);
            }
            $processed_comments++;
            
            $comment = get_comment($comment_id);
            $items_checked++;
            
            // Analyze comment content
            $content_violations = $this->analyze_content($comment->comment_content, 'comment', $comment_id, 'Comment #' . $comment_id);
            $violations = array_merge($violations, $content_violations);
            
            // Check author name for violations
            $author_violations = $this->analyze_content($comment->comment_author, 'comment_author', $comment_id, 'Comment Author');
            $violations = array_merge($violations, $author_violations);
            
            // Check for suspicious URLs
            $url_violations = $this->check_suspicious_urls($comment->comment_content, 'comment', $comment_id, 'Comment #' . $comment_id);
            $violations = array_merge($violations, $url_violations);
        }
        
        $this->debug_log[] = '[Content Safety] Comments scan complete: ' . $items_checked . ' items checked, ' . count($violations) . ' violations found';
        
        return [
            'items_checked' => $items_checked,
            'violations' => $violations
        ];
    }
    
    /**
     * Scan media files for content violations
     *
     * @return array Scan results
     */
    private function scan_media_files() {
        $violations = [];
        $items_checked = 0;
        
        // Get all media attachments
        $media = get_posts([
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'numberposts' => 500, // Limit to prevent timeout
            'fields' => 'ids'
        ]);
        
        $this->debug_log[] = '[Content Safety] Found ' . count($media) . ' media files to scan';
        
        foreach ($media as $media_id) {
            $attachment = get_post($media_id);
            $items_checked++;
            
            // Check file title
            $title_violations = $this->analyze_content($attachment->post_title, 'media_title', $media_id, $attachment->post_title);
            $violations = array_merge($violations, $title_violations);
            
            // Check file description
            $desc_violations = $this->analyze_content($attachment->post_content, 'media_description', $media_id, $attachment->post_title);
            $violations = array_merge($violations, $desc_violations);
            
            // Check alt text
            $alt_text = get_post_meta($media_id, '_wp_attachment_image_alt', true);
            if ($alt_text) {
                $alt_violations = $this->analyze_content($alt_text, 'media_alt', $media_id, $attachment->post_title);
                $violations = array_merge($violations, $alt_violations);
            }
            
            // Check filename for suspicious patterns
            $filename = basename(get_attached_file($media_id));
            $filename_violations = $this->analyze_content($filename, 'media_filename', $media_id, $filename);
            $violations = array_merge($violations, $filename_violations);
        }
        
        $this->debug_log[] = '[Content Safety] Media files scan complete: ' . $items_checked . ' items checked, ' . count($violations) . ' violations found';
        
        return [
            'items_checked' => $items_checked,
            'violations' => $violations
        ];
    }
    
    /**
     * Scan user profiles for content violations
     *
     * @return array Scan results
     */
    private function scan_user_profiles() {
        $violations = [];
        $items_checked = 0;
        
        // Get all users
        $users = get_users(['fields' => 'all']);
        
        $this->debug_log[] = '[Content Safety] Found ' . count($users) . ' user profiles to scan';
        
        foreach ($users as $user) {
            $items_checked++;
            
            // Check display name
            $display_violations = $this->analyze_content($user->display_name, 'user_display_name', $user->ID, 'User: ' . $user->user_login);
            $violations = array_merge($violations, $display_violations);
            
            // Check bio/description
            $bio = get_user_meta($user->ID, 'description', true);
            if ($bio) {
                $bio_violations = $this->analyze_content($bio, 'user_bio', $user->ID, 'User: ' . $user->user_login);
                $violations = array_merge($violations, $bio_violations);
                
                // Check for suspicious URLs in bio
                $url_violations = $this->check_suspicious_urls($bio, 'user_bio', $user->ID, 'User: ' . $user->user_login);
                $violations = array_merge($violations, $url_violations);
            }
            
            // Check website URL if provided
            if ($user->user_url) {
                $website_violations = $this->check_suspicious_urls($user->user_url, 'user_website', $user->ID, 'User: ' . $user->user_login);
                $violations = array_merge($violations, $website_violations);
            }
        }
        
        $this->debug_log[] = '[Content Safety] User profiles scan complete: ' . $items_checked . ' items checked, ' . count($violations) . ' violations found';
        
        return [
            'items_checked' => $items_checked,
            'violations' => $violations
        ];
    }
    
    /**
     * Scan widgets and menus for content violations
     *
     * @return array Scan results
     */
    private function scan_widgets_and_menus() {
        $violations = [];
        $items_checked = 0;
        
        // Scan text widgets
        $widgets = wp_get_sidebars_widgets();
        
        foreach ($widgets as $sidebar_id => $widget_ids) {
            if (empty($widget_ids) || !is_array($widget_ids)) continue;
            
            foreach ($widget_ids as $widget_id) {
                if (strpos($widget_id, 'text') === 0) {
                    $items_checked++;
                    $widget_options = get_option('widget_text');
                    $widget_number = str_replace('text-', '', $widget_id);
                    
                    if (isset($widget_options[$widget_number]['text'])) {
                        $widget_content = $widget_options[$widget_number]['text'];
                        $widget_violations = $this->analyze_content($widget_content, 'widget', $widget_number, 'Text Widget');
                        $violations = array_merge($violations, $widget_violations);
                        
                        $url_violations = $this->check_suspicious_urls($widget_content, 'widget', $widget_number, 'Text Widget');
                        $violations = array_merge($violations, $url_violations);
                    }
                }
            }
        }
        
        // Scan navigation menus
        $menus = wp_get_nav_menus();
        foreach ($menus as $menu) {
            $menu_items = wp_get_nav_menu_items($menu->term_id);
            foreach ($menu_items as $menu_item) {
                $items_checked++;
                
                // Check menu item title
                $title_violations = $this->analyze_content($menu_item->title, 'menu_item', $menu_item->ID, 'Menu: ' . $menu->name);
                $violations = array_merge($violations, $title_violations);
                
                // Check menu item URL
                if ($menu_item->url) {
                    $url_violations = $this->check_suspicious_urls($menu_item->url, 'menu_item', $menu_item->ID, 'Menu: ' . $menu->name);
                    $violations = array_merge($violations, $url_violations);
                }
            }
        }
        
        $this->debug_log[] = '[Content Safety] Widgets/Menus scan complete: ' . $items_checked . ' items checked, ' . count($violations) . ' violations found';
        
        return [
            'items_checked' => $items_checked,
            'violations' => $violations
        ];
    }
    
    /**
     * Analyze content for violations
     *
     * @param string $content Content to analyze
     * @param string $content_type Type of content
     * @param int $content_id Content ID
     * @param string $content_title Content title for reference
     * @return array Array of violations found
     */
    /**
     * Advanced content analysis with context understanding and ML-inspired techniques
     *
     * @param string $content Content to analyze
     * @param string $content_type Type of content
     * @param int $content_id Content ID
     * @param string $content_title Content title for reference
     * @return array Array of violations found
     */
    private function analyze_content($content, $content_type, $content_id, $content_title) {
        $violations = [];
        
        if (empty($content)) {
            return $violations;
        }
        
        // Enhanced content preprocessing
        $original_content = $content;
        $content_clean = $this->preprocess_content($content);
        $content_lower = strtolower($content_clean);
        
        // 1. Advanced Pattern Matching with Context Analysis
        $pattern_violations = $this->analyze_patterns_with_context($content_clean, $content_type, $content_id, $content_title);
        $violations = array_merge($violations, $pattern_violations);
        
        // 2. Sentiment and Tone Analysis
        $sentiment_violations = $this->analyze_sentiment_and_tone($content_clean, $content_type, $content_id, $content_title);
        $violations = array_merge($violations, $sentiment_violations);
        
        // 3. URL and Link Analysis
        $url_violations = $this->analyze_urls_advanced($content, $content_type, $content_id, $content_title);
        $violations = array_merge($violations, $url_violations);
        
        // 4. Statistical Content Analysis
        $statistical_violations = $this->analyze_content_statistics($content_clean, $content_type, $content_id, $content_title);
        $violations = array_merge($violations, $statistical_violations);
        
        // 5. Language and Encoding Analysis
        $language_violations = $this->analyze_language_patterns($content_clean, $content_type, $content_id, $content_title);
        $violations = array_merge($violations, $language_violations);
        
        // 6. Behavioral Pattern Analysis
        $behavioral_violations = $this->analyze_behavioral_patterns($content_clean, $content_type, $content_id, $content_title);
        $violations = array_merge($violations, $behavioral_violations);
        
        return $violations;
    }
    
    /**
     * Advanced content preprocessing with normalization
     *
     * @param string $content Raw content
     * @return string Preprocessed content
     */
    private function preprocess_content($content) {
        // Remove HTML tags and decode entities
        $content = html_entity_decode(wp_strip_all_tags($content), ENT_QUOTES, 'UTF-8');
        
        // Normalize whitespace and special characters
        $content = preg_replace('/\s+/', ' ', $content);
        $content = preg_replace('/[^\w\s\-\.\@\:\/\?\=\&]/', ' ', $content);
        
        // Handle obfuscation attempts
        $content = $this->deobfuscate_content($content);
        
        return trim($content);
    }
    
    /**
     * Deobfuscate common content hiding techniques
     *
     * @param string $content Content to deobfuscate
     * @return string Deobfuscated content
     */
    private function deobfuscate_content($content) {
        // Handle leetspeak and character substitution
        $substitutions = [
            '3' => 'e', '4' => 'a', '1' => 'i', '0' => 'o', '5' => 's',
            '@' => 'a', '$' => 's', '!' => 'i', '7' => 't', '8' => 'b'
        ];
        
        $deobfuscated = str_replace(array_keys($substitutions), array_values($substitutions), $content);
        
        // Handle spaced characters (p o r n -> porn)
        $deobfuscated = preg_replace('/\b([a-z])\s+([a-z])\s+([a-z])\s+([a-z])\b/', '$1$2$3$4', $deobfuscated);
        
        // Handle intentional misspellings
        $deobfuscated = preg_replace('/p\W*o\W*r\W*n/', 'porn', $deobfuscated);
        $deobfuscated = preg_replace('/s\W*e\W*x/', 'sex', $deobfuscated);
        $deobfuscated = preg_replace('/d\W*r\W*u\W*g\W*s/', 'drugs', $deobfuscated);
        
        return $deobfuscated;
    }
    
    /**
     * Advanced pattern matching with contextual analysis
     *
     * @param string $content Preprocessed content
     * @param string $content_type Content type
     * @param int $content_id Content ID
     * @param string $content_title Content title
     * @return array Violations found
     */
    private function analyze_patterns_with_context($content, $content_type, $content_id, $content_title) {
        $violations = [];
        $content_lower = strtolower($content);
        
        foreach ($this->violation_patterns as $violation_type => $pattern_data) {
            $violation_score = 0;
            $matched_keywords = [];
            $matched_contexts = [];
            
            // 1. Keyword matching with scoring
            foreach ($pattern_data['keywords'] as $keyword) {
                $keyword_lower = strtolower($keyword);
                $matches = substr_count($content_lower, $keyword_lower);
                
                if ($matches > 0) {
                    $violation_score += $matches * 10;
                    $matched_keywords[] = $keyword;
                }
            }
            
            // 2. Context pattern matching (higher weight)
            if (isset($pattern_data['context_patterns'])) {
                foreach ($pattern_data['context_patterns'] as $context_pattern) {
                    if (preg_match($context_pattern, $content)) {
                        $violation_score += 25 * $pattern_data['severity_multiplier'];
                        $matched_contexts[] = $context_pattern;
                    }
                }
            }
            
            // 3. Check minimum matches requirement to reduce false positives
            $total_matches = count($matched_keywords) + count($matched_contexts);
            $min_matches = $pattern_data['min_matches'] ?? 1;
            
            // 4. Apply severity multiplier and context bonus only if minimum matches met
            if ($violation_score > 0 && $total_matches >= $min_matches) {
                $violation_score *= $pattern_data['severity_multiplier'];
                
                // Context bonus - higher score if multiple indicators
                if (count($matched_keywords) > 1 || count($matched_contexts) > 0) {
                    $violation_score *= 1.5;
                }
                
                // Determine final severity based on score
                $final_severity = $this->calculate_severity($violation_score);
                
                $this->debug_log[] = "[Content Safety] VIOLATION: {$violation_type} detected in {$content_type} (ID: {$content_id}) - Score: {$violation_score}, Keywords: " . implode(', ', $matched_keywords) . ", Contexts: " . count($matched_contexts) . ", Min matches required: {$min_matches}";
                
                $violations[] = [
                    'type' => $violation_type,
                    'severity' => $final_severity,
                    'score' => $violation_score,
                    'title' => 'Content Safety Violation: ' . ucwords(str_replace('_', ' ', $violation_type)),
                    'description' => $pattern_data['description'] . ' in ' . $content_type,
                    'details' => "Keywords found: " . implode(', ', $matched_keywords) . 
                               (count($matched_contexts) > 0 ? ". Context patterns matched: " . count($matched_contexts) : ""),
                    'recommendation' => $this->generate_recommendation($violation_type, $violation_score),
                    'content_type' => $content_type,
                    'content_id' => $content_id,
                    'content_title' => $content_title,
                    'matched_keywords' => $matched_keywords,
                    'matched_contexts' => count($matched_contexts),
                    'category' => $pattern_data['category'] ?? 'general'
                ];
            } else if ($violation_score > 0) {
                // Log when violations were found but didn't meet minimum threshold
                $this->debug_log[] = "[Content Safety] BELOW THRESHOLD: {$violation_type} in {$content_type} (ID: {$content_id}) - Total matches: {$total_matches}, Required: {$min_matches}";
            }
        }
        
        return $violations;
    }
    
    /**
     * Advanced sentiment and tone analysis
     *
     * @param string $content Content to analyze
     * @param string $content_type Content type
     * @param int $content_id Content ID
     * @param string $content_title Content title
     * @return array Violations found
     */
    private function analyze_sentiment_and_tone($content, $content_type, $content_id, $content_title) {
        $violations = [];
        $content_lower = strtolower($content);
        $words = str_word_count($content_lower, 1);
        
        if (count($words) < 5) {
            return $violations; // Skip very short content
        }
        
        $sentiment_scores = [
            'positive' => 0,
            'negative' => 0,
            'aggressive' => 0,
            'suspicious' => 0
        ];
        
        // Calculate sentiment scores
        foreach ($words as $word) {
            foreach ($this->sentiment_words as $sentiment_type => $sentiment_list) {
                if (in_array($word, $sentiment_list)) {
                    $sentiment_scores[$sentiment_type]++;
                }
            }
        }
        
        // Normalize scores by content length
        $total_words = count($words);
        foreach ($sentiment_scores as $type => $score) {
            $sentiment_scores[$type] = ($score / $total_words) * 100;
        }
        
        // Check for concerning sentiment patterns
        if ($sentiment_scores['aggressive'] > 5 && $sentiment_scores['negative'] > 10) {
            $violations[] = [
                'type' => 'aggressive_tone',
                'severity' => 'medium',
                'score' => $sentiment_scores['aggressive'] + $sentiment_scores['negative'],
                'title' => 'Aggressive or Threatening Tone Detected',
                'description' => 'Content exhibits aggressive or threatening language patterns',
                'details' => sprintf("Aggressive score: %.1f%%, Negative score: %.1f%%", 
                           $sentiment_scores['aggressive'], $sentiment_scores['negative']),
                'recommendation' => 'Review content tone to ensure it meets community standards',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'category' => 'tone_analysis'
            ];
        }
        
        if ($sentiment_scores['suspicious'] > 8) {
            $violations[] = [
                'type' => 'suspicious_language',
                'severity' => 'low',
                'score' => $sentiment_scores['suspicious'],
                'title' => 'Suspicious Language Patterns',
                'description' => 'Content contains language patterns often associated with spam or deceptive content',
                'details' => sprintf("Suspicious language score: %.1f%%", $sentiment_scores['suspicious']),
                'recommendation' => 'Verify content authenticity and intent',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'category' => 'language_analysis'
            ];
        }
        
        return $violations;
    }
    
    /**
     * Advanced URL analysis with reputation checking
     *
     * @param string $content Content containing URLs
     * @param string $content_type Content type
     * @param int $content_id Content ID
     * @param string $content_title Content title
     * @return array Violations found
     */
    private function analyze_urls_advanced($content, $content_type, $content_id, $content_title) {
        $violations = [];
        
        if (empty($content)) {
            return $violations;
        }
        
        // Extract all URLs from content
        preg_match_all('/https?:\/\/[^\s<>"\']+/', $content, $matches);
        $urls = array_unique($matches[0]);
        
        if (empty($urls)) {
            return $violations;
        }
        
        foreach ($urls as $url) {
            // 1. Pattern-based analysis
            $pattern_violations = $this->check_url_patterns($url, $content_type, $content_id, $content_title);
            $violations = array_merge($violations, $pattern_violations);
            
            // 2. Domain reputation analysis
            $reputation_violations = $this->check_url_reputation($url, $content_type, $content_id, $content_title);
            $violations = array_merge($violations, $reputation_violations);
            
            // 3. URL structure analysis
            $structure_violations = $this->analyze_url_structure($url, $content_type, $content_id, $content_title);
            $violations = array_merge($violations, $structure_violations);
        }
        
        return $violations;
    }
    
    /**
     * Check URL against suspicious patterns
     *
     * @param string $url URL to check
     * @param string $content_type Content type
     * @param int $content_id Content ID
     * @param string $content_title Content title
     * @return array Violations found
     */
    private function check_url_patterns($url, $content_type, $content_id, $content_title) {
        $violations = [];
        
        foreach ($this->suspicious_url_patterns as $pattern_name => $pattern_data) {
            if (preg_match($pattern_data['pattern'], $url)) {
                $this->debug_log[] = "[Content Safety] SUSPICIOUS URL: {$url} matches {$pattern_name} pattern";
                
                $violations[] = [
                    'type' => 'suspicious_url_' . $pattern_name,
                    'severity' => $pattern_data['severity'],
                    'title' => 'Suspicious URL Pattern: ' . ucwords(str_replace('_', ' ', $pattern_name)),
                    'description' => $pattern_data['description'],
                    'details' => "URL: {$url}",
                    'recommendation' => 'Verify URL legitimacy and destination safety',
                    'content_type' => $content_type,
                    'content_id' => $content_id,
                    'content_title' => $content_title,
                    'suspicious_url' => $url,
                    'pattern_matched' => $pattern_name,
                    'category' => 'url_analysis'
                ];
            }
        }
        
        return $violations;
    }
    
    /**
     * Check for suspicious URLs in content
     *
     * @param string $content Content to check
     * @param string $content_type Type of content
     * @param int $content_id Content ID
     * @param string $content_title Content title for reference
     * @return array Array of violations found
     */
    private function check_suspicious_urls($content, $content_type, $content_id, $content_title) {
        $violations = [];
        
        if (empty($content)) {
            return $violations;
        }
        
        // Extract URLs from content
        preg_match_all('/https?:\/\/[^\s<>"]+/', $content, $matches);
        $urls = $matches[0];
        
        foreach ($urls as $url) {
            foreach ($this->suspicious_url_patterns as $pattern_name => $pattern_data) {
                if (preg_match($pattern_data['pattern'], $url)) {
                    $this->debug_log[] = '[Content Safety] SUSPICIOUS URL: ' . $url . ' in ' . $content_type . ' (ID: ' . $content_id . ')';
                    
                    $violations[] = [
                        'type' => 'suspicious_url',
                        'severity' => $pattern_data['severity'],
                        'title' => 'Suspicious URL Detected',
                        'description' => $pattern_data['description'],
                        'details' => "URL: {$url} matches {$pattern_name} pattern",
                        'recommendation' => 'Review URL for legitimacy and safety.',
                        'content_type' => $content_type,
                        'content_id' => $content_id,
                        'content_title' => $content_title,
                        'suspicious_url' => $url
                    ];
                    break;
                }
            }
        }
        
        return $violations;
    }
    
    /**
     * Scan enhanced content sources (page builders, custom fields, etc.)
     *
     * @param int $post_id Post ID
     * @param string $post_title Post title for reference
     * @return array Array of violations found
     */
    private function scan_enhanced_content($post_id, $post_title) {
        $violations = [];
        
        // Get all meta fields for this post
        $meta_fields = get_post_meta($post_id);
        
        foreach ($meta_fields as $meta_key => $meta_values) {
            // Skip internal WordPress fields and common non-content fields
            if (strpos($meta_key, '_') === 0 || in_array($meta_key, ['_edit_lock', '_edit_last'])) {
                continue;
            }
            
            foreach ($meta_values as $meta_value) {
                if (is_string($meta_value) && strlen($meta_value) > 10) {
                    // Check if this looks like content (not just settings/IDs)
                    if ($this->is_content_like($meta_value)) {
                        $this->debug_log[] = '[Content Safety] Scanning custom field: ' . $meta_key . ' for post ' . $post_id;
                        
                        $field_violations = $this->analyze_content($meta_value, 'custom_field', $post_id, $post_title . ' (' . $meta_key . ')');
                        $violations = array_merge($violations, $field_violations);
                        
                        $url_violations = $this->check_suspicious_urls($meta_value, 'custom_field', $post_id, $post_title . ' (' . $meta_key . ')');
                        $violations = array_merge($violations, $url_violations);
                    }
                }
            }
        }
        
        // Check for custom template content
        $template_violations = $this->scan_custom_template($post_id, $post_title);
        $violations = array_merge($violations, $template_violations);
        
        // Check for Elementor content (common page builder)
        $elementor_data = get_post_meta($post_id, '_elementor_data', true);
        if (!empty($elementor_data)) {
            $this->debug_log[] = '[Content Safety] Scanning Elementor content for post ' . $post_id;
            $elementor_violations = $this->analyze_content($elementor_data, 'elementor_content', $post_id, $post_title . ' (Elementor)');
            $violations = array_merge($violations, $elementor_violations);
        }
        
        // Check for Divi Builder content
        $divi_content = get_post_meta($post_id, '_et_pb_page_layout', true);
        if (!empty($divi_content)) {
            $this->debug_log[] = '[Content Safety] Scanning Divi content for post ' . $post_id;
            $divi_violations = $this->analyze_content($divi_content, 'divi_content', $post_id, $post_title . ' (Divi)');
            $violations = array_merge($violations, $divi_violations);
        }
        
        // Check for Gutenberg block content stored in meta
        $gutenberg_content = get_post_meta($post_id, '_gutenberg_blocks_content', true);
        if (!empty($gutenberg_content)) {
            $this->debug_log[] = '[Content Safety] Scanning Gutenberg blocks content for post ' . $post_id;
            $gutenberg_violations = $this->analyze_content($gutenberg_content, 'gutenberg_blocks', $post_id, $post_title . ' (Gutenberg)');
            $violations = array_merge($violations, $gutenberg_violations);
        }
        
        return $violations;
    }
    
    /**
     * Scan custom template files for content
     *
     * @param int $post_id Post ID
     * @param string $post_title Post title for reference
     * @return array Array of violations found
     */
    private function scan_custom_template($post_id, $post_title) {
        $violations = [];
        
        // Get the custom template for this page
        $template = get_post_meta($post_id, '_wp_page_template', true);
        
        if (empty($template) || $template === 'default') {
            return $violations;
        }
        
        $this->debug_log[] = '[Content Safety] Found custom template: ' . $template . ' for post ' . $post_id;
        
        // Look for the template file
        $theme_dir = get_template_directory();
        $template_path = $theme_dir . '/' . $template;
        
        if (file_exists($template_path)) {
            $this->debug_log[] = '[Content Safety] Scanning custom template file: ' . $template_path;
            
            $template_content = file_get_contents($template_path);
            
            if (!empty($template_content)) {
                // Remove PHP code and keep only HTML/text content
                $clean_content = $this->extract_template_content($template_content);
                
                if (!empty($clean_content)) {
                    $this->debug_log[] = '[Content Safety] Extracted ' . strlen($clean_content) . ' characters from template';
                    
                    $template_violations = $this->analyze_content($clean_content, 'custom_template', $post_id, $post_title . ' (Template: ' . $template . ')');
                    $violations = array_merge($violations, $template_violations);
                    
                    $url_violations = $this->check_suspicious_urls($clean_content, 'custom_template', $post_id, $post_title . ' (Template)');
                    $violations = array_merge($violations, $url_violations);
                }
            }
        } else {
            $this->debug_log[] = '[Content Safety] Custom template file not found: ' . $template_path;
        }
        
        return $violations;
    }
    
    /**
     * Extract content from template file, removing PHP code
     *
     * @param string $template_content Raw template content
     * @return string Cleaned content for scanning
     */
    private function extract_template_content($template_content) {
        // Remove PHP opening and closing tags and their content
        $content = preg_replace('/<\?php.*?\?>/s', '', $template_content);
        $content = preg_replace('/<\?.*?\?>/s', '', $content);
        
        // Extract text from HTML tags
        $content = wp_strip_all_tags($content);
        
        // Clean up whitespace
        $content = preg_replace('/\s+/', ' ', $content);
        $content = trim($content);
        
        // Only return if we have substantial content
        return strlen($content) > 20 ? $content : '';
    }
    
    /**
     * Check if a meta value looks like content worth scanning
     *
     * @param string $value Meta value to check
     * @return bool True if it looks like content
     */
    private function is_content_like($value) {
        // Check if it contains common content indicators
        $content_indicators = ['<p>', '<div>', '<span>', '<h1>', '<h2>', '<h3>', 'http', 'www.'];
        
        foreach ($content_indicators as $indicator) {
            if (strpos($value, $indicator) !== false) {
                return true;
            }
        }
        
        // Check if it's mostly alphabetic (likely text content)
        $alpha_ratio = strlen(preg_replace('/[^a-zA-Z\s]/', '', $value)) / strlen($value);
        
        return $alpha_ratio > 0.3; // If more than 30% is alphabetic, consider it content
    }
    
    /**
     * Clear previous scan data for this scan type
     */
    private function clear_previous_scan_data() {
        global $wpdb;
        
        // Clear previous scan issues from new table structure
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table names from WordPress prefix
        $issues_table = $wpdb->prefix . 'vmpfence_scan_issues';
        
        $deleted_issues = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$issues_table} WHERE issue_type = %s AND status != 'ignored'",
            $this->scan_type
        ));
        
        // Clear previous scan results
        $results_table = $wpdb->prefix . 'vmpfence_scan_results';
        $deleted_results = $wpdb->query($wpdb->prepare(
            "DELETE FROM {$results_table} WHERE scan_type = %s",
            $this->scan_type
        ));
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        
        $this->log_debug("Cleared previous content safety scan data from both issues and results tables");
    }
    
    /**
     * Save scan results to database
     *
     * @param array $results Scan results to save
     */
    private function save_scan_results($results) {
        global $wpdb;
        
        $issues_count = is_array($results) ? count($results) : 0;
        
        // Save scan summary to scan_results table (ALWAYS save, even if no issues found)
        $scan_results_table = $wpdb->prefix . 'vmpfence_scan_results';
        $scan_result_id = $wpdb->insert(
            $scan_results_table,
            [
                'scan_type' => 'content_safety',
                'scan_time' => current_time('mysql'),
                'total_files' => 0, // Content safety scans don't scan files directly
                'issues_found' => $issues_count,
                'scan_status' => 'completed',
                'scan_data' => wp_json_encode([
                    'violations_found' => $issues_count,
                    'scan_type' => 'content_safety'
                ])
            ]
        );
        
        if ($scan_result_id === false) {
            $this->log_debug('Error saving scan summary: ' . $wpdb->last_error);
            return;
        }
        
        $scan_id = $wpdb->insert_id;
        $this->log_debug("Saved content safety scan summary (ID: {$scan_id}) with {$issues_count} issues found");
        
        // If no issues found, we're done (but we did save the scan record)
        if (empty($results)) {
            $this->log_debug("No content safety violations found, but scan record saved successfully");
            return;
        }
        
        // Save individual issues to scan_issues table
        $scan_issues_table = $wpdb->prefix . 'vmpfence_scan_issues';
        
        foreach ($results as $result) {
            $description = $result['title'] . ': ' . $result['description'] . ' Details: ' . $result['details'] . ' Solution: ' . $result['recommendation'];
            
            // First check if this issue should be recreated as ignored
            if ($this->handle_ignored_issue('', 'content_safety', $result['type'], $description, $scan_id)) {
                continue; // Issue was handled as ignored, skip normal processing
            }
            
            // Check if this issue is currently ignored (skip normal creation)
            if ($this->is_issue_ignored('', 'content_safety', $result['type'], $description)) {
                $this->log_debug('SKIP: Content safety issue already ignored - ' . $result['title']);
                continue;
            }

            $insert_result = $wpdb->insert(
                $scan_issues_table,
                [
                    'scan_id' => $scan_id,
                    'file_path' => '', // Not applicable for content safety
                    'issue_type' => 'content_safety',
                    'type' => $result['type'], // Specific violation type (adult_content, violence, etc.)
                    'severity' => $this->map_issue_type_to_severity('content_safety'),
                    'description' => $description,
                    'detected_time' => current_time('mysql'),
                    'status' => 'new'
                ]
            );
            
            if ($insert_result === false) {
                $this->log_debug('Error saving content safety issue: ' . $wpdb->last_error);
            }
        }
        
                $this->log_debug("Saved scan summary (ID: " . $scan_id . ") and " . count($results) . " content safety violations to database");
    }
    
    /**
     * Check if an issue is already ignored
     */
    private function is_issue_ignored($file_path, $issue_type, $type, $description) {
        global $wpdb;
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name from WordPress prefix
        $scan_issues_table = $wpdb->prefix . 'vmpfence_scan_issues';
        
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $scan_issues_table 
             WHERE file_path = %s AND issue_type = %s AND type = %s AND description = %s AND status = 'ignored'",
            $file_path,
            $issue_type,
            $type,
            $description
        ));
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        
        return $count > 0;
    }
    
    /**
     * Handle previously ignored issues - recreate them in current scan as ignored
     *
     * @param string $file_path File path
     * @param string $issue_type Issue type
     * @param string $description Issue description
     * @param int $scan_id Current scan ID
     * @return bool Whether issue was handled
     */
    private function handle_ignored_issue($file_path, $issue_type, $type, $description, $scan_id) {
        global $wpdb;
        
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name from WordPress prefix
        $issues_table = $wpdb->prefix . 'vmpfence_scan_issues';
        
        // Check if this exact issue was previously ignored
        $ignored_issue = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$issues_table} WHERE file_path = %s AND issue_type = %s AND type = %s AND description = %s AND status = 'ignored' ORDER BY detected_time DESC LIMIT 1",
            $file_path,
            $issue_type,
            $type,
            $description
        ));
        
        if ($ignored_issue) {
            // Recreate the ignored issue in current scan
            $insert_result = $wpdb->insert(
                $issues_table,
                [
                    'scan_id' => $scan_id,
                    'file_path' => $file_path,
                    'issue_type' => $issue_type,
                    'type' => $type,
                    'severity' => $this->map_issue_type_to_severity($issue_type),
                    'description' => $description,
                    'status' => 'ignored',
                    'detected_time' => current_time('mysql'),
                    'resolved_time' => current_time('mysql')
                ],
                ['%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s']
            );
            
            if ($insert_result) {
                // Clean up old ignored entries for this same issue (keep only the latest)
                $wpdb->query($wpdb->prepare(
                    "DELETE FROM {$issues_table} WHERE file_path = %s AND issue_type = %s AND description = %s AND status = 'ignored' AND id != %d",
                    $file_path,
                    $issue_type,
                    $description,
                    $wpdb->insert_id
                ));
                // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                
                $this->debug_log[] = '[' . current_time('H:i:s') . '] PRESERVED: Recreated ignored content_safety - ' . $description;
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Map issue type to severity level
     *
     * @param string $issue_type Issue type
     * @return string Severity level
     */
    private function map_issue_type_to_severity($issue_type) {
        switch ($issue_type) {
            case 'content_safety':
                return 'medium';
            default:
                return 'medium';
        }
    }
    
    /**
     * Map text severity to numeric value for database storage
     *
     * @param string $severity Severity text (critical, high, medium, low)
     * @return int Numeric severity value
     */
    private function map_severity_to_number($severity) {
        switch (strtolower($severity)) {
            case 'critical':
                return 4;
            case 'high':
                return 3;
            case 'medium':
                return 2;
            case 'low':
                return 1;
            default:
                return 2; // Default to medium
        }
    }
    
    /**
     * Get content safety statistics
     *
     * @return array Statistics about content safety
     */
    public function get_content_safety_stats() {
        global $wpdb;
        
        $total_posts = wp_count_posts()->publish;
        $total_comments = wp_count_comments()->approved;
        
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name from WordPress prefix
        $table = $wpdb->prefix . 'vmpfence_scan_issues'; // Use new table structure
        $issues_count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE issue_type = %s AND status != 'ignored'",
            $this->scan_type
        ));
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        
        return [
            'total_posts' => $total_posts,
            'total_comments' => $total_comments,
            'content_violations' => (int) $issues_count,
            'safety_score' => $this->calculate_content_safety_score($total_posts + $total_comments, $issues_count)
        ];
    }
    
    /**
     * Calculate content safety score
     *
     * @param int $total_content Total content items
     * @param int $issues_count Number of content issues
     * @return int Safety score (0-100)
     */
    private function calculate_content_safety_score($total_content, $issues_count) {
        if ($total_content === 0) {
            return 100;
        }
        
        $issue_ratio = $issues_count / $total_content;
        $score = max(0, 100 - ($issue_ratio * 100));
        
        return (int) round($score);
    }
    
    /**
     * Check URL reputation using public APIs and local blacklists
     *
     * @param string $url URL to check
     * @param string $content_type Content type
     * @param int $content_id Content ID
     * @param string $content_title Content title
     * @return array Violations found
     */
    private function check_url_reputation($url, $content_type, $content_id, $content_title) {
        $violations = [];
        $domain = wp_parse_url($url, PHP_URL_HOST);
        
        if (!$domain) {
            return $violations;
        }
        
        // Check against known malicious domains (local blacklist)
        $known_bad_domains = [
            'bit.do', '0x00.name', '1337x.to', 'thepiratebay.org',
            'kickasstorrents.to', 'malware-domain.com', 'phishing-site.net'
        ];
        
        if (in_array(strtolower($domain), $known_bad_domains)) {
            $violations[] = [
                'type' => 'blacklisted_domain',
                'severity' => 'critical',
                'title' => 'Blacklisted Domain Detected',
                'description' => 'URL points to a known malicious or problematic domain',
                'details' => "Domain: {$domain} is on the blacklist",
                'recommendation' => 'Remove or replace this URL immediately',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'malicious_url' => $url,
                'category' => 'security_threat'
            ];
        }
        
        return $violations;
    }
    
    /**
     * Analyze URL structure for suspicious characteristics
     *
     * @param string $url URL to analyze
     * @param string $content_type Content type
     * @param int $content_id Content ID
     * @param string $content_title Content title
     * @return array Violations found
     */
    private function analyze_url_structure($url, $content_type, $content_id, $content_title) {
        $violations = [];
        $parsed = wp_parse_url($url);
        
        if (!$parsed) {
            return $violations;
        }
        
        $domain = $parsed['host'] ?? '';
        $path = $parsed['path'] ?? '';
        $query = $parsed['query'] ?? '';
        
        // Check for excessively long URLs (often used in phishing)
        if (strlen($url) > 200) {
            $violations[] = [
                'type' => 'excessive_url_length',
                'severity' => 'low',
                'title' => 'Excessively Long URL',
                'description' => 'URL is unusually long, which may indicate suspicious activity',
                'details' => "URL length: " . strlen($url) . " characters",
                'recommendation' => 'Verify URL legitimacy',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'suspicious_url' => $url,
                'category' => 'url_analysis'
            ];
        }
        
        // Check for suspicious query parameters
        $suspicious_params = ['redirect', 'goto', 'url', 'link', 'forward', 'continue'];
        foreach ($suspicious_params as $param) {
            if (strpos($query, $param . '=') !== false) {
                $violations[] = [
                    'type' => 'suspicious_redirect_param',
                    'severity' => 'medium',
                    'title' => 'Suspicious Redirect Parameter',
                    'description' => 'URL contains parameters that may be used for redirection attacks',
                    'details' => "Suspicious parameter: {$param}",
                    'recommendation' => 'Verify redirect destination is safe',
                    'content_type' => $content_type,
                    'content_id' => $content_id,
                    'content_title' => $content_title,
                    'suspicious_url' => $url,
                    'category' => 'url_analysis'
                ];
                break;
            }
        }
        
        return $violations;
    }
    
    /**
     * Statistical analysis of content characteristics
     *
     * @param string $content Content to analyze
     * @param string $content_type Content type
     * @param int $content_id Content ID
     * @param string $content_title Content title
     * @return array Violations found
     */
    private function analyze_content_statistics($content, $content_type, $content_id, $content_title) {
        $violations = [];
        
        if (strlen($content) < 10) {
            return $violations;
        }
        
        $words = str_word_count($content, 1);
        $total_words = count($words);
        $total_chars = strlen($content);
        
        // Calculate various statistics
        $avg_word_length = $total_chars / max($total_words, 1);
        $uppercase_ratio = (strlen($content) - strlen(preg_replace('/[A-Z]/', '', $content))) / $total_chars;
        $digit_ratio = (strlen($content) - strlen(preg_replace('/[0-9]/', '', $content))) / $total_chars;
        $special_char_ratio = (strlen($content) - strlen(preg_replace('/[^a-zA-Z0-9\s]/', '', $content))) / $total_chars;
        
        // Check for excessive uppercase (spam indicator)
        if ($uppercase_ratio > 0.5 && $total_chars > 20) {
            $violations[] = [
                'type' => 'excessive_uppercase',
                'severity' => 'low',
                'title' => 'Excessive Uppercase Usage',
                'description' => 'Content contains unusually high percentage of uppercase letters',
                'details' => sprintf("Uppercase ratio: %.1f%%", $uppercase_ratio * 100),
                'recommendation' => 'Review content formatting',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'category' => 'formatting_analysis'
            ];
        }
        
        // Check for excessive special characters (obfuscation indicator)
        if ($special_char_ratio > 0.3 && $total_chars > 20) {
            $violations[] = [
                'type' => 'excessive_special_chars',
                'severity' => 'medium',
                'title' => 'Excessive Special Characters',
                'description' => 'Content contains unusually high percentage of special characters',
                'details' => sprintf("Special character ratio: %.1f%%", $special_char_ratio * 100),
                'recommendation' => 'Check for content obfuscation attempts',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'category' => 'formatting_analysis'
            ];
        }
        
        return $violations;
    }
    
    /**
     * Analyze language patterns and encoding
     *
     * @param string $content Content to analyze
     * @param string $content_type Content type
     * @param int $content_id Content ID
     * @param string $content_title Content title
     * @return array Violations found
     */
    private function analyze_language_patterns($content, $content_type, $content_id, $content_title) {
        $violations = [];
        
        // Check for mixed scripts (potential homograph attacks)
        $has_latin = preg_match('/[a-zA-Z]/', $content);
        $has_cyrillic = preg_match('/[\p{Cyrillic}]/u', $content);
        $has_greek = preg_match('/[\p{Greek}]/u', $content);
        
        if ($has_latin && ($has_cyrillic || $has_greek)) {
            $violations[] = [
                'type' => 'mixed_script_homograph',
                'severity' => 'medium',
                'title' => 'Mixed Script Usage Detected',
                'description' => 'Content mixes Latin characters with Cyrillic or Greek (potential homograph attack)',
                'details' => 'Mixed character sets detected',
                'recommendation' => 'Verify content is not attempting character spoofing',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'category' => 'encoding_analysis'
            ];
        }
        
        // Check for unusual Unicode characters
        if (preg_match('/[\x{200B}-\x{200F}\x{2060}-\x{206F}]/u', $content)) {
            $violations[] = [
                'type' => 'hidden_unicode_chars',
                'severity' => 'medium',
                'title' => 'Hidden Unicode Characters',
                'description' => 'Content contains invisible or zero-width Unicode characters',
                'details' => 'Hidden Unicode characters detected',
                'recommendation' => 'Check for content manipulation attempts',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'category' => 'encoding_analysis'
            ];
        }
        
        return $violations;
    }
    
    /**
     * Analyze behavioral patterns in content
     *
     * @param string $content Content to analyze
     * @param string $content_type Content type
     * @param int $content_id Content ID
     * @param string $content_title Content title
     * @return array Violations found
     */
    private function analyze_behavioral_patterns($content, $content_type, $content_id, $content_title) {
        $violations = [];
        $content_lower = strtolower($content);
        
        // Check for urgency/pressure tactics
        $urgency_patterns = [
            '/\b(urgent|emergency|immediate|asap|hurry|quick|fast)\b/',
            '/\b(expires?|deadline|limited time|act now|don\'t wait)\b/',
            '/\b(last chance|final notice|only \d+ left)\b/'
        ];
        
        $urgency_matches = 0;
        foreach ($urgency_patterns as $pattern) {
            if (preg_match($pattern, $content_lower)) {
                $urgency_matches++;
            }
        }
        
        if ($urgency_matches >= 2) {
            $violations[] = [
                'type' => 'high_pressure_tactics',
                'severity' => 'medium',
                'title' => 'High-Pressure Tactics Detected',
                'description' => 'Content uses multiple urgency/pressure tactics commonly found in scams',
                'details' => "Found {$urgency_matches} urgency indicators",
                'recommendation' => 'Review content for potential deceptive practices',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'category' => 'behavioral_analysis'
            ];
        }
        
        // Check for excessive punctuation (spam indicator)
        $exclamation_count = substr_count($content, '!');
        $question_count = substr_count($content, '?');
        $total_punctuation = $exclamation_count + $question_count;
        
        if ($total_punctuation > 10 && strlen($content) < 500) {
            $violations[] = [
                'type' => 'excessive_punctuation',
                'severity' => 'low',
                'title' => 'Excessive Punctuation Usage',
                'description' => 'Content contains excessive exclamation marks or question marks',
                'details' => "Exclamation marks: {$exclamation_count}, Question marks: {$question_count}",
                'recommendation' => 'Review content formatting',
                'content_type' => $content_type,
                'content_id' => $content_id,
                'content_title' => $content_title,
                'category' => 'formatting_analysis'
            ];
        }
        
        return $violations;
    }
    
    /**
     * Calculate severity based on violation score
     *
     * @param float $score Violation score
     * @return string Severity level
     */
    private function calculate_severity($score) {
        if ($score >= 100) {
            return 'critical';
        } elseif ($score >= 50) {
            return 'high';
        } elseif ($score >= 25) {
            return 'medium';
        } else {
            return 'low';
        }
    }
    
    /**
     * Generate contextual recommendations based on violation type and score
     *
     * @param string $violation_type Type of violation
     * @param float $score Violation score
     * @return string Recommendation text
     */
    private function generate_recommendation($violation_type, $score) {
        $base_recommendations = [
            'adult_content' => 'Remove or restrict adult content to comply with content policies',
            'violence' => 'Remove violent content or threats - consider content warnings if educational',
            'hate_speech' => 'Remove discriminatory language and hate speech immediately',
            'illegal_activities' => 'Remove content promoting illegal activities',
            'spam_scam' => 'Remove spam patterns and deceptive marketing claims',
            'phishing' => 'Remove phishing content and suspicious links immediately',
            'malicious_links' => 'Remove potentially malicious downloads and links'
        ];
        
        $recommendation = $base_recommendations[$violation_type] ?? 'Review and modify content to comply with content policies';
        
        if ($score > 75) {
            $recommendation .= ' - HIGH PRIORITY: This content poses significant policy violations.';
        } elseif ($score > 50) {
            $recommendation .= ' - MODERATE PRIORITY: Multiple indicators suggest policy violations.';
        }
        
        return $recommendation;
    }
    
    /**
     * Real-time post scanning hook
     *
     * @param int $post_id Post ID
     * @param WP_Post $post Post object
     */
    public function scan_post_on_save($post_id, $post) {
        if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) {
            return;
        }
        
        $violations = $this->analyze_content($post->post_content, 'post', $post_id, $post->post_title);
        
        if (!empty($violations)) {
            // Save violations for immediate review
            $this->save_realtime_violations($violations, 'post_save');
            
            // Optionally, moderate the post
            if ($this->should_moderate_content($violations)) {
                wp_update_post([
                    'ID' => $post_id,
                    'post_status' => 'pending'
                ]);
            }
        }
    }
    
    /**
     * Real-time comment scanning hook
     *
     * @param int $comment_id Comment ID
     * @param array $comment_data Comment data
     */
    public function scan_comment_on_insert($comment_id, $comment_data) {
        $comment = get_comment($comment_id);
        
        if (!$comment) {
            return;
        }
        
        $violations = $this->analyze_content($comment->comment_content, 'comment', $comment_id, 'Comment #' . $comment_id);
        
        if (!empty($violations)) {
            $this->save_realtime_violations($violations, 'comment_insert');
            
            // Moderate comment if necessary
            if ($this->should_moderate_content($violations)) {
                wp_set_comment_status($comment_id, 'hold');
            }
        }
    }
    
    /**
     * Determine if content should be automatically moderated
     *
     * @param array $violations Array of violations
     * @return bool Whether to moderate content
     */
    private function should_moderate_content($violations) {
        $critical_count = 0;
        $high_count = 0;
        
        foreach ($violations as $violation) {
            if ($violation['severity'] === 'critical') {
                $critical_count++;
            } elseif ($violation['severity'] === 'high') {
                $high_count++;
            }
        }
        
        // Auto-moderate if any critical violations or multiple high violations
        return $critical_count > 0 || $high_count >= 2;
    }
    
    /**
     * Save real-time violations for immediate attention
     *
     * @param array $violations Violations found
     * @param string $trigger What triggered the scan
     */
    private function save_realtime_violations($violations, $trigger) {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'vmpfence_scan_issues';
        
        foreach ($violations as $violation) {
            $issue_data = [
                'scan_type' => $this->scan_type,
                'severity' => $violation['severity'],
                'title' => $violation['title'],
                'description' => $violation['description'],
                'details' => $violation['details'],
                'recommendation' => $violation['recommendation'],
                'status' => 'new',
                'created_at' => current_time('mysql'),
                'extra_data' => json_encode([
                    'content_type' => $violation['content_type'],
                    'content_id' => $violation['content_id'],
                    'content_title' => $violation['content_title'],
                    'trigger' => $trigger,
                    'category' => $violation['category'] ?? 'general',
                    'score' => $violation['score'] ?? 0
                ])
            ];
            
            $wpdb->insert($table_name, $issue_data);
        }
    }
    
    /**
     * Log debug messages
     *
     * @param string $message Debug message
     */
    private function log_debug($message) {
        if ($this->debug) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Using error_log for debugging purposes
            // error_log("VMPFence Content Safety Scanner: " . $message);
        }
    }
    
    /**
     * Get scan type identifier
     *
     * @return string Scan type
     */
    public function get_scan_type() {
        return $this->scan_type;
    }
}
