<?php
defined('ABSPATH') || exit;

/**
 * Add a file to the whitelist
 * 
 * @param string $file_path Path to the file to whitelist
 * @param string $reason Reason for whitelisting
 * @param string $added_by Who added the file to whitelist (user, ai, admin)
 * @return bool|WP_Error True on success, WP_Error on failure
 */
function wpsec_whitelist_file($file_path, $reason = '', $added_by = 'user') {
    if (empty($file_path)) {
        return new WP_Error('empty_path', 'File path cannot be empty');
    }
    
    // Normalize the file path
    $normalized_path = wpsec_normalize_scan_path($file_path);
    
    // Validate the file path
    if (!wpsec_validate_file_path($normalized_path)) {
        wpsec_log('Invalid or unsafe file path for whitelisting: ' . $normalized_path, 'error');
        return new WP_Error('invalid_path', 'Invalid or unsafe file path');
    }
    
    // Check if file exists
    if (!file_exists($normalized_path)) {
        wpsec_log('File not found for whitelisting: ' . $normalized_path, 'error');
        return new WP_Error('file_not_found', 'File not found');
    }
    
    // Get existing whitelist
    $whitelist = get_option('wpsec_file_whitelist', []);
    
    // Generate a hash of the file for integrity verification
    $file_hash = md5_file($normalized_path);
    if ($file_hash === false) {
        wpsec_log('Failed to generate hash for file: ' . $normalized_path, 'error');
        return new WP_Error('hash_failed', 'Failed to generate file hash');
    }
    
    // Get file information
    $file_info = wpsec_get_file_info($normalized_path);
    
    // Add to whitelist with metadata
    $whitelist[$normalized_path] = [
        'path' => $normalized_path,
        'original_path' => $file_path,
        'relative_path' => isset($file_info['relative_path']) ? $file_info['relative_path'] : '',
        'hash' => $file_hash,
        'size' => filesize($normalized_path),
        'added_on' => current_time('mysql'),
        'added_by' => $added_by,
        'reason' => $reason,
        'last_verified' => current_time('mysql')
    ];
    
    // Save updated whitelist
    update_option('wpsec_file_whitelist', $whitelist);
    
    wpsec_log('File added to whitelist: ' . $normalized_path, 'info');
    return true;
}

/**
 * Remove a file from the whitelist
 * 
 * @param string $file_path Path to the file to remove from whitelist
 * @return bool True on success, false if file wasn't in whitelist
 */
function wpsec_remove_from_whitelist($file_path) {
    if (empty($file_path)) {
        return false;
    }
    
    // Normalize the file path
    $normalized_path = wpsec_normalize_scan_path($file_path);
    
    // Get existing whitelist
    $whitelist = get_option('wpsec_file_whitelist', []);
    
    // Check if file is in whitelist
    if (!isset($whitelist[$normalized_path])) {
        return false;
    }
    
    // Remove from whitelist
    unset($whitelist[$normalized_path]);
    
    // Save updated whitelist
    update_option('wpsec_file_whitelist', $whitelist);
    
    wpsec_log('File removed from whitelist: ' . $normalized_path, 'info');
    return true;
}

/**
 * Main function to check if a file is whitelisted
 *
 * @param string $file_path Path to the file
 * @param bool $verify_integrity Verify file integrity if on user whitelist
 * @param string $content Optional file content for content-based whitelist checks
 * @return bool True if file is whitelisted
 */
