<?php
/**
 * VMPFence Severity Rating System
 * 
 * Severity Rating System
 * CRITICAL/HIGH/MEDIUM/LOW classification for security issues
 * 
 * @package VMPFence
 * @version 1.0.0
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class VMPFence_Severity_Rating {
    
    /**
     * Severity levels
     */
    const SEVERITY_CRITICAL = 'critical';
    const SEVERITY_HIGH = 'high';
    const SEVERITY_MEDIUM = 'medium';
    const SEVERITY_LOW = 'low';
    
    /**
     * Severity scoring thresholds
     */
    private $severity_thresholds = [
        'critical' => 85,    // Score >= 85: CRITICAL
        'high' => 65,        // Score 65-84: HIGH
        'medium' => 35,      // Score 35-64: MEDIUM
        'low' => 0           // Score < 35: LOW
    ];
    
    /**
     * Severity rating statistics
     */
    private $rating_stats = [
        'issues_rated' => 0,
        'critical_issues' => 0,
        'high_issues' => 0,
        'medium_issues' => 0,
        'low_issues' => 0,
        'total_rating_time' => 0
    ];
    
    /**
     * Debug log for rating operations
     */
    private $debug_log = [];
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->debug_log[] = '[Severity Rating] Engine initialized';
    }
    
    /**
     * Calculate comprehensive severity rating for an issue
     * 
     * @param array $issue_data Complete issue data with all engine results
     * @return array Severity assessment result
     */
    public function calculate_severity($issue_data) {
        $start_time = microtime(true);
        $this->rating_stats['issues_rated']++;
        
        $severity_assessment = [
            'severity_level' => self::SEVERITY_LOW,
            'severity_score' => 0,
            'severity_factors' => [],
            'priority_order' => 999,
            'risk_description' => '',
            'action_required' => 'monitor',
            'assessment_confidence' => 0
        ];
        
        // Factor 1: Repository and Core File Analysis (30 points max)
        $this->assess_repository_factors($severity_assessment, $issue_data);
        
        // Factor 2: Content and Pattern Analysis (25 points max)
        $this->assess_content_factors($severity_assessment, $issue_data);
        
        // Factor 3: Threat Intelligence Integration (20 points max)
        $this->assess_threat_factors($severity_assessment, $issue_data);
        
        // Factor 4: File Location and Context (15 points max)
        $this->assess_location_factors($severity_assessment, $issue_data);
        
        // Factor 5: Legitimacy and Trust Assessment (10 points max)
        $this->assess_legitimacy_factors($severity_assessment, $issue_data);
        
        // Calculate final severity level and recommendations
        $this->finalize_severity_assessment($severity_assessment, $issue_data);
        
        // Update statistics
        $this->update_severity_statistics($severity_assessment);
        
        // Track rating time
        $rating_time = microtime(true) - $start_time;
        $this->rating_stats['total_rating_time'] += $rating_time;
        
        $this->debug_log[] = '[Severity Rating] Issue: ' . ($issue_data['relative_path'] ?? 'unknown') . 
                           ' (Level: ' . $severity_assessment['severity_level'] . 
                           ', Score: ' . $severity_assessment['severity_score'] . ')';
        
        return $severity_assessment;
    }
    
    /**
     * Assess repository and core file factors
     */
    private function assess_repository_factors(&$assessment, $issue_data) {
        $score = 0;
        $factors = [];
        
        // Critical: Core WordPress files modified
        if (isset($issue_data['issue_type']) && $issue_data['issue_type'] === 'modified') {
            if (isset($issue_data['metadata']['repository_verified']) && $issue_data['metadata']['repository_verified']) {
                $score += 25;
                $factors[] = 'Modified WordPress core file (+25)';
                
                // Extra severity for critical system files
                $relative_path = $issue_data['relative_path'] ?? '';
                if (preg_match('/^(wp-admin|wp-includes)\//', $relative_path)) {
                    $score += 5;
                    $factors[] = 'Critical system directory (+5)';
                }
            }
        }
        
        // High: Plugin/theme integrity violations
        if (isset($issue_data['issue_type']) && in_array($issue_data['issue_type'], ['plugin_update', 'theme_update'])) {
            $score += 15;
            $factors[] = 'Plugin/theme integrity issue (+15)';
        }
        
        // Medium: Unknown files in core areas
        if (isset($issue_data['issue_type']) && $issue_data['issue_type'] === 'unknown_threat') {
            $relative_path = $issue_data['relative_path'] ?? '';
            if (preg_match('/^(wp-admin|wp-includes|wp-content\/(plugins|themes))\//', $relative_path)) {
                $score += 10;
                $factors[] = 'Unknown file in core area (+10)';
            }
        }
        
        $assessment['severity_score'] += $score;
        $assessment['severity_factors'] = array_merge($assessment['severity_factors'], $factors);
    }
    
    /**
     * Assess content and pattern analysis factors
     */
    private function assess_content_factors(&$assessment, $issue_data) {
        $score = 0;
        $factors = [];
        
        // Critical: Malicious content patterns detected
        if (isset($issue_data['metadata']['content_analysis'])) {
            $content_data = $issue_data['metadata']['content_analysis'];
            
            if (isset($content_data['threat_level'])) {
                switch ($content_data['threat_level']) {
                    case 'critical':
                        $score += 25;
                        $factors[] = 'Critical malicious content detected (+25)';
                        break;
                    case 'high':
                        $score += 20;
                        $factors[] = 'High-risk content patterns (+20)';
                        break;
                    case 'medium':
                        $score += 10;
                        $factors[] = 'Suspicious content patterns (+10)';
                        break;
                    case 'low':
                        $score += 5;
                        $factors[] = 'Minor content concerns (+5)';
                        break;
                }
            }
            
            // Additional scoring for high-risk content scores
            if (isset($content_data['risk_score'])) {
                $risk_score = intval($content_data['risk_score']);
                if ($risk_score >= 100) {
                    $score += 5;
                    $factors[] = 'Extreme content risk score (+5)';
                } elseif ($risk_score >= 75) {
                    $score += 3;
                    $factors[] = 'High content risk score (+3)';
                }
            }
        }
        
        // SHAC pattern analysis
        if (isset($issue_data['metadata']['suspicious_patterns'])) {
            $pattern_count = count($issue_data['metadata']['suspicious_patterns']);
            if ($pattern_count >= 5) {
                $score += 8;
                $factors[] = 'Multiple suspicious patterns (+8)';
            } elseif ($pattern_count >= 2) {
                $score += 4;
                $factors[] = 'Several suspicious patterns (+4)';
            }
        }
        
        $assessment['severity_score'] += $score;
        $assessment['severity_factors'] = array_merge($assessment['severity_factors'], $factors);
    }
    
    /**
     * Assess threat intelligence factors
     */
    private function assess_threat_factors(&$assessment, $issue_data) {
        $score = 0;
        $factors = [];
        
        // Critical: Known malware signatures
        if (isset($issue_data['issue_type']) && $issue_data['issue_type'] === 'malicious_content') {
            $score += 20;
            $factors[] = 'Known malware signature detected (+20)';
        }
        
        // High: Threat intelligence matches
        if (isset($issue_data['metadata']['threat_level'])) {
            switch ($issue_data['metadata']['threat_level']) {
                case 'critical':
                    $score += 15;
                    $factors[] = 'Critical threat intelligence match (+15)';
                    break;
                case 'high':
                    $score += 12;
                    $factors[] = 'High threat intelligence match (+12)';
                    break;
                case 'medium':
                    $score += 8;
                    $factors[] = 'Medium threat intelligence match (+8)';
                    break;
            }
        }
        
        // Unknown file threat classification
        if (isset($issue_data['metadata']['classification'])) {
            $classification = $issue_data['metadata']['classification'];
            if ($classification === 'malware_like') {
                $score += 12;
                $factors[] = 'Malware-like characteristics (+12)';
            } elseif ($classification === 'highly_suspicious') {
                $score += 8;
                $factors[] = 'Highly suspicious file (+8)';
            } elseif ($classification === 'suspicious') {
                $score += 5;
                $factors[] = 'Suspicious file characteristics (+5)';
            }
        }
        
        $assessment['severity_score'] += $score;
        $assessment['severity_factors'] = array_merge($assessment['severity_factors'], $factors);
    }
    
    /**
     * Assess file location and context factors
     */
    private function assess_location_factors(&$assessment, $issue_data) {
        $score = 0;
        $factors = [];
        
        $relative_path = $issue_data['relative_path'] ?? '';
        
        // Critical locations
        if (preg_match('/^wp-config\.php$/', $relative_path)) {
            $score += 15;
            $factors[] = 'WordPress configuration file (+15)';
        } elseif (preg_match('/^wp-admin\/(admin|index|admin-ajax)\.php$/', $relative_path)) {
            $score += 12;
            $factors[] = 'Core admin functionality (+12)';
        } elseif (preg_match('/^wp-includes\/(wp-db|functions|class-wp)/', $relative_path)) {
            $score += 10;
            $factors[] = 'Core WordPress functionality (+10)';
        }
        
        // High-risk locations
        elseif (preg_match('/^wp-content\/uploads\/.*\.php$/', $relative_path)) {
            $score += 12;
            $factors[] = 'PHP file in uploads directory (+12)';
        } elseif (preg_match('/\.(php|js)$/', $relative_path) && preg_match('/^wp-content\/themes\/[^\/]+\/(functions\.php|header\.php|footer\.php)/', $relative_path)) {
            $score += 8;
            $factors[] = 'Critical theme file (+8)';
        }
        
        // Suspicious file patterns
        if (preg_match('/\.(tmp|temp|bak|old|suspect)$/i', $relative_path)) {
            $score += 6;
            $factors[] = 'Suspicious file extension (+6)';
        }
        
        // Hidden or obfuscated files
        if (preg_match('/\/\.[^\/]+\.php$/', $relative_path) || preg_match('/[a-f0-9]{32,}\.php$/', $relative_path)) {
            $score += 8;
            $factors[] = 'Hidden or obfuscated filename (+8)';
        }
        
        $assessment['severity_score'] += $score;
        $assessment['severity_factors'] = array_merge($assessment['severity_factors'], $factors);
    }
    
    /**
     * Assess legitimacy and trust factors
     */
    private function assess_legitimacy_factors(&$assessment, $issue_data) {
        $score = 0;
        $factors = [];
        
        // Legitimacy assessment integration
        if (isset($issue_data['metadata']['legitimacy_assessment'])) {
            $legitimacy = $issue_data['metadata']['legitimacy_assessment'];
            
            if (isset($legitimacy['legitimacy_level'])) {
                switch ($legitimacy['legitimacy_level']) {
                    case 'malicious':
                        $score += 10;
                        $factors[] = 'Assessed as malicious (+10)';
                        break;
                    case 'suspicious':
                        $score += 6;
                        $factors[] = 'Assessed as suspicious (+6)';
                        break;
                    case 'legitimate':
                        // Reduce severity for legitimate files
                        $score -= 5;
                        $factors[] = 'Assessed as legitimate (-5)';
                        break;
                }
            }
            
            // Low confidence in legitimacy increases severity
            if (isset($legitimacy['confidence']) && $legitimacy['confidence'] < 50) {
                $score += 3;
                $factors[] = 'Low legitimacy confidence (+3)';
            }
        }
        
        // Known file database status
        if (isset($issue_data['metadata']['file_type'])) {
            $file_type = $issue_data['metadata']['file_type'];
            if ($file_type === 'unknown' || $file_type === 'suspicious') {
                $score += 4;
                $factors[] = 'Unknown file type (+4)';
            }
        }
        
        $assessment['severity_score'] += $score;
        $assessment['severity_factors'] = array_merge($assessment['severity_factors'], $factors);
    }
    
    /**
     * Finalize severity assessment and set recommendations
     */
    private function finalize_severity_assessment(&$assessment, $issue_data) {
        $score = $assessment['severity_score'];
        
        // Determine severity level
        if ($score >= $this->severity_thresholds['critical']) {
            $assessment['severity_level'] = self::SEVERITY_CRITICAL;
            $assessment['priority_order'] = 1;
            $assessment['action_required'] = 'immediate_action';
            $assessment['risk_description'] = 'Immediate security threat requiring urgent intervention';
            $assessment['assessment_confidence'] = min(95, 70 + ($score - 85));
        } elseif ($score >= $this->severity_thresholds['high']) {
            $assessment['severity_level'] = self::SEVERITY_HIGH;
            $assessment['priority_order'] = 2;
            $assessment['action_required'] = 'prompt_review';
            $assessment['risk_description'] = 'Significant security concern needing prompt attention';
            $assessment['assessment_confidence'] = min(90, 60 + ($score - 65));
        } elseif ($score >= $this->severity_thresholds['medium']) {
            $assessment['severity_level'] = self::SEVERITY_MEDIUM;
            $assessment['priority_order'] = 3;
            $assessment['action_required'] = 'investigate';
            $assessment['risk_description'] = 'Moderate security risk requiring investigation';
            $assessment['assessment_confidence'] = min(85, 50 + ($score - 35));
        } else {
            $assessment['severity_level'] = self::SEVERITY_LOW;
            $assessment['priority_order'] = 4;
            $assessment['action_required'] = 'monitor';
            $assessment['risk_description'] = 'Low-priority security concern for monitoring';
            $assessment['assessment_confidence'] = min(80, 40 + $score);
        }
        
        // Special overrides for critical situations
        $this->apply_severity_overrides($assessment, $issue_data);
    }
    
    /**
     * Apply special severity overrides for critical situations
     */
    private function apply_severity_overrides(&$assessment, $issue_data) {
        // Override 1: wp-config.php modifications are always critical
        if (isset($issue_data['relative_path']) && $issue_data['relative_path'] === 'wp-config.php') {
            $assessment['severity_level'] = self::SEVERITY_CRITICAL;
            $assessment['priority_order'] = 1;
            $assessment['action_required'] = 'immediate_action';
            $assessment['severity_factors'][] = 'Critical override: wp-config.php modification';
        }
        
        // Override 2: Multiple malicious indicators = critical
        $malicious_indicators = 0;
        if (isset($issue_data['metadata']['content_analysis']['threat_level']) && 
            in_array($issue_data['metadata']['content_analysis']['threat_level'], ['critical', 'high'])) {
            $malicious_indicators++;
        }
        if (isset($issue_data['metadata']['legitimacy_assessment']['legitimacy_level']) && 
            $issue_data['metadata']['legitimacy_assessment']['legitimacy_level'] === 'malicious') {
            $malicious_indicators++;
        }
        if (isset($issue_data['issue_type']) && $issue_data['issue_type'] === 'malicious_content') {
            $malicious_indicators++;
        }
        
        if ($malicious_indicators >= 2) {
            $assessment['severity_level'] = self::SEVERITY_CRITICAL;
            $assessment['priority_order'] = 1;
            $assessment['severity_factors'][] = 'Critical override: Multiple malicious indicators';
        }
        
        // Override 3: Known legitimate files with minor issues = low severity
        if (isset($issue_data['metadata']['legitimacy_assessment']['legitimacy_level']) && 
            $issue_data['metadata']['legitimacy_assessment']['legitimacy_level'] === 'legitimate' &&
            $assessment['severity_score'] < 40) {
            $assessment['severity_level'] = self::SEVERITY_LOW;
            $assessment['priority_order'] = 4;
            $assessment['severity_factors'][] = 'Override: Legitimate file with minor concerns';
        }
    }
    
    /**
     * Update severity statistics
     */
    private function update_severity_statistics($assessment) {
        switch ($assessment['severity_level']) {
            case self::SEVERITY_CRITICAL:
                $this->rating_stats['critical_issues']++;
                break;
            case self::SEVERITY_HIGH:
                $this->rating_stats['high_issues']++;
                break;
            case self::SEVERITY_MEDIUM:
                $this->rating_stats['medium_issues']++;
                break;
            case self::SEVERITY_LOW:
                $this->rating_stats['low_issues']++;
                break;
        }
    }
    
    /**
     * Generate severity issue description for database
     */
    public function generate_severity_description($assessment) {
        $level = strtoupper($assessment['severity_level']);
        $score = $assessment['severity_score'];
        $confidence = $assessment['assessment_confidence'];
        
        $description = "Severity: {$level} (Score: {$score}, Confidence: {$confidence}%) - {$assessment['risk_description']}";
        
        if (!empty($assessment['severity_factors'])) {
            $description .= " | Factors: " . implode(', ', $assessment['severity_factors']);
        }
        
        $description .= " | Action: " . ucfirst(str_replace('_', ' ', $assessment['action_required']));
        
        return $description;
    }
    
    /**
     * Get severity statistics
     */
    public function get_severity_stats() {
        $stats = $this->rating_stats;
        
        // Calculate average rating time
        if ($stats['issues_rated'] > 0) {
            $stats['avg_rating_time'] = round(($stats['total_rating_time'] / $stats['issues_rated']) * 1000, 2) . 'ms';
        } else {
            $stats['avg_rating_time'] = '0ms';
        }
        
        // Calculate severity distribution
        if ($stats['issues_rated'] > 0) {
            $stats['severity_distribution'] = [
                'critical' => round(($stats['critical_issues'] / $stats['issues_rated']) * 100, 1) . '%',
                'high' => round(($stats['high_issues'] / $stats['issues_rated']) * 100, 1) . '%',
                'medium' => round(($stats['medium_issues'] / $stats['issues_rated']) * 100, 1) . '%',
                'low' => round(($stats['low_issues'] / $stats['issues_rated']) * 100, 1) . '%'
            ];
        }
        
        return $stats;
    }
    
    /**
     * Get debug log
     */
    public function get_debug_log() {
        return $this->debug_log;
    }
    
    /**
     * Reset statistics for new scan
     */
    public function reset_stats() {
        $this->rating_stats = [
            'issues_rated' => 0,
            'critical_issues' => 0,
            'high_issues' => 0,
            'medium_issues' => 0,
            'low_issues' => 0,
            'total_rating_time' => 0
        ];
        $this->debug_log = ['[Severity Rating] Statistics reset for new scan'];
    }
    
    /**
     * Get severity level color for UI display
     */
    public function get_severity_color($severity_level) {
        switch ($severity_level) {
            case self::SEVERITY_CRITICAL:
                return '#dc3545'; // Red
            case self::SEVERITY_HIGH:
                return '#fd7e14'; // Orange
            case self::SEVERITY_MEDIUM:
                return '#ffc107'; // Yellow
            case self::SEVERITY_LOW:
                return '#28a745'; // Green
            default:
                return '#6c757d'; // Gray
        }
    }
    
    /**
     * Sort issues by severity priority
     */
    public function sort_issues_by_severity($issues) {
        if (empty($issues)) {
            return $issues;
        }
        
        // Sort by priority order (1 = highest priority)
        usort($issues, function($a, $b) {
            $priority_a = isset($a['severity_assessment']['priority_order']) ? $a['severity_assessment']['priority_order'] : 999;
            $priority_b = isset($b['severity_assessment']['priority_order']) ? $b['severity_assessment']['priority_order'] : 999;
            
            if ($priority_a === $priority_b) {
                // Secondary sort by severity score (higher = more severe)
                $score_a = isset($a['severity_assessment']['severity_score']) ? $a['severity_assessment']['severity_score'] : 0;
                $score_b = isset($b['severity_assessment']['severity_score']) ? $b['severity_assessment']['severity_score'] : 0;
                return $score_b - $score_a;
            }
            
            return $priority_a - $priority_b;
        });
        
        return $issues;
    }
}
