<?php
/**
 * 
 * 
 * WordPress file verification against official checksums
 * 
 * 
 */

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

class VMPFence_WP_Integrity_Checker {
    
    private $wp_api_base = 'https://api.wordpress.org';
    private $checksum_cache = array();
    private $cache_ttl = 86400; // 24 hours
    private $debug_log = array();
    private $stats = array(
        'core_files_checked' => 0,
        'plugin_files_checked' => 0,
        'theme_files_checked' => 0,
        'modified_files_found' => 0,
        'api_calls_made' => 0,
        'cache_hits' => 0
    );
    
    public function __construct() {
        // Ensure WordPress constants are available
        if (!defined('ABSPATH')) {
            throw new Exception('WordPress ABSPATH not defined. Please load WordPress before using this class.');
        }
        
        if (!defined('WP_PLUGIN_DIR')) {
            if (!function_exists('wp_plugin_directory_constants')) {
                define('WP_PLUGIN_DIR', ABSPATH . 'wp-content/plugins');
            } else {
                wp_plugin_directory_constants();
            }
        }
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] WP Integrity Checker initialized';
        $this->debug_log[] = '[' . current_time('H:i:s') . '] ABSPATH: ' . ABSPATH;
        $this->debug_log[] = '[' . current_time('H:i:s') . '] WP_PLUGIN_DIR: ' . WP_PLUGIN_DIR;
    }
    
    /**
     * Verify WordPress core files
     */
    public function verify_core_files($wp_version = null) {
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Starting core file verification...';
        
        if (!$wp_version) {
            $wp_version = get_bloginfo('version');
        }
        
        $issues = array();
        
        // Get official WordPress core checksums
        $core_checksums = $this->get_official_checksums('core', $wp_version);
        
        if (!$core_checksums) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Failed to get core checksums for version ' . $wp_version;
            return array();
        }
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Retrieved ' . count($core_checksums) . ' core file checksums';
        
        // Verify each core file
        foreach ($core_checksums as $file_path => $expected_hash) {
            // Skip invalid entries - version numbers shouldn't be file paths
            if (preg_match('/^\d+\.\d+/', $file_path) || empty($file_path) || !is_string($file_path)) {
                $this->debug_log[] = '[' . current_time('H:i:s') . '] Skipping invalid file path: ' . $file_path;
                continue;
            }
            
            // Skip if hash is not a string
            if (!is_string($expected_hash) || empty($expected_hash)) {
                $this->debug_log[] = '[' . current_time('H:i:s') . '] Skipping file with invalid hash: ' . $file_path . ' (hash type: ' . gettype($expected_hash) . ')';
                continue;
            }
            
            $full_path = ABSPATH . $file_path;
            
            // Always increment the files checked counter
            $this->stats['core_files_checked']++;
            
            if (!file_exists($full_path)) {
                // Missing core file
                $issues[] = array(
                    'type' => 'missing_core_file',
                    'severity' => 'critical',
                    'title' => 'Missing WordPress Core File',
                    'description' => 'Required WordPress core file is missing',
                    'location' => $file_path,
                    'details' => 'Expected file: ' . $file_path . ' | Status: Missing',
                    'recommendation' => 'Restore the missing WordPress core file from official distribution',
                    'expected_hash' => $expected_hash,
                    'actual_hash' => null,
                    'file_status' => 'missing'
                );
                
                $this->debug_log[] = '[' . current_time('H:i:s') . '] MISSING CORE FILE: ' . $file_path;
                continue;
            }
            
            // Calculate actual file hash
            $actual_hash = md5_file($full_path);
            
            if ($actual_hash !== $expected_hash) {
                // Modified core file
                $issues[] = array(
                    'type' => 'modified_core_file',
                    'severity' => 'high',
                    'title' => 'Modified WordPress Core File',
                    'description' => 'WordPress core file has been modified from official version',
                    'location' => $file_path,
                    'details' => 'File: ' . $file_path . ' | Expected: ' . $expected_hash . ' | Actual: ' . $actual_hash,
                    'recommendation' => 'Review file changes and restore from official WordPress if compromised',
                    'expected_hash' => $expected_hash,
                    'actual_hash' => $actual_hash,
                    'file_status' => 'modified',
                    'file_size' => filesize($full_path)
                );
                
                $this->stats['modified_files_found']++;
                $this->debug_log[] = '[' . current_time('H:i:s') . '] MODIFIED CORE FILE: ' . $file_path;
            }
        }
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Core verification complete. Found ' . count($issues) . ' issues';
        
        return $issues;
    }
    
    /**
     * Verify plugin files
     */
    public function verify_plugin_files($plugin_slugs = null) {
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Starting plugin file verification...';
        
        $issues = array();
        
        // Get ALL plugins if no specific plugins specified
        if (!$plugin_slugs) {
            if (!function_exists('get_plugins')) {
                require_once ABSPATH . 'wp-admin/includes/plugin.php';
            }
            
            $all_plugins = get_plugins(); // Get all plugins (active + inactive + custom)
            $plugin_slugs = array();
            
            foreach (array_keys($all_plugins) as $plugin_path) {
                $plugin_slug = dirname($plugin_path);
                // Only include directory-based plugins (exclude single files like hello.php)
                if ($plugin_slug !== '.' && is_dir(WP_PLUGIN_DIR . '/' . $plugin_slug)) {
                    $plugin_slugs[] = $plugin_slug;
                }
            }
        }
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Checking ' . count($plugin_slugs) . ' plugins: ' . implode(', ', $plugin_slugs);
        
        foreach ($plugin_slugs as $plugin_slug) {
            $plugin_issues = $this->verify_single_plugin($plugin_slug);
            $issues = array_merge($issues, $plugin_issues);
        }
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Plugin verification complete. Found ' . count($issues) . ' issues';
        
        return $issues;
    }
    
    /**
     * Verify a single plugin
     */
    private function verify_single_plugin($plugin_slug) {
        $issues = array();
        
        // Get plugin info
        $plugin_data = $this->get_plugin_data($plugin_slug);
        if (!$plugin_data) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Could not get plugin data for: ' . $plugin_slug;
            return array();
        }
        
        // PRIORITY FIX #1: Check if plugin exists in repository first
        $plugin_info = $this->get_plugin_repository_info($plugin_slug);
        if (!$plugin_info) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Plugin not in WordPress.org repository: ' . $plugin_slug;
            return array(); // Skip plugins not in official repository
        }
        
        // PRIORITY FIX #1: Version compatibility check
        $installed_version = $plugin_data['version'];
        $latest_version = $plugin_info['version'];
        
        if (version_compare($installed_version, $latest_version, '!=')) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Version mismatch for ' . $plugin_slug . ': installed=' . $installed_version . ', latest=' . $latest_version;
            
            // Only flag if version is significantly different or suspicious
            if ($this->is_suspicious_version_difference($installed_version, $latest_version)) {
                return array(array(
                    'type' => 'suspicious_plugin_version',
                    'severity' => 'medium',
                    'title' => 'Suspicious Plugin Version',
                    'description' => 'Plugin version differs significantly from official repository',
                    'location' => 'wp-content/plugins/' . $plugin_slug,
                    'details' => 'Installed: ' . $installed_version . ', Repository: ' . $latest_version,
                    'recommendation' => 'Update plugin to latest version or verify legitimacy',
                    'plugin_slug' => $plugin_slug,
                    'installed_version' => $installed_version,
                    'repository_version' => $latest_version
                ));
            }
            
            // Skip integrity check for minor version differences
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Skipping integrity check due to version mismatch: ' . $plugin_slug;
            return array();
        }
        
        // Get official plugin checksums for exact version
        $plugin_checksums = $this->get_official_checksums('plugin', $plugin_slug, $plugin_data['version']);
        
        if (!$plugin_checksums) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] No checksums available for plugin version: ' . $plugin_slug . ' v' . $installed_version;
            return array();
        }
        
        $plugin_path = WP_PLUGIN_DIR . '/' . $plugin_slug . '/';
        
        // PRIORITY FIX #2: Define smart file patterns
        $dynamic_file_patterns = array(
            // Cache and temporary files
            '/\/cache\/.*/i',
            '/\/tmp\/.*/i',
            '/\/temp\/.*/i',
            '/\.cache$/i',
            '/\.tmp$/i',
            '/\.log$/i',
            
            // Config and settings files that change
            '/config\.php$/i',
            '/settings\.php$/i',
            '/options\.php$/i',
            
            // Wordfence specific dynamic files
            '/\/waf\/.*/i',
            '/wfWAF.*\.php$/i',
            '/wordfence.*config.*\.php$/i',
            
            // Build and vendor files (commonly change)
            '/\/vendor\/.*/i',
            '/\/node_modules\/.*/i',
            '/\/build\/.*/i',
            '/\/dist\/.*/i',
            '/composer\.lock$/i',
            '/package-lock\.json$/i',
            
            // Documentation files
            '/readme\.txt$/i',
            '/changelog\.txt$/i',
            '/license\.txt$/i'
        );
        
        $commonly_missing_patterns = array(
            // Generated/dynamic files that may not exist in distribution
            '/\/languages?\/.*/i',
            '/\/assets\/build\/.*/i',
            '/\/assets\/dist\/.*/i',
            '/installed\.php$/i',
            '/autoload\.php$/i'
        );
        
        // Verify each plugin file
        foreach ($plugin_checksums as $file_path => $expected_hash) {
            $full_path = $plugin_path . $file_path;
            
            // PRIORITY FIX #2: Skip dynamic files
            $is_dynamic = false;
            foreach ($dynamic_file_patterns as $pattern) {
                if (preg_match($pattern, $file_path)) {
                    $is_dynamic = true;
                    $this->debug_log[] = '[' . current_time('H:i:s') . '] Skipping dynamic file: ' . $file_path;
                    break;
                }
            }
            if ($is_dynamic) continue;
            
            if (!file_exists($full_path)) {
                // PRIORITY FIX #2: Skip commonly missing files
                $is_commonly_missing = false;
                foreach ($commonly_missing_patterns as $pattern) {
                    if (preg_match($pattern, $file_path)) {
                        $is_commonly_missing = true;
                        $this->debug_log[] = '[' . current_time('H:i:s') . '] Skipping commonly missing file: ' . $file_path;
                        break;
                    }
                }
                if ($is_commonly_missing) continue;
                
                // Missing plugin file (only for core files)
                $issues[] = array(
                    'type' => 'missing_plugin_file',
                    'severity' => 'high', // Reduced from critical
                    'title' => 'Missing Core Plugin File',
                    'description' => 'Essential plugin file is missing from installation',
                    'location' => 'wp-content/plugins/' . $plugin_slug . '/' . $file_path,
                    'details' => 'Plugin: ' . $plugin_slug . ' | Missing core file: ' . $file_path,
                    'recommendation' => 'Reinstall the plugin from WordPress.org',
                    'plugin_slug' => $plugin_slug,
                    'plugin_version' => $plugin_data['version'],
                    'expected_hash' => $expected_hash,
                    'actual_hash' => null,
                    'file_status' => 'missing'
                );
                continue;
            }
            
            // Calculate actual file hash
            $actual_hash = md5_file($full_path);
            $this->stats['plugin_files_checked']++;
            
            if ($actual_hash !== $expected_hash) {
                // PRIORITY FIX #3: Context-aware severity scoring
                $file_age_hours = (time() - filemtime($full_path)) / 3600;
                $file_size = filesize($full_path);
                
                // Determine severity based on context
                $severity = 'medium';
                if ($file_age_hours < 24) {
                    // Recently modified - likely legitimate update
                    $severity = 'low';
                } elseif ($file_age_hours > 720) { // 30 days
                    // Old modification - more suspicious
                    $severity = 'high';
                }
                
                // Adjust severity based on plugin trust level
                $trusted_plugins = array('wordfence', 'akismet', 'jetpack', 'woocommerce', 'yoast-seo');
                if (in_array($plugin_slug, $trusted_plugins)) {
                    // Reduce severity for trusted plugins
                    $severity = ($severity === 'high') ? 'medium' : 'low';
                }
                
                // Check if file extension is commonly modified
                $extension = pathinfo($file_path, PATHINFO_EXTENSION);
                $safe_extensions = array('txt', 'md', 'json', 'css');
                if (in_array(strtolower($extension), $safe_extensions)) {
                    $severity = 'low'; // These files commonly change
                }
                
                $age_description = ($file_age_hours < 24) ? 
                    ' (modified ' . round($file_age_hours, 1) . 'h ago)' : 
                    ' (modified ' . round($file_age_hours / 24, 1) . 'd ago)';
                
                // Modified plugin file
                $issues[] = array(
                    'type' => 'modified_plugin_file',
                    'severity' => $severity,
                    'title' => 'Modified Plugin File',
                    'description' => 'Plugin file differs from official version' . $age_description,
                    'location' => 'wp-content/plugins/' . $plugin_slug . '/' . $file_path,
                    'details' => 'Plugin: ' . $plugin_slug . ' v' . $plugin_data['version'] . ' | File: ' . $file_path,
                    'recommendation' => ($severity === 'high') ? 
                        'Investigate modification - may be compromised' : 
                        'Review changes or reinstall if concerned',
                    'plugin_slug' => $plugin_slug,
                    'plugin_version' => $plugin_data['version'],
                    'expected_hash' => $expected_hash,
                    'actual_hash' => $actual_hash,
                    'file_status' => 'modified',
                    'file_size' => $file_size,
                    'modification_age_hours' => round($file_age_hours, 1)
                );
                
                $this->stats['modified_files_found']++;
                $this->debug_log[] = '[' . current_time('H:i:s') . '] MODIFIED PLUGIN FILE (' . $severity . '): ' . $plugin_slug . '/' . $file_path;
            }
        }
        
        return $issues;
    }
    
    /**
     * Get official checksums from WordPress.org API
     */
    public function get_official_checksums($type, $slug_or_version, $version = null) {
        // Check cache first
        $cache_key = $type . '_' . $slug_or_version . '_' . ($version ?: 'latest');
        
        if (isset($this->checksum_cache[$cache_key])) {
            $cached_data = $this->checksum_cache[$cache_key];
            if (time() - $cached_data['timestamp'] < $this->cache_ttl) {
                $this->stats['cache_hits']++;
                $this->debug_log[] = '[' . current_time('H:i:s') . '] Using cached checksums for: ' . $cache_key;
                return $cached_data['checksums'];
            }
        }
        
        $checksums = null;
        
        if ($type === 'core') {
            $checksums = $this->get_core_checksums($slug_or_version);
        } elseif ($type === 'plugin') {
            $checksums = $this->get_plugin_checksums($slug_or_version, $version);
        }
        
        // Cache the results
        if ($checksums !== null) {
            $this->checksum_cache[$cache_key] = array(
                'checksums' => $checksums,
                'timestamp' => time()
            );
        }
        
        return $checksums;
    }
    
    /**
     * Get WordPress core checksums
     */
    private function get_core_checksums($wp_version) {
        $url = $this->wp_api_base . '/core/checksums/1.0/?version=' . $wp_version;
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Fetching core checksums: ' . $url;
        $this->stats['api_calls_made']++;
        
        $response = wp_remote_get($url, array(
            'timeout' => 30,
            'user-agent' => 'VMPFence/' . (defined('VMPFENCE_VERSION') ? VMPFENCE_VERSION : '1.0') . '; ' . home_url()
        ));
        
        if (is_wp_error($response)) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] API error: ' . $response->get_error_message();
            return null;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['checksums'])) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Invalid API response for core checksums';
            return null;
        }
        
        return $data['checksums'];
    }
    
    /**
     * Get plugin repository info from WordPress.org API
     */
    private function get_plugin_repository_info($plugin_slug) {
        $url = $this->wp_api_base . '/plugins/info/1.0/' . $plugin_slug . '.json';
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Fetching plugin info: ' . $url;
        $this->stats['api_calls_made']++;
        
        $response = wp_remote_get($url, array(
            'timeout' => 30,
            'user-agent' => 'VMPFence/' . (defined('VMPFENCE_VERSION') ? VMPFENCE_VERSION : '1.0') . '; ' . home_url()
        ));
        
        if (is_wp_error($response)) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Plugin API error: ' . $response->get_error_message();
            return null;
        }
        
        $http_code = wp_remote_retrieve_response_code($response);
        if ($http_code !== 200) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Plugin not found in repository: ' . $plugin_slug;
            return null;
        }
        
        $response_body = wp_remote_retrieve_body($response);
        $plugin_info = json_decode($response_body, true);
        
        if (!$plugin_info || !isset($plugin_info['version'])) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Invalid plugin info response: ' . $plugin_slug;
            return null;
        }
        
        return $plugin_info;
    }
    
    /**
     * Check if version difference is suspicious
     */
    private function is_suspicious_version_difference($installed, $latest) {
        // Parse versions
        $installed_parts = explode('.', $installed);
        $latest_parts = explode('.', $latest);
        
        // If installed version is newer, it might be a pre-release or custom build
        if (version_compare($installed, $latest, '>')) {
            return true;
        }
        
        // If major version differs significantly, it's suspicious
        $installed_major = (int)($installed_parts[0] ?? 0);
        $latest_major = (int)($latest_parts[0] ?? 0);
        
        if (abs($installed_major - $latest_major) > 1) {
            return true;
        }
        
        // If installed version is very old compared to latest
        if (version_compare($installed, $latest, '<')) {
            $installed_minor = (int)($installed_parts[1] ?? 0);
            $latest_minor = (int)($latest_parts[1] ?? 0);
            
            // More than 5 minor versions behind is suspicious
            if (($latest_minor - $installed_minor) > 5) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * Get plugin checksums
     */
    private function get_plugin_checksums($plugin_slug, $version) {
        // Get plugin repository info first
        $plugin_info = $this->get_plugin_repository_info($plugin_slug);
        
        if (!$plugin_info) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Plugin not in repository: ' . $plugin_slug;
            return null;
        }
        
        // Check if we have the right version
        if ($plugin_info['version'] !== $version) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Version mismatch for ' . $plugin_slug . ': installed=' . $version . ', repository=' . $plugin_info['version'];
            return null; // Don't verify mismatched versions
        }
        
        // ACTUAL PRODUCTION IMPLEMENTATION: Download plugin ZIP and generate checksums
        return $this->download_and_verify_plugin($plugin_slug, $plugin_info, $version);
    }
    
    /**
     * Download and verify plugin against official distribution
     */
    private function download_and_verify_plugin($plugin_slug, $plugin_info, $version) {
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Starting actual plugin download and verification for: ' . $plugin_slug;
        
        $download_url = $plugin_info['download_link'];
        $checksums = array();
        
        // Create temporary directory for plugin verification
        $temp_dir = wp_upload_dir()['basedir'] . '/vmpfence_temp_' . time();
        if (!wp_mkdir_p($temp_dir)) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Failed to create temp directory: ' . $temp_dir;
            return array();
        }
        
        $zip_file = $temp_dir . '/' . $plugin_slug . '.zip';
        $extract_dir = $temp_dir . '/extracted';
        
        try {
            // Download the official plugin ZIP file
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Downloading official plugin: ' . $download_url;
            
            $download_response = wp_remote_get($download_url, array(
                'timeout' => 120,
                'user-agent' => 'VMPFence/' . (defined('VMPFENCE_VERSION') ? VMPFENCE_VERSION : '1.0') . '; ' . home_url()
            ));
            
            if (is_wp_error($download_response)) {
                throw new Exception('Failed to download plugin: ' . $download_response->get_error_message());
            }
            
            $zip_content = wp_remote_retrieve_body($download_response);
            if (empty($zip_content)) {
                throw new Exception('Downloaded plugin ZIP is empty');
            }
            
            // Save ZIP file
            if (!file_put_contents($zip_file, $zip_content)) {
                throw new Exception('Failed to save downloaded plugin ZIP');
            }
            
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Plugin downloaded: ' . number_format(strlen($zip_content)) . ' bytes';
            
            // Extract ZIP file using WordPress built-in functionality
            if (!wp_mkdir_p($extract_dir)) {
                throw new Exception('Failed to create extraction directory');
            }
            
            // Use WordPress built-in unzip functionality instead of ZipArchive
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
            
            $unzip_result = unzip_file($zip_file, $extract_dir);
            if (is_wp_error($unzip_result)) {
                throw new Exception('Failed to extract plugin ZIP: ' . $unzip_result->get_error_message());
            }
            
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Plugin extracted successfully using WordPress unzip';
            
            // Find the plugin directory in extracted files
            $extracted_plugin_dir = $this->find_plugin_directory($extract_dir, $plugin_slug);
            if (!$extracted_plugin_dir) {
                throw new Exception('Could not find plugin directory in extracted files');
            }
            
            // Generate checksums for all PHP files in official plugin
            $official_files = $this->get_plugin_files_recursive($extracted_plugin_dir);
            $local_plugin_dir = WP_PLUGIN_DIR . '/' . $plugin_slug;
            
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Comparing ' . count($official_files) . ' files from official plugin';
            
            foreach ($official_files as $relative_file) {
                $official_file_path = $extracted_plugin_dir . '/' . $relative_file;
                $local_file_path = $local_plugin_dir . '/' . $relative_file;
                
                if (file_exists($official_file_path)) {
                    // Generate checksum for official file
                    $official_hash = md5_file($official_file_path);
                    $checksums[$relative_file] = $official_hash;
                    
                    $this->debug_log[] = '[' . current_time('H:i:s') . '] Generated official checksum for: ' . $relative_file;
                }
            }
            
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Generated ' . count($checksums) . ' official checksums for plugin: ' . $plugin_slug;
            
        } catch (Exception $e) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Plugin verification error: ' . $e->getMessage();
            $checksums = array(); // Return empty array on error
        } finally {
            // Clean up temporary files
            $this->cleanup_temp_directory($temp_dir);
        }
        
        return $checksums;
    }
    
    /**
     * Find plugin directory in extracted files
     */
    private function find_plugin_directory($extract_dir, $plugin_slug) {
        $directories = glob($extract_dir . '/*', GLOB_ONLYDIR);
        
        foreach ($directories as $dir) {
            $dir_name = basename($dir);
            // Plugin directory might be exactly the slug or contain the slug
            if ($dir_name === $plugin_slug || strpos($dir_name, $plugin_slug) !== false) {
                return $dir;
            }
        }
        
        // If not found by name, look for directory with main plugin file
        foreach ($directories as $dir) {
            $main_file_candidates = array(
                $dir . '/' . $plugin_slug . '.php',
                $dir . '/index.php',
                $dir . '/plugin.php'
            );
            
            foreach ($main_file_candidates as $main_file) {
                if (file_exists($main_file)) {
                    // Check if this file has plugin headers
                    $file_content = file_get_contents($main_file, false, null, 0, 8192);
                    if (strpos($file_content, 'Plugin Name:') !== false) {
                        return $dir;
                    }
                }
            }
        }
        
        return null;
    }
    
    /**
     * Get all PHP files in plugin directory recursively
     */
    private function get_plugin_files_recursive($plugin_dir) {
        $files = array();
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($plugin_dir, RecursiveDirectoryIterator::SKIP_DOTS)
        );
        
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
                // Include PHP files and other important files
                if (in_array(strtolower($extension), array('php', 'js', 'css', 'txt', 'md'))) {
                    $relative_path = str_replace($plugin_dir . DIRECTORY_SEPARATOR, '', $file->getPathname());
                    $relative_path = str_replace(DIRECTORY_SEPARATOR, '/', $relative_path);
                    $files[] = $relative_path;
                }
            }
        }
        
        return $files;
    }
    
    /**
     * Clean up temporary directory
     */
    private function cleanup_temp_directory($temp_dir) {
        if (!is_dir($temp_dir)) {
            return;
        }
        
        try {
            // Use WordPress filesystem to remove directory recursively
            global $wp_filesystem;
            
            if (empty($wp_filesystem)) {
                require_once ABSPATH . '/wp-admin/includes/file.php';
                WP_Filesystem();
            }
            
            if ($wp_filesystem) {
                $wp_filesystem->rmdir($temp_dir, true);
                $this->debug_log[] = '[' . current_time('H:i:s') . '] Cleaned up temp directory: ' . $temp_dir;
            } else {
                // Fallback manual cleanup
                $this->rmdir_recursive($temp_dir);
            }
            
        } catch (Exception $e) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Temp cleanup error: ' . $e->getMessage();
        }
    }
    
    /**
     * Recursive directory removal fallback
     */
    private function rmdir_recursive($dir) {
        if (!is_dir($dir)) {
            return;
        }
        
        // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_scandir, WordPress.WP.AlternativeFunctions.unlink_unlink, WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- Fallback when WP_Filesystem unavailable
        $files = array_diff(scandir($dir), array('.', '..'));
        foreach ($files as $file) {
            $path = $dir . DIRECTORY_SEPARATOR . $file;
            if (is_dir($path)) {
                $this->rmdir_recursive($path);
            } else {
                unlink($path);
            }
        }
        rmdir($dir);
        // phpcs:enable WordPress.WP.AlternativeFunctions.file_system_operations_scandir, WordPress.WP.AlternativeFunctions.unlink_unlink, WordPress.WP.AlternativeFunctions.file_system_operations_rmdir
    }
    
    /**
     * Make API request with proper error handling
     */
    private function make_api_request($url) {
        $response = wp_remote_get($url, array(
            'timeout' => 30,
            'user-agent' => 'VMPFence/' . (defined('VMPFENCE_VERSION') ? VMPFENCE_VERSION : '1.0') . '; ' . home_url()
        ));
        
        if (is_wp_error($response)) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] API request error: ' . $response->get_error_message();
            return null;
        }
        
        if (wp_remote_retrieve_response_code($response) !== 200) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] API request failed with status: ' . wp_remote_retrieve_response_code($response);
            return null;
        }
        
        return wp_remote_retrieve_body($response);
    }
    
    /**
     * Get plugin data from headers
     */
    private function get_plugin_data($plugin_slug) {
        $plugin_path = WP_PLUGIN_DIR . '/' . $plugin_slug;
        
        if (!is_dir($plugin_path)) {
            return null;
        }
        
        // Find main plugin file
        $plugin_files = glob($plugin_path . '/*.php');
        foreach ($plugin_files as $file) {
            $plugin_data = get_file_data($file, array(
                'Name' => 'Plugin Name',
                'Version' => 'Version',
                'Description' => 'Description'
            ));
            
            if (!empty($plugin_data['Name'])) {
                return array(
                    'name' => $plugin_data['Name'],
                    'version' => $plugin_data['Version'],
                    'description' => $plugin_data['Description'],
                    'file' => basename($file)
                );
            }
        }
        
        return null;
    }
    
    /**
     * Verify theme files (bonus method)
     */
    public function verify_theme_files($theme_slug = null) {
        $issues = array();
        
        if (!$theme_slug) {
            $theme_slug = get_option('stylesheet');
        }
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Checking theme: ' . $theme_slug;
        
        // Check if theme exists in WordPress.org repository
        $url = $this->wp_api_base . '/themes/info/1.1/?action=theme_information&request[slug]=' . $theme_slug;
        
        $response = wp_remote_get($url, array(
            'timeout' => 30,
            'user-agent' => 'VMPFence/' . VMPFENCE_VERSION . '; ' . home_url()
        ));
        
        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Theme not found in repository or API error: ' . $theme_slug;
            return array();
        }
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Theme found in repository: ' . $theme_slug;
        
        // Get theme info from WordPress.org API
        $theme_info = json_decode($theme_response, true);
        if (!$theme_info || !isset($theme_info['download_link'])) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Cannot get theme download info: ' . $theme_slug;
            return $issues;
        }
        
        // ACTUAL PRODUCTION IMPLEMENTATION: Download and verify theme files
        $theme_checksums = $this->download_and_verify_theme($theme_slug, $theme_info);
        
        if (empty($theme_checksums)) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Could not verify theme files: ' . $theme_slug;
            return $issues;
        }
        
        // Verify each theme file against official checksums
        $theme_path = get_theme_root() . '/' . $theme_slug;
        
        foreach ($theme_checksums as $file_path => $expected_hash) {
            $full_path = $theme_path . '/' . $file_path;
            
            if (!file_exists($full_path)) {
                $issues[] = array(
                    'type' => 'missing_theme_file',
                    'severity' => 'medium',
                    'title' => 'Missing Theme File',
                    'description' => 'Theme file is missing from official distribution',
                    'location' => $theme_slug . '/' . $file_path,
                    'details' => 'Theme: ' . $theme_slug . ' | Missing file: ' . $file_path,
                    'recommendation' => 'Reinstall the theme from WordPress.org',
                    'expected_hash' => $expected_hash,
                    'actual_hash' => null,
                    'file_status' => 'missing'
                );
                continue;
            }
            
            $actual_hash = md5_file($full_path);
            $this->stats['theme_files_checked']++;
            
            if ($actual_hash !== $expected_hash) {
                $issues[] = array(
                    'type' => 'modified_theme_file',
                    'severity' => 'medium',
                    'title' => 'Modified Theme File',
                    'description' => 'Theme file has been modified from official version',
                    'location' => $theme_slug . '/' . $file_path,
                    'details' => 'Theme: ' . $theme_slug . ' | File: ' . $file_path,
                    'recommendation' => 'Review changes or reinstall theme if compromised',
                    'expected_hash' => $expected_hash,
                    'actual_hash' => $actual_hash,
                    'file_status' => 'modified',
                    'file_size' => filesize($full_path)
                );
                
                $this->stats['modified_files_found']++;
                $this->debug_log[] = '[' . current_time('H:i:s') . '] MODIFIED THEME FILE: ' . $theme_slug . '/' . $file_path;
            }
        }
        
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Theme integrity check completed: ' . $theme_slug . ' (' . count($issues) . ' issues)';
        return $issues;
    }
    
    /**
     * Download and verify theme against official distribution  
     */
    private function download_and_verify_theme($theme_slug, $theme_info) {
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Starting actual theme download and verification for: ' . $theme_slug;
        
        $download_url = $theme_info['download_link'];
        $checksums = array();
        
        // Create temporary directory for theme verification
        $temp_dir = wp_upload_dir()['basedir'] . '/vmpfence_theme_temp_' . time();
        if (!wp_mkdir_p($temp_dir)) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Failed to create temp directory: ' . $temp_dir;
            return array();
        }
        
        $zip_file = $temp_dir . '/' . $theme_slug . '.zip';
        $extract_dir = $temp_dir . '/extracted';
        
        try {
            // Download the official theme ZIP file
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Downloading official theme: ' . $download_url;
            
            $download_response = wp_remote_get($download_url, array(
                'timeout' => 120,
                'user-agent' => 'VMPFence/' . (defined('VMPFENCE_VERSION') ? VMPFENCE_VERSION : '1.0') . '; ' . home_url()
            ));
            
            if (is_wp_error($download_response)) {
                throw new Exception('Failed to download theme: ' . $download_response->get_error_message());
            }
            
            $zip_content = wp_remote_retrieve_body($download_response);
            if (empty($zip_content)) {
                throw new Exception('Downloaded theme ZIP is empty');
            }
            
            // Save and extract ZIP file
            if (!file_put_contents($zip_file, $zip_content)) {
                throw new Exception('Failed to save downloaded theme ZIP');
            }
            
            if (!wp_mkdir_p($extract_dir)) {
                throw new Exception('Failed to create extraction directory');
            }
            
            // Use WordPress built-in unzip functionality
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
            
            $unzip_result = unzip_file($zip_file, $extract_dir);
            if (is_wp_error($unzip_result)) {
                throw new Exception('Failed to extract theme ZIP: ' . $unzip_result->get_error_message());
            }
            
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Theme extracted successfully using WordPress unzip';
            
            // Find theme directory and generate checksums
            $theme_dir = $extract_dir . '/' . $theme_slug;
            if (!is_dir($theme_dir)) {
                // Try to find theme directory
                $directories = glob($extract_dir . '/*', GLOB_ONLYDIR);
                $theme_dir = $directories[0] ?? null;
            }
            
            if (!$theme_dir || !is_dir($theme_dir)) {
                throw new Exception('Could not find theme directory in extracted files');
            }
            
            $theme_files = $this->get_theme_files_recursive($theme_dir);
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Processing ' . count($theme_files) . ' theme files';
            
            foreach ($theme_files as $relative_file) {
                $file_path = $theme_dir . '/' . $relative_file;
                if (file_exists($file_path)) {
                    $checksums[$relative_file] = md5_file($file_path);
                }
            }
            
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Generated ' . count($checksums) . ' checksums for theme: ' . $theme_slug;
            
        } catch (Exception $e) {
            $this->debug_log[] = '[' . current_time('H:i:s') . '] Theme verification error: ' . $e->getMessage();
            $checksums = array();
        } finally {
            $this->cleanup_temp_directory($temp_dir);
        }
        
        return $checksums;
    }
    
    /**
     * Get all theme files recursively
     */
    private function get_theme_files_recursive($theme_dir) {
        $files = array();
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($theme_dir, RecursiveDirectoryIterator::SKIP_DOTS)
        );
        
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
                // Include theme-related files
                if (in_array(strtolower($extension), array('php', 'css', 'js', 'txt', 'md', 'json'))) {
                    $relative_path = str_replace($theme_dir . DIRECTORY_SEPARATOR, '', $file->getPathname());
                    $relative_path = str_replace(DIRECTORY_SEPARATOR, '/', $relative_path);
                    $files[] = $relative_path;
                }
            }
        }
        
        return $files;
    }
    
    /**
     * Get integrity check statistics
     */
    public function get_integrity_stats() {
        return $this->stats;
    }
    
    /**
     * Get debug log
     */
    public function get_debug_log() {
        return $this->debug_log;
    }
    
    /**
     * Clear checksum cache
     */
    public function clear_cache() {
        $this->checksum_cache = array();
        $this->stats['cache_hits'] = 0;
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Checksum cache cleared';
    }
    
    /**
     * Set cache TTL
     */
    public function set_cache_ttl($seconds) {
        $this->cache_ttl = $seconds;
        $this->debug_log[] = '[' . current_time('H:i:s') . '] Cache TTL set to: ' . $seconds . ' seconds';
    }
}
?>