function wpsec_is_file_whitelisted($file_path, $verify_integrity = true, $content = null) {
    // Check deep scan flag first - if enabled, bypass whitelist completely
    global $wpsec_force_deep_scan, $wpsec_verbose_logging;
    if (!empty($wpsec_force_deep_scan)) {
        if (!empty($wpsec_verbose_logging)) {
            wpsec_debug_log("🔥 WPFort: Deep scan enabled - bypassing whitelist check for: " . basename($file_path), 'info');
        }
        // Return false to indicate file is NOT whitelisted, forcing it to be scanned
        return false;
    }
    
    // Normalize the file path
    $normalized_path = wpsec_normalize_scan_path($file_path);
    
    // Check if file exists (if not, can't be whitelisted)
    if (!file_exists($normalized_path)) {
        return false;
    }
    
    // Debugging to track usage
    $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
    $caller = isset($backtrace[1]['function']) ? $backtrace[1]['function'] : 'unknown';
    $caller_file = isset($backtrace[1]['file']) ? basename($backtrace[1]['file']) : 'unknown';
    
    wpsec_debug_log("🔍 WHITELIST CHECK: Validating file $normalized_path (called from {$caller_file}::{$caller})", 'info');
    
    // Check for suspicious file size (0 byte files are often indicators of compromise)
    if (filesize($normalized_path) === 0) {
        wpsec_debug_log("⚠️ SECURITY NOTICE: Zero-byte file detected, not whitelisting: $normalized_path", 'warning');
        return false;
    }
    
    // CRITICAL: Only whitelist our own plugin files to prevent self-flagging
    // Use multiple methods to ensure proper plugin directory detection
    $plugin_dirs = [];
    
    // Method 1: Use WPSEC_PLUGIN_DIR constant if available
    if (defined('WPSEC_PLUGIN_DIR')) {
        $plugin_dirs[] = rtrim(WPSEC_PLUGIN_DIR, '/');
    }
    
    // Method 2: Calculate from current file location
    $plugin_dirs[] = WP_CONTENT_DIR . '/plugins/' . basename(dirname(dirname(__FILE__)));
    
    // Method 3: Try common plugin folder names
    $plugin_dirs[] = WP_CONTENT_DIR . '/plugins/wpfortai-security';
    $plugin_dirs[] = WP_CONTENT_DIR . '/plugins/wpfortai-security';
    
    // Method 4: Pattern-based matching for different server configurations
    $plugin_path_patterns = [
        '/wp-content/plugins/wpfortai-security/',
        '/wp-content/plugins/wpfortai-security/',
        '/plugins/wpfortai-security/',
        '/plugins/wpfortai-security/'
    ];
    
    // Debug logging
    wpsec_debug_log("🔍 WHITELIST DEBUG: Checking file: $normalized_path", 'debug');
    wpsec_debug_log("🔍 WHITELIST DEBUG: Plugin directories: " . implode(', ', $plugin_dirs), 'debug');
    
    // Check against all possible plugin directories
    foreach ($plugin_dirs as $plugin_dir) {
        if (strpos($normalized_path, $plugin_dir) === 0) {
            wpsec_debug_log("✅ WHITELIST ACCEPT: Our own plugin file $normalized_path (matched: $plugin_dir)", 'info');
            return true;
        }
    }
    
    // Check pattern-based matching as fallback
    foreach ($plugin_path_patterns as $pattern) {
        if (strpos($normalized_path, $pattern) !== false) {
            wpsec_debug_log("✅ WHITELIST ACCEPT: Our own plugin file $normalized_path (pattern matched: $pattern)", 'info');
            return true;
        }
    }
    
    // HASH-BASED WHITELIST: Check user-managed whitelist with hash verification
    $whitelist = get_option('wpsec_file_whitelist', []);
    if (isset($whitelist[$normalized_path])) {
        // If integrity check is not required, return true immediately
        if (!$verify_integrity) {
            wpsec_debug_log("✅ WHITELIST ACCEPT: User-managed whitelist $normalized_path", 'info');
            return true;
        }
        
        // Verify file integrity by checking hash
        $current_hash = md5_file($normalized_path);
        if ($current_hash === false) {
            wpsec_debug_log("❌ WHITELIST REJECT: Failed to generate hash for whitelisted file: $normalized_path", 'error');
            wpsec_log("Failed to generate hash for whitelisted file: $normalized_path", 'warning');
            return false;
        }
        
        // If hash matches, file is whitelisted
        if ($current_hash === $whitelist[$normalized_path]['hash']) {
            wpsec_debug_log("✅ WHITELIST ACCEPT: User-managed whitelist with integrity verified $normalized_path", 'info');
            wpsec_log("File is whitelisted and integrity verified: $normalized_path", 'debug');
            return true;
        } else {
            wpsec_debug_log("❌ WHITELIST REJECT: File is whitelisted but integrity check failed: $normalized_path", 'error');
            wpsec_log("File is whitelisted but integrity check failed: $normalized_path", 'warning');
            return false;
        }
    }
    
    // HASH-BASED CACHE CHECK: Use proper caching mechanism instead of path-based exclusions
    // This will check if file was previously scanned and found safe, with hash verification
    if (function_exists('wpsec_is_file_cached_as_safe')) {
        if (wpsec_is_file_cached_as_safe($normalized_path)) {
            wpsec_debug_log("✅ WHITELIST ACCEPT: File cached as safe with verified hash: $normalized_path", 'info');
            return true;
        }
    }
    
    wpsec_debug_log("❌ WHITELIST REJECT: No whitelist rule matched for $normalized_path", 'error');
    // Not whitelisted - file should be scanned
    return false;
}

