<?php
/**
 * VMPFence Diagnostic Model
 *
 * Handles all diagnostic tests for the plugin
 *
 * @package VMPFence
 * @subpackage Tools/Models
 * @since 2.2.0
 * @since 2.2.1 Updated text-domain to vmpfence-security
 * @since 2.2.2 Updated to reflect VMP Security branding
 */

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

// Load cURL interceptor
require_once VMPFENCE_PLUGIN_DIR . 'lib/class-curl-interceptor.php';

/**
 * Diagnostic Test Engine
 *
 * @since 2.2.0
 */
class VMPFence_Tools_Diagnostic {

    /**
     * Run comprehensive diagnostics
     *
     * @since 2.2.0
     * @param array $tests_to_run Specific tests to run (optional)
     * @return array Diagnostic results
     */
    public static function run_diagnostics($tests_to_run = array()) {
        
        $all_tests = array(
            'vmpfence_status',
            'filesystem',
            'config',
            'firewall',
            'database',
            'php_environment',
            'connectivity',
            'time',
            'ip_detection',
            'wordpress_settings',
            'wordpress_plugins',
            'mu_plugins',
            'dropin_plugins',
            'themes',
            'cron_jobs',
            'database_tables',
            'log_files'
        );

        if (empty($tests_to_run)) {
            $tests_to_run = $all_tests;
        }

        $results = array(
            'overall_status' => 'healthy',
            'timestamp' => current_time('timestamp'),
            'tests' => array(),
            'summary' => array(
                'total_tests' => count($tests_to_run),
                'passed' => 0,
                'warnings' => 0,
                'failed' => 0
            ),
            'recommendations' => array()
        );

        foreach ($tests_to_run as $test) {
            $method = 'test_' . $test;
            if (method_exists(__CLASS__, $method)) {
                $test_result = self::$method();
                $results['tests'][$test] = $test_result;

                // Update summary
                switch ($test_result['status']) {
                    case 'passed':
                        $results['summary']['passed']++;
                        break;
                    case 'warning':
                        $results['summary']['warnings']++;
                        if ($results['overall_status'] === 'healthy') {
                            $results['overall_status'] = 'warning';
                        }
                        break;
                    case 'failed':
                        $results['summary']['failed']++;
                        $results['overall_status'] = 'critical';
                        break;
                }

                // Add recommendations
                if (!empty($test_result['recommendations'])) {
                    $results['recommendations'] = array_merge(
                        $results['recommendations'],
                        $test_result['recommendations']
                    );
                }
            }
        }
        
        return $results;
    }