/**
 * DEPRECATED: This function has been removed as it was causing path-based exclusions
 * that prevented proper scanning of potentially infected files.
 * 
 * Hash-based caching via wpsec_is_file_cached_as_safe() should be used instead.
 * 
 * @deprecated Use hash-based caching instead of path-based exclusions
 * @param string $file_path Path to the file
 * @return bool Always returns false to ensure all files are scanned unless cached as safe
 */
function wpsec_file_meets_safety_criteria($file_path) {
    // SECURITY FIX: This function previously excluded files based on path patterns,
    // which allowed infected files in "safe" directories to bypass scanning.
    // Now we rely only on hash-based caching for performance optimization.
    
    wpsec_debug_log("⚠️ DEPRECATED: wpsec_file_meets_safety_criteria called for $file_path - use hash-based caching instead", 'warning');
    
    // Always return false to ensure file gets scanned unless it's cached as safe
    return false;
}

/**
 * Check if a file is whitelisted based on advanced definitions
 *
 * @param string $file_path Path to the file
 * @param string $content File content (optional, will be read if not provided)
 * @return bool True if the file is whitelisted by advanced definitions
 */
function wpsec_check_advanced_definitions_whitelist($file_path, $content = null) {
    // Log whitelist check for debugging
    $file_basename = basename($file_path);
    
    // With deep scan, we should BYPASS whitelist checks
    global $wpsec_current_scan_id, $wpsec_force_deep_scan, $wpsec_verbose_logging;
    if (!empty($wpsec_current_scan_id) && !empty($wpsec_force_deep_scan)) {
        if (!empty($wpsec_verbose_logging)) {
            wpsec_debug_log("🔥 WPFort: Deep scan - BYPASSING advanced definitions whitelist for {$file_basename}", 'info');
        }
        // Return false to indicate file is NOT whitelisted, forcing it to be scanned
        return false;
    }
    
    wpsec_debug_log("🔍 WPFort: Checking advanced whitelist for file: {$file_basename}", 'info');
    
    // Try to load advanced definitions if available
    if (!function_exists('wpsec_load_advanced_definitions')) {
        if (file_exists(dirname(__FILE__) . '/advanced.php')) {
            wpsec_debug_log("📂 WPFort: Loading advanced.php for whitelist check", 'info');
            require_once dirname(__FILE__) . '/advanced.php';
        } else {
            wpsec_debug_log("❌ WPFort: Advanced.php not found, cannot check whitelist", 'error');
            return false;
        }
    }
    
    $advanced_definitions = wpsec_load_advanced_definitions();
    
    if (!$advanced_definitions || !isset($advanced_definitions['whitelist'])) {
        wpsec_debug_log("❌ WHITELIST: No valid whitelist definitions available", 'error');
        return false;
    }
    
    $whitelist = $advanced_definitions['whitelist'];
    
    // If content wasn't provided, read it
    if ($content === null && file_exists($file_path)) {
        $content = file_get_contents($file_path);
    }
    
    if (empty($content)) {
        return false;
    }
    
    // Special handling for potentially flagged files with eval() usage
    // This adds a powerful content analysis layer for more robust global detection
    if (strpos($content, 'eval(') !== false) {
        // Get file extension
        $ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
        
        // Only apply to PHP files
        if ($ext === 'php' || $ext === 'inc' || $ext === 'phtml') {
            // SAFE EVAL PATTERN ANALYSIS - Content-based approach for legitimate eval() usage
            
            // 1. CRYPTO LIBRARIES - Identify known cryptographic implementations
            $crypto_patterns = [
                // PhpSecLib and other crypto libraries
                'function crypt_random_string',
                'class Crypt_',
                'class Math_',
                'class File_',
                'symmetric key',
                'public function decrypt',
                'Barrett modular reduction',
            ];
            
            // 2. CACHING/REDIS PATTERNS - Identify Redis and caching implementations
            $caching_patterns = [
                'redis command',
                'function eval($script',
                'function evalSha',
                'class RedisCluster',
                'class Redis',
                'function executeEval',
            ];
            
            // 3. TEMPLATE ENGINES - Identify template engines like Twig
            $template_patterns = [
                'class Twig_',
                'class Twig\\',
                'public function render',
                'function compileTemplate',
                'function parseTemplate',
                'template engine',
            ];
            
            // 4. CODE EXECUTION PLUGINS - Legitimate code snippet execution
            $execution_patterns = [
                'class SnippetExecution',
                'function executeSnippet',
                'admin-ajax.php',
                'class WPCode',
                'integration class',
            ];
            
            // Check all pattern sets
            $all_patterns = array_merge($crypto_patterns, $caching_patterns, $template_patterns, $execution_patterns);
            
            foreach ($all_patterns as $pattern) {
                if (stripos($content, $pattern) !== false) {
                    // Found legitimate pattern that explains eval() usage
                    wpsec_debug_log("✅ WPFort: Advanced Content Analysis - Legitimate eval() usage detected in: {$file_basename}", 'info');
                    return true;
                }
            }
            
            // SECURE EVAL PATTERN - If the eval is used in a controlled, secure manner
            if (preg_match('/function\s+eval\s*\(/', $content) || // Function declaration named eval
                preg_match('/\$[a-z0-9_]+\s*=\s*eval\s*;/', $content)) { // Variable assignment
                wpsec_debug_log("✅ WPFort: Advanced Content Analysis - Non-executable eval reference: {$file_basename}", 'info');
                return true;
            }
            
            // OBFUSCATION CHECK - Is eval used with obfuscation techniques?
            $has_obfuscation = (
                preg_match('/eval\s*\(\s*base64_decode\s*\(/', $content) || 
                preg_match('/eval\s*\(\s*str_rot13\s*\(/', $content) ||
                preg_match('/eval\s*\(\s*gzinflate\s*\(/', $content) ||
                preg_match('/eval\s*\([^\)]{200,}\)/', $content) // Very long eval parameter
            );
            
            if ($has_obfuscation) {
                wpsec_debug_log("⚠️ WPFort: Advanced Content Analysis - Suspicious obfuscated eval() usage detected: {$file_basename}", 'warning');
                return false; // This is likely malicious
            }
        }
    }
    
    // Continue with traditional hash-based whitelist
    // Content hash and file size - the format used in advanced definitions
    $content_hash = md5($content);
    $content_length = strlen($content);
    $hash_with_size = $content_hash . 'O' . $content_length; // This is the key format in definitions
    
    // Get file extension
    $ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
    
    // Log the hash lookup we're performing
    wpsec_debug_log("🔎 WHITELIST: Checking hash whitelist for {$file_basename} (key: {$hash_with_size})", 'info');
    
    // Check PHP whitelist using the proper hash format from definitions
    if (($ext === 'php' || $ext === 'inc' || $ext === 'phtml') && isset($whitelist['php'])) {
        // Direct lookup using the hash+size key format
        if (isset($whitelist['php'][$hash_with_size])) {
            $whitelist_code = $whitelist['php'][$hash_with_size];
            wpsec_debug_log("✅ WHITELIST: File {$file_basename} found in PHP hash whitelist (code: {$whitelist_code})", 'info');
            return true;
        }
        wpsec_debug_log("❓ WHITELIST: File {$file_basename} NOT found in PHP whitelist", 'info');
    }
    
    // Check JS whitelist using the proper hash format from definitions
    if ($ext === 'js' && isset($whitelist['js'])) {
        // Direct lookup using the hash+size key format
        if (isset($whitelist['js'][$hash_with_size])) {
            $whitelist_code = $whitelist['js'][$hash_with_size];
            wpsec_debug_log("✅ WHITELIST: File {$file_basename} found in JS hash whitelist (code: {$whitelist_code})", 'info');
            return true;
        }
        wpsec_debug_log("❓ WHITELIST: File {$file_basename} NOT found in JS whitelist", 'info');
    }
    
    // Check other common file types that might be in the whitelist
    $common_types = ['css', 'html', 'svg', 'txt', 'json'];
    
    // Special handling for .htm -> html mapping
    $type = ($ext == 'htm') ? 'html' : $ext;
    
    // If this type exists in the whitelist
    if (in_array($type, $common_types) && isset($whitelist[$type])) {
        // Direct lookup using the hash+size key format
        if (isset($whitelist[$type][$hash_with_size])) {
            $whitelist_code = $whitelist[$type][$hash_with_size];
            wpsec_debug_log("✅ WHITELIST: File {$file_basename} found in {$type} hash whitelist (code: {$whitelist_code})", 'info');
            return true;
        }
    }
    
    wpsec_debug_log("❌ WHITELIST: File {$file_basename} not found in any whitelist definitions", 'error');
    return false;
}

/**
 * Get context information about a file based on its path
 *
 * @param string $file_path Path to the file
 * @return array Context information about the file
 */
function wpsec_get_file_context($file_path) {
    // Context information about the file
    $context = [
        'type' => 'unknown',
        'is_core' => false,
        'is_plugin' => false,
        'is_theme' => false,
        'is_upload' => false,
        'risk_level' => 'medium'
    ];
    
    // Core WordPress files
    if (strpos($file_path, '/wp-includes/') !== false || strpos($file_path, '/wp-admin/') !== false) {
        $context['type'] = 'core';
        $context['is_core'] = true;
        $context['risk_level'] = 'low';
        
        // Extra validation for core files
        if (wpsec_is_valid_core_file($file_path)) {
            $context['risk_level'] = 'very_low';
        }
    }
    // Plugin files
    else if (strpos($file_path, '/wp-content/plugins/') !== false) {
        $context['type'] = 'plugin';
        $context['is_plugin'] = true;
    }
    // Theme files
    else if (strpos($file_path, '/wp-content/themes/') !== false) {
        $context['type'] = 'theme';
        $context['is_theme'] = true;
    }
    // Upload files
    else if (strpos($file_path, '/wp-content/uploads/') !== false) {
        $context['type'] = 'upload';
        $context['is_upload'] = true;
        $context['risk_level'] = 'high'; // Uploads should be scrutinized more closely
    }
    
    return $context;
}