    /**
     * Test VMPFence Status
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_vmpfence_status() {        
        $test = array(
            'name' => __('VMP Security Status', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // Check version
        $version = defined('VMPFENCE_VERSION') ? VMPFENCE_VERSION : '2.0.0';
        $test['details'][] = array(
            'label' => __('VMPFence Version', 'vmpfence-security'),
            'value' => $version,
            'status' => 'passed'
        );

        // Check GeoIP version
        $geoip_version = get_option('vmpfence_geoip_db_version', 'Not installed');
        $test['details'][] = array(
            'label' => __('GeoIP Version', 'vmpfence-security'),
            'value' => $geoip_version,
            'status' => 'passed'
        );

        // Check cron status
        $cron = _get_cron_array();
        $overdue = 0;
        foreach ($cron as $timestamp => $values) {
            if (is_array($values)) {
                foreach ($values as $cron_job => $v) {
                    if (is_numeric($timestamp) && (time() - 1800) > $timestamp) {
                        $overdue++;
                    }
                }
            }
        }

        $test['details'][] = array(
            'label' => __('Cron Status', 'vmpfence-security'),
            'value' => $overdue ? sprintf(_n('%d Job Overdue', '%d Jobs Overdue', $overdue, 'vmpfence-security'), $overdue) : __('Normal', 'vmpfence-security'),
            'status' => $overdue > 0 ? 'warning' : 'passed'
        );

        if ($overdue > 0) {
            $test['status'] = 'warning';
            $test['recommendations'][] = __('Check WordPress cron configuration', 'vmpfence-security');
        }

        return $test;
    }

    /**
     * Test Filesystem Permissions
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_filesystem() {
        
        $test = array(
            'name' => __('Filesystem', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        $plugin_dir = VMPFENCE_PLUGIN_DIR;
        
        // Check plugin directory readable
        $readable = is_readable($plugin_dir);
        $test['details'][] = array(
            'label' => __('Checking if web server can read from ~/plugins/vmpfence', 'vmpfence-security'),
            'value' => $readable ? __('OK', 'vmpfence-security') : __('FAILED', 'vmpfence-security'),
            'status' => $readable ? 'passed' : 'failed'
        );

        if (!$readable) {
            $test['status'] = 'failed';
            $test['recommendations'][] = __('Make plugin directory readable', 'vmpfence-security');
        }

        // Check plugin directory writable
        $writable = is_writable($plugin_dir);
        $test['details'][] = array(
            'label' => __('Checking if web server can write to ~/plugins/vmpfence', 'vmpfence-security'),
            'value' => $writable ? __('OK', 'vmpfence-security') : __('FAILED', 'vmpfence-security'),
            'status' => $writable ? 'passed' : 'warning'
        );

        if (!$writable && $test['status'] !== 'failed') {
            $test['status'] = 'warning';
            $test['recommendations'][] = __('Make plugin directory writable for updates', 'vmpfence-security');
        }

        // Check VMPFence data directory
        $upload_dir = wp_upload_dir();
        $vmpfence_dir = $upload_dir['basedir'] . '/vmpfence';
        
        // Create directory if it doesn't exist
        if (!file_exists($vmpfence_dir)) {
            wp_mkdir_p($vmpfence_dir);
        }
        
        $vmpfence_readable = is_readable($vmpfence_dir);
        $test['details'][] = array(
            'label' => __('Checking if web server can read from ~/wp-content/uploads/vmpfence', 'vmpfence-security'),
            'value' => $vmpfence_readable ? __('OK', 'vmpfence-security') : __('FAILED', 'vmpfence-security'),
            'status' => $vmpfence_readable ? 'passed' : 'failed'
        );

        // Check VMPFence data directory writable
        $vmpfence_writable = is_writable($vmpfence_dir);
        $test['details'][] = array(
            'label' => __('Checking if web server can write to ~/wp-content/uploads/vmpfence', 'vmpfence-security'),
            'value' => $vmpfence_writable ? __('OK', 'vmpfence-security') : __('FAILED', 'vmpfence-security'),
            'status' => $vmpfence_writable ? 'passed' : 'failed'
        );

        return $test;
    }

    /**
     * Test Config Read/Write
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_config() {
        
        $test = array(
            'name' => __('VMP Security Config', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // Test basic config write
        $test_key = 'vmpfence_diagnostic_test_' . time();
        $test_value = md5(time());
        
        update_option($test_key, $test_value, false);
        $retrieved = get_option($test_key);
        $basic_test = ($retrieved === $test_value);
        delete_option($test_key);

        $test['details'][] = array(
            'label' => __('Checking basic config reading/writing', 'vmpfence-security'),
            'value' => $basic_test ? __('Basic config writing', 'vmpfence-security') : __('Failed', 'vmpfence-security'),
            'status' => $basic_test ? 'passed' : 'failed'
        );

        if (!$basic_test) {
            $test['status'] = 'failed';
            $test['recommendations'][] = __('Check database permissions', 'vmpfence-security');
        }

        // Test serialized config write
        $test_key_serialized = 'vmpfence_diagnostic_test_serialized_' . time();
        $test_value_serialized = array(
            'test' => 'value',
            'number' => 12345,
            'nested' => array('key' => 'data')
        );
        
        update_option($test_key_serialized, $test_value_serialized, false);
        $retrieved_serialized = get_option($test_key_serialized);
        $serialized_test = ($retrieved_serialized === $test_value_serialized);
        delete_option($test_key_serialized);

        $test['details'][] = array(
            'label' => __('Checking serialized config reading/writing', 'vmpfence-security'),
            'value' => $serialized_test ? __('Serialized config writing', 'vmpfence-security') : __('Failed', 'vmpfence-security'),
            'status' => $serialized_test ? 'passed' : 'failed'
        );

        if (!$serialized_test && $test['status'] !== 'failed') {
            $test['status'] = 'failed';
            $test['recommendations'][] = __('Check database serialization support', 'vmpfence-security');
        }

        return $test;
    }

    /**
     * Test Firewall Status
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_firewall() {
        global $wpdb;
        
        $test = array(
            'name' => __('VMP Security Firewall', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // Configured WAF storage engine
        $configured_engine = defined('VMPFENCE_WAF_STORAGE_ENGINE') ? VMPFENCE_WAF_STORAGE_ENGINE : __('(default)', 'vmpfence-security');
        $test['details'][] = array(
            'label' => __('Configured WAF storage engine (VMPFENCE_WAF_STORAGE_ENGINE)', 'vmpfence-security'),
            'value' => $configured_engine,
            'status' => 'passed'
        );

        // Active WAF storage engine - determine what's actually being used
        $active_engine = __('MySQL database', 'vmpfence-security'); // Default to MySQL since we use database storage
        
        // Check if file-based storage exists (fallback scenario)
        $upload_dir = wp_upload_dir();
        $config_file = $upload_dir['basedir'] . '/vmpfence/config.php';
        if (file_exists($config_file) && !defined('VMPFENCE_WAF_STORAGE_ENGINE')) {
            $active_engine = __('File system (fallback)', 'vmpfence-security');
        }
        
        $test['details'][] = array(
            'label' => __('Active WAF storage engine', 'vmpfence-security'),
            'value' => $active_engine,
            'status' => 'passed'
        );

        // WAF log path
        $upload_dir = wp_upload_dir();
        $waf_log_path = $upload_dir['basedir'] . '/vmpfence/logs/';
        $test['details'][] = array(
            'label' => __('WAF log path', 'vmpfence-security'),
            'value' => str_replace(ABSPATH, '~/', $waf_log_path),
            'status' => 'passed'
        );

        // WAF subdirectory installation (check if WordPress is in subdirectory but accessible from root)
        $home_url = home_url();
        $site_url = site_url();
        $is_subdirectory = $home_url !== $site_url;
        $test['details'][] = array(
            'label' => __('WAF installed in subdirectory', 'vmpfence-security'),
            'value' => $is_subdirectory ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed'
        );

        // WAF File Permissions
        $permissions_msg = __('0660 - using default', 'vmpfence-security');
        
        // Check if constant is defined
        if (defined('VMPFENCE_WAF_LOG_FILE_MODE')) {
            $permissions_msg = sprintf(__('%s - using constant', 'vmpfence-security'), str_pad(decoct(VMPFENCE_WAF_LOG_FILE_MODE), 4, '0', STR_PAD_LEFT));
        } else {
            // Check template file permissions
            $upload_dir = wp_upload_dir();
            $template_file = $upload_dir['basedir'] . '/vmpfence/template.php';
            
            if (file_exists($template_file)) {
                $stat = @stat($template_file);
                if ($stat !== false) {
                    $mode = $stat[2];
                    $updated_mode = 0600;
                    if (($mode & 0020) == 0020) {
                        $updated_mode = $updated_mode | 0060;
                    }
                    $permissions_msg = sprintf(__('%s - using template', 'vmpfence-security'), str_pad(decoct($updated_mode), 4, '0', STR_PAD_LEFT));
                }
            }
        }
        
        $test['details'][] = array(
            'label' => __('WAF File Permissions', 'vmpfence-security'),
            'value' => $permissions_msg,
            'status' => 'passed'
        );

        // WAF Loaded Successfully (check if WAF is enabled and has rules)
        $waf_enabled = VMPFence_Config::get('waf_enabled', false);
        $table_name = $wpdb->prefix . 'vmpfence_waf_rules';
        $rule_count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name WHERE enabled = 1");
        $waf_loaded = $waf_enabled && $rule_count > 0;
        $test['details'][] = array(
            'label' => __('WAF Loaded Successfully', 'vmpfence-security'),
            'value' => $waf_loaded ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => $waf_loaded ? 'passed' : 'warning'
        );

        if (!$waf_loaded) {
            $test['status'] = 'warning';
        }

        return $test;
    }

    /**
     * Test Database Health
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_database() {
        global $wpdb;
        
        $test = array(
            'name' => __('MySQL', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // Get database version
        $version = $wpdb->get_var("SELECT VERSION()");
        $test['details'][] = array(
            'label' => __('Database Version', 'vmpfence-security'),
            'value' => $version,
            'status' => 'passed'
        );

        // Check MySQL user privileges
        $privileges = array('DELETE', 'INSERT', 'UPDATE', 'SELECT', 'CREATE', 'ALTER', 'DROP', 'CREATE TEMPORARY TABLES');
        $grants = $wpdb->get_results("SHOW GRANTS FOR CURRENT_USER", ARRAY_N);

        foreach ($privileges as $privilege) {
            $has_privilege = false;
            
            if ($grants) {
                foreach ($grants as $grant) {
                    $grant_string = $grant[0];
                    // Check for ALL PRIVILEGES or specific privilege
                    if (stripos($grant_string, 'ALL PRIVILEGES') !== false || stripos($grant_string, $privilege) !== false) {
                        $has_privilege = true;
                        break;
                    }
                }
            }
            
            $label_map = array(
                'DELETE' => 'DELETE privilege',
                'INSERT' => 'INSERT privilege',
                'UPDATE' => 'UPDATE privilege',
                'SELECT' => 'SELECT privilege',
                'CREATE' => 'CREATE TABLE privilege',
                'ALTER' => 'ALTER TABLE privilege',
                'DROP' => 'DROP privilege',
                'CREATE TEMPORARY TABLES' => 'TRUNCATE privilege'
            );
            
            $test['details'][] = array(
                'label' => sprintf(__('Checking if MySQL user has %s', 'vmpfence-security'), $label_map[$privilege]),
                'value' => $has_privilege ? __('OK', 'vmpfence-security') : __('FAIL', 'vmpfence-security'),
                'status' => $has_privilege ? 'passed' : 'failed'
            );
            
            if (!$has_privilege && $test['status'] !== 'failed') {
                $test['status'] = 'failed';
            }
        }

        return $test;
    }

    /**
     * Test PHP Environment
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_php_environment() {
        
        $test = array(
            'name' => __('PHP Environment', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // PHP Version
        $php_version = phpversion();
        $php_ok = version_compare($php_version, '7.0.0', '>=');
        
        $test['details'][] = array(
            'label' => __('PHP version >= PHP 7.0.0 (<a href="https://wordpress.org/about/requirements/" target="_blank">WordPress requirements</a>)', 'vmpfence-security'),
            'value' => $php_version,
            'status' => $php_ok ? 'passed' : 'failed'
        );

        if (!$php_ok) {
            $test['status'] = 'failed';
        }

        // Process Owner
        $process_owner = function_exists('posix_getpwuid') && function_exists('posix_geteuid') 
            ? posix_getpwuid(posix_geteuid())['name'] 
            : (getenv('USERNAME') ?: getenv('USER') ?: 'Unknown');
        
        $test['details'][] = array(
            'label' => __('Process Owner', 'vmpfence-security'),
            'value' => $process_owner,
            'status' => 'passed'
        );

        // OpenSSL Support
        $openssl_loaded = extension_loaded('openssl');
        $test['details'][] = array(
            'label' => __('Checking for OpenSSL support', 'vmpfence-security'),
            'value' => $openssl_loaded ? __('OK', 'vmpfence-security') : __('Not Available', 'vmpfence-security'),
            'status' => $openssl_loaded ? 'passed' : 'warning'
        );

        // OpenSSL Version
        if ($openssl_loaded && defined('OPENSSL_VERSION_TEXT')) {
            $openssl_version = OPENSSL_VERSION_TEXT . ' (' . sprintf('0x%08x', OPENSSL_VERSION_NUMBER) . ')';
            $test['details'][] = array(
                'label' => __('Checking OpenSSL version', 'vmpfence-security'),
                'value' => $openssl_version,
                'status' => 'passed'
            );
        }

        // cURL Support
        $curl_loaded = extension_loaded('curl');
        if ($curl_loaded && function_exists('curl_version')) {
            $curl_info = curl_version();
            
            // cURL Version
            $curl_version = $curl_info['version'] . ' (' . sprintf('0x%06x', $curl_info['version_number']) . ')';
            $test['details'][] = array(
                'label' => __('Checking for cURL support', 'vmpfence-security'),
                'value' => $curl_version,
                'status' => 'passed'
            );

            // cURL Features Code
            $test['details'][] = array(
                'label' => __('cURL Features Code', 'vmpfence-security'),
                'value' => sprintf('0x%08x', $curl_info['features']),
                'status' => 'passed'
            );

            // cURL Host
            $test['details'][] = array(
                'label' => __('cURL Host', 'vmpfence-security'),
                'value' => $curl_info['host'],
                'status' => 'passed'
            );

            // cURL Supported Protocols
            $protocols = implode(', ', $curl_info['protocols']);
            $test['details'][] = array(
                'label' => __('cURL Support Protocols', 'vmpfence-security'),
                'value' => $protocols,
                'status' => 'passed'
            );

            // cURL SSL Version
            $test['details'][] = array(
                'label' => __('cURL SSL Version', 'vmpfence-security'),
                'value' => $curl_info['ssl_version'],
                'status' => 'passed'
            );

            // cURL libz Version
            if (isset($curl_info['libz_version'])) {
                $test['details'][] = array(
                    'label' => __('cURL libz Version', 'vmpfence-security'),
                    'value' => $curl_info['libz_version'],
                    'status' => 'passed'
                );
            }
        } else {
            $test['details'][] = array(
                'label' => __('Checking for cURL support', 'vmpfence-security'),
                'value' => __('Not Available', 'vmpfence-security'),
                'status' => 'warning'
            );
            
            if ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
        }

        // Display Errors
        $display_errors = ini_get('display_errors');
        $display_errors_on = $display_errors && strtolower($display_errors) !== 'off';
        $test['details'][] = array(
            'label' => __('Checking display_errors (<a href="https://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors" target="_blank">Should be disabled on production servers</a>)', 'vmpfence-security'),
            'value' => $display_errors_on ? __('On', 'vmpfence-security') : __('Off', 'vmpfence-security'),
            'status' => $display_errors_on ? 'warning' : 'passed'
        );

        if ($display_errors_on && $test['status'] === 'passed') {
            $test['status'] = 'warning';
        }

        return $test;
    }

    /**
     * Test Network Connectivity
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_connectivity() {
        
        $test = array(
            'name' => __('Connectivity', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // Test VMPFence servers connectivity (https)
        $vmpfence_start = microtime(true);
        $vmpfence_server = 'https://newton-wordpress-security.vpnmasterpro.com/';
        $vmpfence_response = wp_remote_get($vmpfence_server, array('timeout' => 10, 'sslverify' => true));
        $vmpfence_ok = !is_wp_error($vmpfence_response) && wp_remote_retrieve_response_code($vmpfence_response) === 200;
        
        $test['details'][] = array(
            'label' => __('Connecting to VMPFence servers (https)', 'vmpfence-security'),
            'value' => $vmpfence_ok ? __('OK', 'vmpfence-security') : __('Failed', 'vmpfence-security'),
            'status' => $vmpfence_ok ? 'passed' : 'warning'
        );

        if (!$vmpfence_ok) {
            $test['status'] = 'warning';
        }

        // Test self-connectivity (back to this site)
        $self_start = microtime(true);
        $admin_ajax = admin_url('admin-ajax.php?action=vmpfence_testAjax');
        $response = wp_remote_post($admin_ajax, array(
            'timeout' => 10,
            'blocking' => true,
            'headers' => array()
        ));
        
        $self_ok = !is_wp_error($response) 
                   && wp_remote_retrieve_response_code($response) === 200 
                   && strpos(wp_remote_retrieve_body($response), 'VMPWORDPRESSSECURITYSCANTESTOK') !== false;
        $self_duration = microtime(true) - $self_start;



        $test['details'][] = array(
            'label' => __('Connecting back to this site', 'vmpfence-security'),
            'value' => $self_ok ? __('OK', 'vmpfence-security') : __('Failed', 'vmpfence-security'),
            'status' => $self_ok ? 'passed' : 'warning'
        );

        if (!$self_ok && $test['status'] !== 'warning') {
            $test['status'] = 'warning';
        }

        // Test IPv6 connectivity (not required)
        $ipv6_start = microtime(true);
        $ipv6_value = '';
        $ipv6_ok = false;
        
        if (function_exists('curl_version')) {
            $interceptor = new VMPFence_Curl_Interceptor();
            $interceptor->setOption(CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
            try {
                $admin_ajax = admin_url('admin-ajax.php?action=vmpfence_testAjax');
                $ipv6_response = $interceptor->intercept(function() use ($admin_ajax) {
                    return wp_remote_post($admin_ajax, array(
                        'timeout' => 10,
                        'blocking' => true,
                        'headers' => array()
                    ));
                });
                
                $ipv6_ok = !is_wp_error($ipv6_response) 
                           && wp_remote_retrieve_response_code($ipv6_response) === 200 
                           && strpos(wp_remote_retrieve_body($ipv6_response), 'VMPWORDPRESSSECURITYSCANTESTOK') !== false;
                
                // Get error message if failed
                if ($ipv6_ok) {
                    $ipv6_value = __('OK', 'vmpfence-security');
                } else {
                    if (is_wp_error($ipv6_response)) {
                        $ipv6_value = __('wp_remote_post() test back to this server failed! Response was: ', 'vmpfence-security') . $ipv6_response->get_error_message();
                    } else {
                        $ipv6_value = __('wp_remote_post() test back to this server failed! Response was: ', 'vmpfence-security') . $ipv6_response['response']['code'] . ' ' . $ipv6_response['response']['message'];
                    }
                }
            } catch (VMPFence_Curl_Interception_Failed_Exception $e) {
                $ipv6_value = __('This diagnostic is unavailable as cURL appears to be supported, but was not used by WordPress for this request', 'vmpfence-security');
            }
        } else {
            $ipv6_value = __('This diagnostic requires cURL', 'vmpfence-security');
        }
        
        $test['details'][] = array(
            'label' => __('Connecting back to this site via IPv6 (not required; failure to connect may not be an issue on some sites)', 'vmpfence-security'),
            'value' => $ipv6_value,
            'status' => $ipv6_ok ? 'passed' : 'warning' // Warning if failed, but not critical
        );

        // Get server IP(s)
        $ip_start = microtime(true);
        $server_ips = array();
        
        // Try to get from $_SERVER
        if (isset($_SERVER['SERVER_ADDR'])) {
            $server_ips[] = $_SERVER['SERVER_ADDR'];
        }
        
        // Try to get from hostname resolution
        $hostname = gethostname();
        if ($hostname) {
            $resolved_ip = gethostbyname($hostname);
            if ($resolved_ip !== $hostname && !in_array($resolved_ip, $server_ips)) {
                $server_ips[] = $resolved_ip;
            }
        }
        
        // Try to get external IP
        $external_ip_services = array('https://api.ipify.org', 'https://ifconfig.me/ip', 'https://icanhazip.com');
        foreach ($external_ip_services as $service) {
            $ip_response = wp_remote_get($service, array('timeout' => 5));
            if (!is_wp_error($ip_response) && wp_remote_retrieve_response_code($ip_response) === 200) {
                $external_ip = trim(wp_remote_retrieve_body($ip_response));
                if (filter_var($external_ip, FILTER_VALIDATE_IP) && !in_array($external_ip, $server_ips)) {
                    $server_ips[] = $external_ip;
                    break;
                }
            }
        }
        
        $ip_list = !empty($server_ips) ? implode(', ', $server_ips) : 'Unable to determine';
        $test['details'][] = array(
            'label' => __('IP(s) used by this server', 'vmpfence-security'),
            'value' => $ip_list,
            'status' => 'passed'
        );

        return $test;
    }

    /**
     * Test Time Synchronization
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_time() {
        
        $test = array(
            'name' => __('Time', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // VMPFence Network Time
        $vmpfence_time = self::get_vmpfence_network_time();
        
        $test['details'][] = array(
            'label' => __('VMP Security Network Time', 'vmpfence-security'),
            'value' => $vmpfence_time,
            'status' => 'passed'
        );

        // Server Time
        $server_time = gmdate('Y-m-d H:i:s') . ' UTC';
        $test['details'][] = array(
            'label' => __('Server Time', 'vmpfence-security'),
            'value' => $server_time,
            'status' => 'passed'
        );

        // VMPFence Network Time Offset
        $vmpfence_offset = self::get_vmpfence_time_offset();
        
        $test['details'][] = array(
            'label' => __('VMP Security Network Time Offset', 'vmpfence-security'),
            'value' => $vmpfence_offset,
            'status' => 'passed'
        );

        // NTP Time Offset
        $ntp_offset = self::get_ntp_time_offset();
        
        $test['details'][] = array(
            'label' => __('NTP Time Offset', 'vmpfence-security'),
            'value' => $ntp_offset,
            'status' => 'passed'
        );

        // NTP Status
        $ntp_status = self::get_ntp_status();
        
        $test['details'][] = array(
            'label' => __('NTP Status', 'vmpfence-security'),
            'value' => $ntp_status,
            'status' => 'passed'
        );

        // TOTP Time Source
        $time_source = self::get_totp_time_source();
        
        $test['details'][] = array(
            'label' => __('TOTP Time Source', 'vmpfence-security'),
            'value' => $time_source,
            'status' => 'passed'
        );

        // WordPress Time Zone
        $timezone = wp_timezone_string();
        $test['details'][] = array(
            'label' => __('WordPress Time Zone', 'vmpfence-security'),
            'value' => $timezone,
            'status' => 'passed'
        );


        return $test;
    }

    /**
     * Get VMPFence network time
     *
     * @return string
     */
    private static function get_vmpfence_network_time() {
        $response = wp_remote_get('https://newton-wordpress-security.vpnmasterpro.com/api/v1/system/time', array('timeout' => 5));
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            if (isset($body['timestamp'])) {
                return gmdate('Y-m-d H:i:s', $body['timestamp']) . ' UTC';
            }
        }
        