/**
 * Check if file is a valid core file
 *
 * @param string $file_path Path to the file
 * @return bool True if the file is a valid core file
 */
function wpsec_is_valid_core_file($file_path) {
    // Check for common safe core files
    $safe_files = [
        'wp-login.php',
        'index.php',
        'wp-blog-header.php',
        'wp-comments-post.php',
        'wp-config-sample.php',
        'wp-cron.php',
        'wp-links-opml.php',
        'wp-load.php',
        'wp-mail.php',
        'wp-settings.php',
        'wp-signup.php',
        'wp-trackback.php',
        'xmlrpc.php'
    ];
    
    $filename = basename($file_path);
    return in_array($filename, $safe_files);
}

/**
 * Get the list of whitelisted files
 * 
 * @param bool $include_details Whether to include detailed information
 * @return array List of whitelisted files
 */
function wpsec_get_whitelisted_files($include_details = true) {
    $whitelist = get_option('wpsec_file_whitelist', []);
    
    if (!$include_details) {
        // Return just the file paths
        return array_keys($whitelist);
    }
    
    return $whitelist;
}

/**
 * Verify the integrity of all whitelisted files
 * 
 * @return array Results of verification
 */
function wpsec_verify_whitelist_integrity() {
    $whitelist = get_option('wpsec_file_whitelist', []);
    $results = [
        'total' => count($whitelist),
        'verified' => 0,
        'changed' => 0,
        'missing' => 0,
        'changed_files' => [],
        'missing_files' => []
    ];
    
    foreach ($whitelist as $path => $info) {
        if (!file_exists($path)) {
            $results['missing']++;
            $results['missing_files'][] = $path;
            continue;
        }
        
        $current_hash = md5_file($path);
        if ($current_hash === false || $current_hash !== $info['hash']) {
            $results['changed']++;
            $results['changed_files'][] = $path;
            continue;
        }
        
        $results['verified']++;
        
        // Update last verified timestamp
        $whitelist[$path]['last_verified'] = current_time('mysql');
    }
    
    // Save updated whitelist
    update_option('wpsec_file_whitelist', $whitelist);
    
    return $results;
}