        return '-';
    }

    /**
     * Get VMPFence time offset
     *
     * @return string
     */
    private static function get_vmpfence_time_offset() {
        $response = wp_remote_get('https://newton-wordpress-security.vpnmasterpro.com/api/v1/system/time', array('timeout' => 5));
        
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            if (isset($body['timestamp'])) {
                $delta = $body['timestamp'] - time();
                if (abs($delta) < 1) {
                    return '+ less than 1 second';
                }
                return ($delta < 0 ? '- ' : '+ ') . self::make_duration(abs($delta));
            }
        }
        
        return '-';
    }

    /**
     * Get NTP time offset
     *
     * @return string
     */
    private static function get_ntp_time_offset() {
        $ntp_time = self::get_ntp_time();
        
        if ($ntp_time === false) {
            return __('Blocked', 'vmpfence-security');
        }
        
        if ($ntp_time === null) {
            return '-';
        }
        
        $delta = $ntp_time - time();
        if (abs($delta) < 1) {
            return '+ less than 1 second';
        }
        return ($delta < 0 ? '- ' : '+ ') . self::make_duration(abs($delta));
    }

    /**
     * Get NTP time from pool.ntp.org
     *
     * @return int|bool|null Timestamp, false if blocked, null if unavailable
     */
    private static function get_ntp_time() {
        if (!function_exists('fsockopen')) {
            return null;
        }
        
        $host = 'pool.ntp.org';
        $port = 123;
        
        $socket = @fsockopen('udp://' . $host, $port, $errno, $errstr, 2);
        
        if (!$socket) {
            return false;
        }
        
        // Set socket timeout
        stream_set_timeout($socket, 2);
        
        // NTP packet structure
        $msg = "\010" . str_repeat("\0", 47);
        fwrite($socket, $msg);
        
        $data = fread($socket, 48);
        
        fclose($socket);
        
        if (strlen($data) == 48) {
            $unpack = unpack('N12', $data);
            $timestamp = sprintf('%u', $unpack[9]) - 2208988800; // Convert from 1900 to 1970 epoch
            return $timestamp;
        }
        
        return null;
    }

    /**
     * Get NTP status
     *
     * @return string
     */
    private static function get_ntp_status() {
        // Check if NTP is disabled via constant
        if (defined('VMPFENCE_DISABLE_NTP') && VMPFENCE_DISABLE_NTP) {
            return __('Disabled (VMPFENCE_DISABLE_NTP)', 'vmpfence-security');
        }
        
        // Check if NTP is working
        $ntp_time = self::get_ntp_time();
        if ($ntp_time === false) {
            return __('Disabled (blocked)', 'vmpfence-security');
        }
        
        if ($ntp_time === null) {
            return __('Disabled (unavailable)', 'vmpfence-security');
        }
        
        return __('Enabled', 'vmpfence-security');
    }

    /**
     * Get TOTP time source
     *
     * @return string
     */
    private static function get_totp_time_source() {
        $ntp_time = self::get_ntp_time();
        
        if ($ntp_time !== false && $ntp_time !== null) {
            return __('NTP', 'vmpfence-security');
        }
        
        // Check if VMPFence network time is available
        $response = wp_remote_get('https://newton-wordpress-security.vpnmasterpro.com/api/v1/system/time', array('timeout' => 5));
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            $body = json_decode(wp_remote_retrieve_body($response), true);
            if (isset($body['timestamp'])) {
                return __('VMPFence Network', 'vmpfence-security');
            }
        }
        
        return __('System', 'vmpfence-security');
    }

    /**
     * Make duration string from seconds
     *
     * @param int $seconds
     * @return string
     */
    private static function make_duration($seconds) {
        if ($seconds < 60) {
            return sprintf(_n('%d second', '%d seconds', $seconds, 'vmpfence-security'), $seconds);
        }
        
        $minutes = floor($seconds / 60);
        if ($minutes < 60) {
            return sprintf(_n('%d minute', '%d minutes', $minutes, 'vmpfence-security'), $minutes);
        }
        
        $hours = floor($minutes / 60);
        if ($hours < 24) {
            return sprintf(_n('%d hour', '%d hours', $hours, 'vmpfence-security'), $hours);
        }
        
        $days = floor($hours / 24);
        return sprintf(_n('%d day', '%d days', $days, 'vmpfence-security'), $days);
    }

    /**
     * Test IP Detection
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_ip_detection() {
        $test = array(
            'name' => __('IP Detection', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // REMOTE_ADDR
        $remote_addr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '(not set)';
        $remote_addr_used = isset($_SERVER['REMOTE_ADDR']);
        $test['details'][] = array(
            'label' => __('REMOTE_ADDR', 'vmpfence-security'),
            'value' => $remote_addr,
            'status' => $remote_addr_used ? 'passed' : 'warning',
            'used' => $remote_addr_used ? __('In use', 'vmpfence-security') : ''
        );

        // CF-Connecting-IP
        $cf_ip = isset($_SERVER['HTTP_CF_CONNECTING_IP']) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : '(not set)';
        $test['details'][] = array(
            'label' => __('CF-Connecting-IP', 'vmpfence-security'),
            'value' => $cf_ip,
            'status' => 'passed',
            'used' => ''
        );

        // X-Real-IP
        $x_real_ip = isset($_SERVER['HTTP_X_REAL_IP']) ? $_SERVER['HTTP_X_REAL_IP'] : '(not set)';
        $test['details'][] = array(
            'label' => __('X-Real-IP', 'vmpfence-security'),
            'value' => $x_real_ip,
            'status' => 'passed',
            'used' => ''
        );

        // X-Forwarded-For
        $x_forwarded = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '(not set)';
        $test['details'][] = array(
            'label' => __('X-Forwarded-For', 'vmpfence-security'),
            'value' => $x_forwarded,
            'status' => 'passed',
            'used' => ''
        );

        // Trusted Proxies
        $trusted_proxies = VMPFence_Config::get('trusted_proxies', '');
        $test['details'][] = array(
            'label' => __('Trusted Proxies', 'vmpfence-security'),
            'value' => !empty($trusted_proxies) ? $trusted_proxies : '(not set)',
            'status' => 'passed',
            'used' => ''
        );

        // Trusted Proxy Preset
        $proxy_preset = VMPFence_Config::get('trusted_proxy_preset', '');
        $test['details'][] = array(
            'label' => __('Trusted Proxy Preset', 'vmpfence-security'),
            'value' => !empty($proxy_preset) ? $proxy_preset : '(not set)',
            'status' => 'passed',
            'used' => ''
        );

        return $test;
    }

    /**
     * Test WordPress Settings
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_wordpress_settings() {
        global $wp_version;
        
        $test = array(
            'name' => __('WordPress Settings', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // WordPress Version
        $test['details'][] = array(
            'label' => __('WordPress Version', 'vmpfence-security'),
            'value' => $wp_version,
            'status' => 'passed'
        );

        // Multisite
        $test['details'][] = array(
            'label' => __('Multisite', 'vmpfence-security'),
            'value' => is_multisite() ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Return value of is_multisite()', 'vmpfence-security')
        );

        // ABSPATH
        $test['details'][] = array(
            'label' => __('ABSPATH', 'vmpfence-security'),
            'value' => ABSPATH,
            'status' => 'passed',
            'description' => __('WordPress base path', 'vmpfence-security')
        );

        // WP_DEBUG
        $test['details'][] = array(
            'label' => __('WP_DEBUG', 'vmpfence-security'),
            'value' => defined('WP_DEBUG') && WP_DEBUG ? __('On', 'vmpfence-security') : __('Off', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('WordPress debug mode', 'vmpfence-security')
        );

        // WP_DEBUG_LOG
        $wp_debug_log = 'Disabled';
        if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
            $wp_debug_log = is_string(WP_DEBUG_LOG) ? WP_DEBUG_LOG : 'Enabled';
        }
        $test['details'][] = array(
            'label' => __('WP_DEBUG_LOG', 'vmpfence-security'),
            'value' => $wp_debug_log,
            'status' => 'passed',
            'description' => __('WordPress error logging override', 'vmpfence-security')
        );

        // WP_DEBUG_DISPLAY
        $test['details'][] = array(
            'label' => __('WP_DEBUG_DISPLAY', 'vmpfence-security'),
            'value' => defined('WP_DEBUG_DISPLAY') && !WP_DEBUG_DISPLAY ? __('Disabled', 'vmpfence-security') : __('Enabled', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('WordPress error display override', 'vmpfence-security')
        );

        // SCRIPT_DEBUG
        $test['details'][] = array(
            'label' => __('SCRIPT_DEBUG', 'vmpfence-security'),
            'value' => defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? __('On', 'vmpfence-security') : __('Off', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('WordPress script debug mode', 'vmpfence-security')
        );

        // SAVEQUERIES
        $test['details'][] = array(
            'label' => __('SAVEQUERIES', 'vmpfence-security'),
            'value' => defined('SAVEQUERIES') && SAVEQUERIES ? __('On', 'vmpfence-security') : __('Off', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('WordPress query debug mode', 'vmpfence-security')
        );

        // DB_CHARSET
        $test['details'][] = array(
            'label' => __('DB_CHARSET', 'vmpfence-security'),
            'value' => defined('DB_CHARSET') ? DB_CHARSET : '(not set)',
            'status' => 'passed',
            'description' => __('Database character set', 'vmpfence-security')
        );

        // DB_COLLATE
        $test['details'][] = array(
            'label' => __('DB_COLLATE', 'vmpfence-security'),
            'value' => defined('DB_COLLATE') && DB_COLLATE ? DB_COLLATE : '',
            'status' => 'passed',
            'description' => __('Database collation', 'vmpfence-security')
        );

        // WP_SITEURL
        $test['details'][] = array(
            'label' => __('WP_SITEURL', 'vmpfence-security'),
            'value' => defined('WP_SITEURL') ? WP_SITEURL : '(not set)',
            'status' => 'passed',
            'description' => __('Explicitly set site URL', 'vmpfence-security')
        );

        // WP_HOME
        $test['details'][] = array(
            'label' => __('WP_HOME', 'vmpfence-security'),
            'value' => defined('WP_HOME') ? WP_HOME : '(not set)',
            'status' => 'passed',
            'description' => __('Explicitly set blog URL', 'vmpfence-security')
        );

        // WP_CONTENT_DIR
        $default_content_dir = ABSPATH . 'wp-content';
        $is_default = (WP_CONTENT_DIR === $default_content_dir);
        $test['details'][] = array(
            'label' => __('WP_CONTENT_DIR', 'vmpfence-security'),
            'value' => $is_default ? __('Yes', 'vmpfence-security') : WP_CONTENT_DIR,
            'status' => 'passed',
            'description' => __('"wp-content" folder is in default location', 'vmpfence-security')
        );

        // WP_CONTENT_URL
        $test['details'][] = array(
            'label' => __('WP_CONTENT_URL', 'vmpfence-security'),
            'value' => WP_CONTENT_URL,
            'status' => 'passed',
            'description' => __('URL to the "wp-content" folder', 'vmpfence-security')
        );

        // WP_PLUGIN_DIR
        $default_plugin_dir = WP_CONTENT_DIR . '/plugins';
        $is_default = (WP_PLUGIN_DIR === $default_plugin_dir);
        $test['details'][] = array(
            'label' => __('WP_PLUGIN_DIR', 'vmpfence-security'),
            'value' => $is_default ? __('Yes', 'vmpfence-security') : WP_PLUGIN_DIR,
            'status' => 'passed',
            'description' => __('"plugins" folder is in default location', 'vmpfence-security')
        );

        // WP_LANG_DIR
        $default_lang_dir = WP_CONTENT_DIR . '/languages';
        $is_default = (WP_LANG_DIR === $default_lang_dir);
        $test['details'][] = array(
            'label' => __('WP_LANG_DIR', 'vmpfence-security'),
            'value' => $is_default ? __('Yes', 'vmpfence-security') : WP_LANG_DIR,
            'status' => 'passed',
            'description' => __('"languages" folder is in default location', 'vmpfence-security')
        );

        // WPLANG
        $test['details'][] = array(
            'label' => __('WPLANG', 'vmpfence-security'),
            'value' => defined('WPLANG') && WPLANG ? WPLANG : '(not set)',
            'status' => 'passed',
            'description' => __('Language choice', 'vmpfence-security')
        );

        // UPLOADS
        $test['details'][] = array(
            'label' => __('UPLOADS', 'vmpfence-security'),
            'value' => defined('UPLOADS') ? UPLOADS : '(not set)',
            'status' => 'passed',
            'description' => __('Custom upload folder location', 'vmpfence-security')
        );

        // TEMPLATEPATH
        $test['details'][] = array(
            'label' => __('TEMPLATEPATH', 'vmpfence-security'),
            'value' => defined('TEMPLATEPATH') && TEMPLATEPATH !== get_template_directory() ? TEMPLATEPATH : '(not set)',
            'status' => 'passed',
            'description' => __('Theme template folder override', 'vmpfence-security')
        );

        // STYLESHEETPATH
        $test['details'][] = array(
            'label' => __('STYLESHEETPATH', 'vmpfence-security'),
            'value' => defined('STYLESHEETPATH') && STYLESHEETPATH !== get_stylesheet_directory() ? STYLESHEETPATH : '(not set)',
            'status' => 'passed',
            'description' => __('Theme stylesheet folder override', 'vmpfence-security')
        );

        // AUTOSAVE_INTERVAL
        $test['details'][] = array(
            'label' => __('AUTOSAVE_INTERVAL', 'vmpfence-security'),
            'value' => defined('AUTOSAVE_INTERVAL') ? AUTOSAVE_INTERVAL : '60',
            'status' => 'passed',
            'description' => __('Post editing automatic saving interval', 'vmpfence-security')
        );

        // WP_POST_REVISIONS
        $revisions = 'Unlimited';
        if (defined('WP_POST_REVISIONS')) {
            if (WP_POST_REVISIONS === false) {
                $revisions = 'Disabled';
            } elseif (is_numeric(WP_POST_REVISIONS)) {
                $revisions = WP_POST_REVISIONS;
            }
        }
        $test['details'][] = array(
            'label' => __('WP_POST_REVISIONS', 'vmpfence-security'),
            'value' => $revisions,
            'status' => 'passed',
            'description' => __('Post revisions saved by WordPress', 'vmpfence-security')
        );

        // COOKIE_DOMAIN
        $test['details'][] = array(
            'label' => __('COOKIE_DOMAIN', 'vmpfence-security'),
            'value' => defined('COOKIE_DOMAIN') && COOKIE_DOMAIN ? COOKIE_DOMAIN : '',
            'status' => 'passed',
            'description' => __('WordPress cookie domain', 'vmpfence-security')
        );

        // COOKIEPATH
        $test['details'][] = array(
            'label' => __('COOKIEPATH', 'vmpfence-security'),
            'value' => defined('COOKIEPATH') ? COOKIEPATH : '/',
            'status' => 'passed',
            'description' => __('WordPress cookie path', 'vmpfence-security')
        );

        // SITECOOKIEPATH
        $test['details'][] = array(
            'label' => __('SITECOOKIEPATH', 'vmpfence-security'),
            'value' => defined('SITECOOKIEPATH') ? SITECOOKIEPATH : '/',
            'status' => 'passed',
            'description' => __('WordPress site cookie path', 'vmpfence-security')
        );

        // ADMIN_COOKIE_PATH
        $test['details'][] = array(
            'label' => __('ADMIN_COOKIE_PATH', 'vmpfence-security'),
            'value' => defined('ADMIN_COOKIE_PATH') ? ADMIN_COOKIE_PATH : SITECOOKIEPATH . 'wp-admin',
            'status' => 'passed',
            'description' => __('WordPress admin cookie path', 'vmpfence-security')
        );

        // PLUGINS_COOKIE_PATH
        $test['details'][] = array(
            'label' => __('PLUGINS_COOKIE_PATH', 'vmpfence-security'),
            'value' => defined('PLUGINS_COOKIE_PATH') ? PLUGINS_COOKIE_PATH : WP_PLUGIN_URL,
            'status' => 'passed',
            'description' => __('WordPress plugins cookie path', 'vmpfence-security')
        );

        // NOBLOGREDIRECT
        $test['details'][] = array(
            'label' => __('NOBLOGREDIRECT', 'vmpfence-security'),
            'value' => defined('NOBLOGREDIRECT') ? NOBLOGREDIRECT : '(not set)',
            'status' => 'passed',
            'description' => __('URL redirected to if the visitor tries to access a nonexistent blog', 'vmpfence-security')
        );

        // CONCATENATE_SCRIPTS
        $test['details'][] = array(
            'label' => __('CONCATENATE_SCRIPTS', 'vmpfence-security'),
            'value' => defined('CONCATENATE_SCRIPTS') && CONCATENATE_SCRIPTS ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Concatenate JavaScript files', 'vmpfence-security')
        );

        // WP_MEMORY_LIMIT
        $test['details'][] = array(
            'label' => __('WP_MEMORY_LIMIT', 'vmpfence-security'),
            'value' => defined('WP_MEMORY_LIMIT') ? WP_MEMORY_LIMIT : '40M',
            'status' => 'passed',
            'description' => __('WordPress memory limit', 'vmpfence-security')
        );

        // WP_MAX_MEMORY_LIMIT
        $test['details'][] = array(
            'label' => __('WP_MAX_MEMORY_LIMIT', 'vmpfence-security'),
            'value' => defined('WP_MAX_MEMORY_LIMIT') ? WP_MAX_MEMORY_LIMIT : '256M',
            'status' => 'passed',
            'description' => __('Administrative memory limit', 'vmpfence-security')
        );

        // WP_CACHE
        $test['details'][] = array(
            'label' => __('WP_CACHE', 'vmpfence-security'),
            'value' => defined('WP_CACHE') && WP_CACHE ? __('Enabled', 'vmpfence-security') : __('Disabled', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Built-in caching', 'vmpfence-security')
        );

        // CUSTOM_USER_TABLE
        $test['details'][] = array(
            'label' => __('CUSTOM_USER_TABLE', 'vmpfence-security'),
            'value' => defined('CUSTOM_USER_TABLE') ? CUSTOM_USER_TABLE : '(not set)',
            'status' => 'passed',
            'description' => __('Custom "users" table', 'vmpfence-security')
        );

        // CUSTOM_USER_META_TABLE
        $test['details'][] = array(
            'label' => __('CUSTOM_USER_META_TABLE', 'vmpfence-security'),
            'value' => defined('CUSTOM_USER_META_TABLE') ? CUSTOM_USER_META_TABLE : '(not set)',
            'status' => 'passed',
            'description' => __('Custom "usermeta" table', 'vmpfence-security')
        );

        // FS_CHMOD_DIR
        $test['details'][] = array(
            'label' => __('FS_CHMOD_DIR', 'vmpfence-security'),
            'value' => defined('FS_CHMOD_DIR') ? decoct(FS_CHMOD_DIR) : '755',
            'status' => 'passed',
            'description' => __('Overridden permissions for a new folder', 'vmpfence-security')
        );

        // FS_CHMOD_FILE
        $test['details'][] = array(
            'label' => __('FS_CHMOD_FILE', 'vmpfence-security'),
            'value' => defined('FS_CHMOD_FILE') ? decoct(FS_CHMOD_FILE) : '644',
            'status' => 'passed',
            'description' => __('Overridden permissions for a new file', 'vmpfence-security')
        );

        // ALTERNATE_WP_CRON
        $test['details'][] = array(
            'label' => __('ALTERNATE_WP_CRON', 'vmpfence-security'),
            'value' => defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON ? __('Enabled', 'vmpfence-security') : __('Disabled', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Alternate WP cron', 'vmpfence-security')
        );

        // DISABLE_WP_CRON
        $test['details'][] = array(
            'label' => __('DISABLE_WP_CRON', 'vmpfence-security'),
            'value' => defined('DISABLE_WP_CRON') && DISABLE_WP_CRON ? __('Cron is disabled', 'vmpfence-security') : __('Cron is enabled', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('WP cron status', 'vmpfence-security')
        );

        // WP_CRON_LOCK_TIMEOUT
        $test['details'][] = array(
            'label' => __('WP_CRON_LOCK_TIMEOUT', 'vmpfence-security'),
            'value' => defined('WP_CRON_LOCK_TIMEOUT') ? WP_CRON_LOCK_TIMEOUT : '60',
            'status' => 'passed',
            'description' => __('Cron running frequency lock', 'vmpfence-security')
        );

        // EMPTY_TRASH_DAYS
        $test['details'][] = array(
            'label' => __('EMPTY_TRASH_DAYS', 'vmpfence-security'),
            'value' => defined('EMPTY_TRASH_DAYS') ? EMPTY_TRASH_DAYS : '30',
            'status' => 'passed',
            'description' => __('Interval the trash is automatically emptied at in days', 'vmpfence-security')
        );

        // WP_ALLOW_REPAIR
        $test['details'][] = array(
            'label' => __('WP_ALLOW_REPAIR', 'vmpfence-security'),
            'value' => defined('WP_ALLOW_REPAIR') && WP_ALLOW_REPAIR ? __('Enabled', 'vmpfence-security') : __('Disabled', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Automatic database repair', 'vmpfence-security')
        );

        // DO_NOT_UPGRADE_GLOBAL_TABLES
        $test['details'][] = array(
            'label' => __('DO_NOT_UPGRADE_GLOBAL_TABLES', 'vmpfence-security'),
            'value' => defined('DO_NOT_UPGRADE_GLOBAL_TABLES') && DO_NOT_UPGRADE_GLOBAL_TABLES ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Do not upgrade global tables', 'vmpfence-security')
        );

        // DISALLOW_FILE_EDIT
        $test['details'][] = array(
            'label' => __('DISALLOW_FILE_EDIT', 'vmpfence-security'),
            'value' => defined('DISALLOW_FILE_EDIT') && DISALLOW_FILE_EDIT ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Disallow plugin/theme editing', 'vmpfence-security')
        );

        // DISALLOW_FILE_MODS
        $test['details'][] = array(
            'label' => __('DISALLOW_FILE_MODS', 'vmpfence-security'),
            'value' => defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Disallow plugin/theme update and installation', 'vmpfence-security')
        );

        // IMAGE_EDIT_OVERWRITE
        $test['details'][] = array(
            'label' => __('IMAGE_EDIT_OVERWRITE', 'vmpfence-security'),
            'value' => defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Overwrite image edits when restoring the original', 'vmpfence-security')
        );

        // FORCE_SSL_ADMIN
        $test['details'][] = array(
            'label' => __('FORCE_SSL_ADMIN', 'vmpfence-security'),
            'value' => defined('FORCE_SSL_ADMIN') && FORCE_SSL_ADMIN ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Force SSL for administrative logins', 'vmpfence-security')
        );

        // WP_HTTP_BLOCK_EXTERNAL
        $test['details'][] = array(
            'label' => __('WP_HTTP_BLOCK_EXTERNAL', 'vmpfence-security'),
            'value' => defined('WP_HTTP_BLOCK_EXTERNAL') && WP_HTTP_BLOCK_EXTERNAL ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Block external URL requests', 'vmpfence-security')
        );

        // WP_ACCESSIBLE_HOSTS
        $test['details'][] = array(
            'label' => __('WP_ACCESSIBLE_HOSTS', 'vmpfence-security'),
            'value' => defined('WP_ACCESSIBLE_HOSTS') ? WP_ACCESSIBLE_HOSTS : '(not set)',
            'status' => 'passed',
            'description' => __('Allowlisted hosts', 'vmpfence-security')
        );

        // WP_AUTO_UPDATE_CORE
        $auto_update = 'Default';
        if (defined('WP_AUTO_UPDATE_CORE')) {
            if (WP_AUTO_UPDATE_CORE === true) {
                $auto_update = 'Everything';
            } elseif (WP_AUTO_UPDATE_CORE === false) {
                $auto_update = 'None';
            } elseif (WP_AUTO_UPDATE_CORE === 'minor') {
                $auto_update = 'Minor versions only';
            }
        }
        $test['details'][] = array(
            'label' => __('WP_AUTO_UPDATE_CORE', 'vmpfence-security'),
            'value' => $auto_update,
            'status' => 'passed',
            'description' => __('Automatic WP Core updates', 'vmpfence-security')
        );

        // WP_PROXY_HOST
        $test['details'][] = array(
            'label' => __('WP_PROXY_HOST', 'vmpfence-security'),
            'value' => defined('WP_PROXY_HOST') ? WP_PROXY_HOST : '(not set)',
            'status' => 'passed',
            'description' => __('Hostname for a proxy server', 'vmpfence-security')
        );

        // WP_PROXY_PORT
        $test['details'][] = array(
            'label' => __('WP_PROXY_PORT', 'vmpfence-security'),
            'value' => defined('WP_PROXY_PORT') ? WP_PROXY_PORT : '(not set)',
            'status' => 'passed',
            'description' => __('Port for a proxy server', 'vmpfence-security')
        );

        // MULTISITE
        $test['details'][] = array(
            'label' => __('MULTISITE', 'vmpfence-security'),
            'value' => defined('MULTISITE') && MULTISITE ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Multisite enabled', 'vmpfence-security')
        );

        // WP_ALLOW_MULTISITE
        $test['details'][] = array(
            'label' => __('WP_ALLOW_MULTISITE', 'vmpfence-security'),
            'value' => defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Multisite/network ability enabled', 'vmpfence-security')
        );

        // SUNRISE
        $test['details'][] = array(
            'label' => __('SUNRISE', 'vmpfence-security'),
            'value' => defined('SUNRISE') ? SUNRISE : '(not set)',
            'status' => 'passed',
            'description' => __('Multisite enabled, WordPress will load the /wp-content/sunrise.php file', 'vmpfence-security')
        );

        // SUBDOMAIN_INSTALL
        $test['details'][] = array(
            'label' => __('SUBDOMAIN_INSTALL', 'vmpfence-security'),
            'value' => defined('SUBDOMAIN_INSTALL') ? SUBDOMAIN_INSTALL : '(not set)',
            'status' => 'passed',
            'description' => __('Multisite enabled, subdomain installation constant', 'vmpfence-security')
        );

        // VHOST
        $test['details'][] = array(
            'label' => __('VHOST', 'vmpfence-security'),
            'value' => defined('VHOST') ? VHOST : '(not set)',
            'status' => 'passed',
            'description' => __('Multisite enabled, Older subdomain installation constant', 'vmpfence-security')
        );

        // DOMAIN_CURRENT_SITE
        $test['details'][] = array(
            'label' => __('DOMAIN_CURRENT_SITE', 'vmpfence-security'),
            'value' => defined('DOMAIN_CURRENT_SITE') ? DOMAIN_CURRENT_SITE : '(not set)',
            'status' => 'passed',
            'description' => __('Defines the multisite domain for the current site', 'vmpfence-security')
        );

        // PATH_CURRENT_SITE
        $test['details'][] = array(
            'label' => __('PATH_CURRENT_SITE', 'vmpfence-security'),
            'value' => defined('PATH_CURRENT_SITE') ? PATH_CURRENT_SITE : '(not set)',
            'status' => 'passed',
            'description' => __('Defines the multisite path for the current site', 'vmpfence-security')
        );

        // BLOG_ID_CURRENT_SITE
        $test['details'][] = array(
            'label' => __('BLOG_ID_CURRENT_SITE', 'vmpfence-security'),
            'value' => defined('BLOG_ID_CURRENT_SITE') ? BLOG_ID_CURRENT_SITE : '(not set)',
            'status' => 'passed',
            'description' => __('Defines the multisite database ID for the current site', 'vmpfence-security')
        );

        // WP_DISABLE_FATAL_ERROR_HANDLER
        $test['details'][] = array(
            'label' => __('WP_DISABLE_FATAL_ERROR_HANDLER', 'vmpfence-security'),
            'value' => defined('WP_DISABLE_FATAL_ERROR_HANDLER') && WP_DISABLE_FATAL_ERROR_HANDLER ? __('Yes', 'vmpfence-security') : __('No', 'vmpfence-security'),
            'status' => 'passed',
            'description' => __('Disable the fatal error handler', 'vmpfence-security')
        );

        // AUTOMATIC_UPDATER_DISABLED
        $test['details'][] = array(
            'label' => __('AUTOMATIC_UPDATER_DISABLED', 'vmpfence-security'),
            'value' => defined('AUTOMATIC_UPDATER_DISABLED') ? (AUTOMATIC_UPDATER_DISABLED ? 'true' : 'false') : '(not set)',
            'status' => 'passed',
            'description' => __('Disables automatic updates', 'vmpfence-security')
        );

        return $test;
    }

    /**
     * Test WordPress Plugins
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_wordpress_plugins() {
        $test = array(
            'name' => __('WordPress Plugins', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );
        // Ensure function exists
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        // Get all plugins
        $all_plugins = get_plugins();
        $active_plugins = get_option('active_plugins', array());
        if (empty($all_plugins)) {
            $test['details'][] = array(
                'label' => __('No plugins installed', 'vmpfence-security'),
                'value' => '',
                'status' => 'passed'
            );
            return $test;
        }

        // Sort plugins alphabetically by name
        uasort($all_plugins, function($a, $b) {
            return strcmp($a['Name'], $b['Name']);
        });

        foreach ($all_plugins as $plugin_path => $plugin_data) {
            $is_active = in_array($plugin_path, $active_plugins);
            
            // Format: Plugin Name (folder/file) - Version X.X.X
            $plugin_name = $plugin_data['Name'];
            $plugin_slug = dirname($plugin_path);
            if ($plugin_slug === '.') {
                $plugin_slug = basename($plugin_path, '.php');
            }
            
            $label = sprintf('%s (%s) - Version %s', 
                $plugin_name,
                $plugin_slug,
                $plugin_data['Version']
            );
            
            $test['details'][] = array(
                'label' => $label,
                'value' => $is_active ? __('Active', 'vmpfence-security') : __('Inactive', 'vmpfence-security'),
                'status' => $is_active ? 'passed' : 'info'
            );
        }

        return $test;
    }

    /**
     * Test Must-Use WordPress Plugins
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_mu_plugins() {
        $test = array(
            'name' => __('Must-Use WordPress Plugins', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // Ensure function exists
        if (!function_exists('get_mu_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        // Get must-use plugins
        $mu_plugins = get_mu_plugins();

        if (empty($mu_plugins)) {
            $test['details'][] = array(
                'label' => __('No must-use plugins installed', 'vmpfence-security'),
                'value' => '',
                'status' => 'passed'
            );
            return $test;
        }

        // Sort plugins alphabetically by name
        uasort($mu_plugins, function($a, $b) {
            return strcmp($a['Name'], $b['Name']);
        });

        foreach ($mu_plugins as $plugin_file => $plugin_data) {
            // Format: Plugin Name (file.php)
            $plugin_name = $plugin_data['Name'];
            
            $label = sprintf('%s (%s)', 
                $plugin_name,
                $plugin_file
            );
            
            // MU plugins are always active
            $test['details'][] = array(
                'label' => $label,
                'value' => __('Active', 'vmpfence-security'),
                'status' => 'passed'
            );
        }

        return $test;
    }

    /**
     * Test Drop-in WordPress Plugins
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_dropin_plugins() {
        $test = array(
            'name' => __('Drop-in WordPress Plugins', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        $dropins = array(
            'advanced-cache.php'      => array( __('Advanced caching plugin', 'vmpfence-security'), 'WP_CACHE' ),
            'db.php'                  => array( __('Custom database class', 'vmpfence-security'), true ),
            'db-error.php'            => array( __('Custom database error message', 'vmpfence-security'), true ),
            'install.php'             => array( __('Custom installation script', 'vmpfence-security'), true ),
            'maintenance.php'         => array( __('Custom maintenance message', 'vmpfence-security'), true ),
            'object-cache.php'        => array( __('External object cache', 'vmpfence-security'), true ),
            'php-error.php'           => array( __('Custom PHP error message', 'vmpfence-security'), true ),
            'fatal-error-handler.php' => array( __('Custom PHP fatal error handler', 'vmpfence-security'), true ),
        );
        
        // Add multisite-specific drop-ins
        $dropins['sunrise.php']        = array( __('Executed before Multisite is loaded', 'vmpfence-security'), is_multisite() && 'SUNRISE' );
        $dropins['blog-deleted.php']   = array( __('Custom site deleted message', 'vmpfence-security'), is_multisite() );
        $dropins['blog-inactive.php']  = array( __('Custom site inactive message', 'vmpfence-security'), is_multisite() );
        $dropins['blog-suspended.php'] = array( __('Custom site suspended message', 'vmpfence-security'), is_multisite() );

        $wp_content_dir = WP_CONTENT_DIR;

        foreach ($dropins as $file => $data) {
            $file_path = $wp_content_dir . '/' . $file;
            $file_exists = file_exists($file_path) && is_readable($file_path);
            $is_active = $file_exists && $data[1];
            
            $label = sprintf('%s (%s)', 
                $data[0],
                $file
            );
            
            $test['details'][] = array(
                'label' => $label,
                'value' => $is_active ? __('Active', 'vmpfence-security') : __('Inactive', 'vmpfence-security'),
                'status' => $is_active ? 'passed' : 'info'
            );
        }

        return $test;
    }

    /**
     * Test Themes
     *
     * @since 2.2.0
     * @return array Test result
     */
    private static function test_themes() {
        $test = array(
            'name' => __('Themes', 'vmpfence-security'),
            'status' => 'passed',
            'message' => '',
            'details' => array(),
            'recommendations' => array()
        );

        // Get all themes
        $all_themes = wp_get_themes();
        $current_theme = wp_get_theme();

        if (empty($all_themes)) {
            $test['details'][] = array(
                'label' => __('No themes installed', 'vmpfence-security'),
                'value' => '',
                'status' => 'passed'
            );
            return $test;
        }

        // Sort themes alphabetically by name
        uasort($all_themes, function($a, $b) {
            return strcmp($a->get('Name'), $b->get('Name'));
        });

        foreach ($all_themes as $theme_slug => $theme) {
            $is_active = ($theme->get_stylesheet() === $current_theme->get_stylesheet());
            
            $theme_name = $theme->get('Name');
            $version = $theme->get('Version');
            
            $label = sprintf('%s (%s) - Version %s', $theme_name, $theme_slug, $version);
            $value = $is_active ? __('Active', 'vmpfence-security') : __('Inactive', 'vmpfence-security');
            
            $test['details'][] = array(
                'label' => $label,
                'value' => $value,
                'status' => $is_active ? 'passed' : 'info'
            );
        }

        return $test;
    }

    private static function test_cron_jobs() {
        $test = array(
            'status' => 'passed',
            'details' => array()
        );

        $cron_jobs = _get_cron_array();
        
        if (empty($cron_jobs)) {
            $test['details'][] = array(
                'label' => __('No cron jobs scheduled', 'vmpfence-security'),
                'value' => '',
                'status' => 'info'
            );
            return $test;
        }

        // Flatten the cron array and sort by next run time
        $scheduled_jobs = array();
        foreach ($cron_jobs as $timestamp => $cron) {
            foreach ($cron as $hook => $details) {
                foreach ($details as $key => $data) {
                    $scheduled_jobs[] = array(
                        'hook' => $hook,
                        'timestamp' => $timestamp,
                        'schedule' => isset($data['schedule']) ? $data['schedule'] : __('Single event', 'vmpfence-security'),
                        'next_run' => $timestamp
                    );
                }
            }
        }

        // Sort by next run time
        usort($scheduled_jobs, function($a, $b) {
            return $a['next_run'] - $b['next_run'];
        });

        foreach ($scheduled_jobs as $job) {
            $next_run = date('Y-m-d H:i:s', $job['timestamp']);
            $schedule_info = $job['schedule'];
            
            $label = $job['hook'];
            $value = sprintf(__('Next run: %s', 'vmpfence-security'), $next_run);
            
            if ($schedule_info !== __('Single event', 'vmpfence-security')) {
                $value .= ' (' . $schedule_info . ')';
            }
            
            $test['details'][] = array(
                'label' => $label,
                'value' => $value,
                'status' => 'info'
            );
        }

        return $test;
    }

    private static function test_database_tables() {
        global $wpdb;
        
        $test = array(
            'status' => 'passed',
            'details' => array(),
            'raw_data' => array() // Store raw table data for special rendering
        );

        // Get total table count
        $total_tables = $wpdb->get_var("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()");
        
        // Get table data (limit to 250 like Wordfence)
        $tables = $wpdb->get_results(
            "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() ORDER BY TABLE_NAME ASC LIMIT 250",
            ARRAY_A
        );
        
        if (!empty($tables)) {
            // Build IN clause for table names
            $table_names = array();
            foreach ($tables as $t) {
                $table_names[] = "'" . esc_sql($t['TABLE_NAME']) . "'";
            }
            
            // Get detailed table status
            $table_status = $wpdb->get_results(
                "SHOW TABLE STATUS WHERE Name IN (" . implode(',', $table_names) . ")",
                ARRAY_A
            );
            
            // VMPFence Table Check - verify all required tables exist
            if ($total_tables > 250) {
                $test['details'][] = array(
                    'label' => __('VMPFence Table Check', 'vmpfence-security'),
                    'value' => __('Unable to verify - table count too high', 'vmpfence-security'),
                    'status' => 'info'
                );
            } else {
                // Get list of existing tables
                $existing_tables = array_column($table_status, 'Name');
                
                // Windows MySQL is case-insensitive
                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                    $existing_tables = array_map('strtolower', $existing_tables);
                }
                
                // Get all required VMPFence tables from constants
                $required_tables = array(
                    VMPFence_Constants::TABLE_CONFIG,
                    VMPFence_Constants::TABLE_LS_SETTINGS,
                    VMPFence_Constants::TABLE_HITS,
                    VMPFence_Constants::TABLE_LOGINS,
                    VMPFence_Constants::TABLE_LOCKED_OUT,
                    VMPFence_Constants::TABLE_BLOCKS,
                    VMPFence_Constants::TABLE_BLOCKED_IPS,
                    VMPFence_Constants::TABLE_SECURITY_ATTEMPTS,
                    VMPFence_Constants::TABLE_WAF_LOG,
                    VMPFence_Constants::TABLE_EVENTS,
                    VMPFence_Constants::TABLE_AUDIT_LOG,
                    VMPFence_Constants::TABLE_SCAN_RESULTS,
                    VMPFence_Constants::TABLE_SCAN_ISSUES,
                    VMPFence_Constants::TABLE_FILE_MODS,
                    VMPFence_Constants::TABLE_KNOWN_FILES,
                    VMPFence_Constants::TABLE_FILE_CHANGES,
                    VMPFence_Constants::TABLE_LIVE_TRAFFIC_HUMAN,
                    VMPFence_Constants::TABLE_CRAWLERS,
                    VMPFence_Constants::TABLE_REVERSE_CACHE,
                    VMPFence_Constants::TABLE_STATUS,
                    VMPFence_Constants::TABLE_TRAFFIC_RATES,
                    VMPFence_Constants::TABLE_2FA,
                    VMPFence_Constants::TABLE_LS_2FA_SECRETS,
                    VMPFence_Constants::TABLE_LS_ROLE_COUNTS,
                    VMPFence_Constants::TABLE_NOTIFICATIONS,
                    VMPFence_Constants::TABLE_PENDING_ISSUES,
                    VMPFence_Constants::TABLE_SNIP_CACHE,
                    VMPFence_Constants::TABLE_WHOIS,
                    VMPFence_Constants::TABLE_WAF_FAILURES
                );
                
                $missing_tables = array();
                $has_all = true;
                
                foreach ($required_tables as $table_short_name) {
                    $table_full_name = $wpdb->prefix . $table_short_name;
                    
                    // Windows comparison
                    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                        $table_full_name = strtolower($table_full_name);
                    }
                    
                    if (!in_array($table_full_name, $existing_tables)) {
                        $has_all = false;
                        $missing_tables[] = $table_short_name;
                    }
                }
                
                if ($has_all) {
                    $test['details'][] = array(
                        'label' => __('VMPFence Table Check', 'vmpfence-security'),
                        'value' => __('All Tables Exist', 'vmpfence-security'),
                        'status' => 'passed'
                    );
                } else {
                    $test['details'][] = array(
                        'label' => __('VMPFence Table Check', 'vmpfence-security'),
                        'value' => sprintf(__('Tables missing (prefix %s): %s', 'vmpfence-security'), $wpdb->prefix, implode(', ', $missing_tables)),
                        'status' => 'failed'
                    );
                    $test['status'] = 'failed';
                }
            }
            
            // Add summary information
            $test['details'][] = array(
                'label' => __('Number of Database Tables', 'vmpfence-security'),
                'value' => $total_tables,
                'status' => 'info'
            );
            
            // Store raw table data for special rendering in JavaScript
            $test['raw_data'] = array(
                'tables' => $table_status,
                'total' => $total_tables,
                'displayed' => count($table_status)
            );
        } else {
            $test['details'][] = array(
                'label' => __('No database tables found', 'vmpfence-security'),
                'value' => '',
                'status' => 'warning'
            );
        }

        return $test;
    }

    private static function test_log_files() {
        $test = array(
            'status' => 'passed',
            'details' => array(),
            'raw_data' => array('log_files' => array()) // Store log file data for special rendering
        );

        $log_files = array();
        
        // Check WordPress debug.log
        $debug_log = WP_CONTENT_DIR . '/debug.log';
        if (file_exists($debug_log)) {
            $size = filesize($debug_log);
            $modified = filemtime($debug_log);
            $normalized_path = wp_normalize_path(realpath($debug_log));
            
            $log_files[$normalized_path] = array(
                'path' => str_replace(ABSPATH, '~/', $debug_log),
                'full_path' => $debug_log,
                'size' => $size,
                'size_formatted' => self::format_bytes($size),
                'modified' => date('M j, Y g:i:s A', $modified) . ' UTC',
                'timestamp' => $modified
            );
        }
        
        // Check PHP error log from php.ini
        $php_error_log = ini_get('error_log');
        if ($php_error_log && file_exists($php_error_log)) {
            $size = filesize($php_error_log);
            $modified = filemtime($php_error_log);
            $normalized_path = wp_normalize_path(realpath($php_error_log));
            
            // Only add if not already in array (using normalized path as key prevents duplicates)
            if (!isset($log_files[$normalized_path])) {
                $log_files[$normalized_path] = array(
                    'path' => $php_error_log,
                    'full_path' => $php_error_log,
                    'size' => $size,
                    'size_formatted' => self::format_bytes($size),
                    'modified' => date('M j, Y g:i:s A', $modified) . ' UTC',
                    'timestamp' => $modified
                );
            }
        }
        
        // Check common PHP error log locations
        $common_php_logs = array(
            'C:/xampp/php/logs/php_error_log',
            'C:\\xampp\\php\\logs\\php_error_log',
            '/var/log/php_errors.log',
            '/var/log/php/error.log'
        );
        
        foreach ($common_php_logs as $log_path) {
            if ($log_path && file_exists($log_path)) {
                $size = filesize($log_path);
                $modified = filemtime($log_path);
                $normalized_path = wp_normalize_path(realpath($log_path));
                
                // Only add if not already in array (using normalized path as key prevents duplicates)
                if (!isset($log_files[$normalized_path])) {
                    $log_files[$normalized_path] = array(
                        'path' => $log_path,
                        'full_path' => $log_path,
                        'size' => $size,
                        'size_formatted' => self::format_bytes($size),
                        'modified' => date('M j, Y g:i:s A', $modified) . ' UTC',
                        'timestamp' => $modified
                    );
                }
            }
        }
        
        // Convert associative array back to indexed array
        $log_files = array_values($log_files);
        
        if (empty($log_files)) {
            $test['details'][] = array(
                'label' => __('No log files found', 'vmpfence-security'),
                'value' => '',
                'status' => 'info'
            );
        } else {
            // Add a placeholder detail to trigger rendering
            $test['details'][] = array(
                'label' => __('Log files found', 'vmpfence-security'),
                'value' => count($log_files),
                'status' => 'passed'
            );
            $test['raw_data']['log_files'] = $log_files;
        }

        return $test;
    }
    
    private static function format_bytes($bytes, $precision = 2) {
        if ($bytes == 0) return '0 B';
        
        $units = array('B', 'KB', 'MB', 'GB', 'TB');
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= pow(1024, $pow);
        
        return round($bytes, $precision) . ' ' . $units[$pow];
    }

}