/**
 * Clean up the whitelist by removing entries for files that no longer exist
 * 
 * @return int Number of entries removed
 */
function wpsec_cleanup_whitelist() {
    $whitelist_file = wpsec_get_whitelist_file();
    $whitelist = json_decode(file_get_contents($whitelist_file), true);
    
    if (!$whitelist || !isset($whitelist['files'])) {
        return 0;
    }
    
    $original_count = count($whitelist['files']);
    $removed = 0;
    
    foreach ($whitelist['files'] as $file_path => $file_data) {
        if (!file_exists($file_path)) {
            unset($whitelist['files'][$file_path]);
            $removed++;
        }
    }
    
    if ($removed > 0) {
        wpsec_debug_log("🧹 WPFort: Cleaned up whitelist, removed {$removed} non-existent files", 'info');
        file_put_contents($whitelist_file, json_encode($whitelist, JSON_PRETTY_PRINT));
    }
    
    return $removed;
}

/**
 * Import whitelist definitions from other security plugins like GOTLMS
 *
 * @param string $plugin_name The plugin to import from ('gotlms', 'sucuri', etc.)
 * @param bool $overwrite Whether to overwrite existing definitions
 * @return array Results of the import operation
 */
function wpsec_import_external_whitelist($plugin_name = 'gotlms', $overwrite = false) {
    $result = [
        'success' => false,
        'imported' => 0,
        'skipped' => 0,
        'message' => '',
        'errors' => []
    ];
    
    // Load our advanced definitions
    if (!function_exists('wpsec_load_advanced_definitions')) {
        require_once dirname(__FILE__) . '/advanced.php';
    }
    
    $advanced_definitions = wpsec_load_advanced_definitions();
    if (!$advanced_definitions || !isset($advanced_definitions['whitelist'])) {
        $result['message'] = 'Could not load existing definitions';
        return $result;
    }
    
    // Import from GOTLMS plugin
    if ($plugin_name === 'gotlms') {
        // Find the GOTLMS definitions file
        $gotlms_paths = [
            WP_CONTENT_DIR . '/plugins/gotlms/includes/definitions.php',
            WP_CONTENT_DIR . '/plugins/gotmls/definitions.php',
            WP_CONTENT_DIR . '/plugins/gotmls/safe-load/definitions.php'
        ];
        
        $gotlms_file = null;
        foreach ($gotlms_paths as $path) {
            if (file_exists($path)) {
                $gotlms_file = $path;
                break;
            }
        }
        
        if (!$gotlms_file) {
            $result['message'] = 'GOTLMS definitions file not found';
            return $result;
        }
        
        // Read the GOTLMS definitions file
        $gotlms_content = file_get_contents($gotlms_file);
        if (!$gotlms_content) {
            $result['message'] = 'Could not read GOTLMS definitions file';
            return $result;
        }
        
        // Try to extract the PHP and JS whitelist arrays
        // This uses regex since we can't directly include their file
        if (preg_match('/[\'"]whitelist[\'"]\s*=>\s*array\((.*?)\)/s', $gotlms_content, $matches)) {
            $whitelist_content = $matches[1];
            
            // Parse the PHP whitelist portion
            if (preg_match('/[\'"]php[\'"]\s*=>\s*array\((.*?)\),/s', $whitelist_content, $php_matches)) {
                $php_whitelist = $php_matches[1];
                preg_match_all('/[\'"](.*?)[\'"](\s*)=>(\s*)[\'"](.*?)[\'"],?/s', $php_whitelist, $php_entries, PREG_SET_ORDER);
                
                foreach ($php_entries as $entry) {
                    $hash_key = trim($entry[1]);
                    $whitelist_code = trim($entry[4]);
                    
                    // Skip the '0' placeholder entry
                    if ($hash_key === '0') continue;
                    
                    // Skip if we already have this and not overwriting
                    if (!$overwrite && isset($advanced_definitions['whitelist']['php'][$hash_key])) {
                        $result['skipped']++;
                        continue;
                    }
                    
                    $advanced_definitions['whitelist']['php'][$hash_key] = $whitelist_code;
                    $result['imported']++;
                }
            }
            
            // Parse the JS whitelist portion
            if (preg_match('/[\'"]js[\'"]\s*=>\s*array\((.*?)\),?/s', $whitelist_content, $js_matches)) {
                $js_whitelist = $js_matches[1];
                preg_match_all('/[\'"](.*?)[\'"](\s*)=>(\s*)[\'"](.*?)[\'"],?/s', $js_whitelist, $js_entries, PREG_SET_ORDER);
                
                foreach ($js_entries as $entry) {
                    $hash_key = trim($entry[1]);
                    $whitelist_code = trim($entry[4]);
                    
                    // Skip the '0' placeholder entry
                    if ($hash_key === '0') continue;
                    
                    // Skip if we already have this and not overwriting
                    if (!$overwrite && isset($advanced_definitions['whitelist']['js'][$hash_key])) {
                        $result['skipped']++;
                        continue;
                    }
                    
                    $advanced_definitions['whitelist']['js'][$hash_key] = $whitelist_code;
                    $result['imported']++;
                }
            }
            
            // If we imported anything, save the updated definitions
            if ($result['imported'] > 0) {
                // Create a backup of the current definitions
                $backup_path = dirname(__FILE__) . '/advanced-definitions.backup-' . gmdate('YmdHis') . '.json';
                file_put_contents($backup_path, json_encode($advanced_definitions, JSON_PRETTY_PRINT));
                
                // Update the definitions
                $update_path = dirname(__FILE__) . '/advanced-definitions.json';
                file_put_contents($update_path, json_encode($advanced_definitions, JSON_PRETTY_PRINT));
                
                $result['success'] = true;
                $result['message'] = "Successfully imported {$result['imported']} whitelist entries from GOTLMS";
                if ($result['skipped'] > 0) {
                    $result['message'] .= " (skipped {$result['skipped']} existing entries)";
                }
            } else {
                $result['message'] = 'No entries were imported';
            }
        } else {
            $result['message'] = 'Could not parse GOTLMS whitelist format';
        }
    } else {
        $result['message'] = "Import from {$plugin_name} is not supported yet";
    }
    
    return $result;
}
