<?php
/**
 * Diagnostic Management Class
 *
 * @package VMPFence
 * @since 1.0.0
 */

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

/**
 * VMPFence Diagnostic Class
 *
 * @since 1.0.0
 */
class VMPFence_Diagnostic {

    /**
     * Run comprehensive diagnostics
     *
     * @since 1.0.0
     * @param array $tests_to_run Specific tests to run
     * @return array
     */
    public static function run_diagnostics($tests_to_run = array()) {
        $all_tests = array(
            'system_requirements',
            'database_health',
            'file_permissions',
            'plugin_configuration',
            'security_status',
            'performance_metrics',
            'network_connectivity',
            'wp_environment'
        );

        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']++;
                        break;
                    case 'failed':
                        $results['summary']['failed']++;
                        break;
                }

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

        // Determine overall status
        if ($results['summary']['failed'] > 0) {
            $results['overall_status'] = 'critical';
        } elseif ($results['summary']['warnings'] > 0) {
            $results['overall_status'] = 'warning';
        }

        return $results;
    }

    /**
     * Test system requirements
     *
     * @since 1.0.0
     * @return array
     */
    private static function test_system_requirements() {
        $test = array(
            'name' => __('System Requirements', 'vmpfence-security'),
            'status' => 'passed',
            'message' => __('All system requirements met', 'vmpfence-security'),
            'details' => array(),
            'recommendations' => array()
        );

        $requirements = array(
            'php_version' => array(
                'required' => '7.4.0',
                'current' => PHP_VERSION,
                'name' => 'PHP Version'
            ),
            'wp_version' => array(
                'required' => '5.0',
                'current' => get_bloginfo('version'),
                'name' => 'WordPress Version'
            ),
            'memory_limit' => array(
                'required' => '256M',
                'current' => ini_get('memory_limit'),
                'name' => 'Memory Limit'
            ),
            'max_execution_time' => array(
                'required' => 300,
                'current' => ini_get('max_execution_time'),
                'name' => 'Max Execution Time'
            )
        );

        foreach ($requirements as $key => $req) {
            $status = 'passed';
            /* translators: %1$s: requirement name, %2$s: current value, %3$s: required value */
            $message = sprintf(__('%1$s: %2$s (Required: %3$s)', 'vmpfence-security'), 
                $req['name'], $req['current'], $req['required']);

            switch ($key) {
                case 'php_version':
                case 'wp_version':
                    if (version_compare($req['current'], $req['required'], '<')) {
                        $status = 'failed';
                        $test['status'] = 'failed'; 
                        $test['recommendations'][] = sprintf(
                            /* translators: %1$s: component name, %2$s: required version */
                            __('Upgrade %1$s to %2$s or higher', 'vmpfence-security'),
                            $req['name'], $req['required']
                        );
                    }
                    break;

                case 'memory_limit':
                    $current_bytes = self::convert_to_bytes($req['current']);
                    $required_bytes = self::convert_to_bytes($req['required']);
                    if ($current_bytes < $required_bytes) {
                        $status = 'warning';
                        if ($test['status'] === 'passed') {
                            $test['status'] = 'warning';
                        }
                        $test['recommendations'][] = sprintf(
                            /* translators: %s: required memory limit */
                            __('Increase memory limit to %s or higher', 'vmpfence-security'),
                            $req['required']
                        );
                    }
                    break;

                case 'max_execution_time':
                    if ((int)$req['current'] > 0 && (int)$req['current'] < $req['required']) {
                        $status = 'warning';
                        if ($test['status'] === 'passed') {
                            $test['status'] = 'warning';
                        }
                        $test['recommendations'][] = sprintf(
                            /* translators: %d: required execution time in seconds */
                            __('Increase max execution time to %d seconds or higher', 'vmpfence-security'),
                            $req['required']
                        );
                    }
                    break;
            }

            $test['details'][$key] = array(
                'name' => $req['name'],
                'status' => $status,
                'current' => $req['current'],
                'required' => $req['required'],
                'message' => $message
            );
        }

        // Check required PHP extensions
        $required_extensions = array('curl', 'json', 'mbstring', 'openssl', 'zip');
        foreach ($required_extensions as $ext) {
            $loaded = extension_loaded($ext);
            $test['details']['ext_' . $ext] = array(
                /* translators: %s: PHP extension name */
                'name' => sprintf(__('PHP Extension: %s', 'vmpfence-security'), $ext),
                'status' => $loaded ? 'passed' : 'failed',
                'current' => $loaded ? __('Loaded', 'vmpfence-security') : __('Not loaded', 'vmpfence-security'),
                'required' => __('Required', 'vmpfence-security'),
                /* translators: %1$s: extension name, %2$s: status (Available/Missing) */
                'message' => sprintf(__('PHP Extension %1$s: %2$s', 'vmpfence-security'), 
                    $ext, $loaded ? __('Available', 'vmpfence-security') : __('Missing', 'vmpfence-security'))
            );

            if (!$loaded) {
                $test['status'] = 'failed';
                $test['recommendations'][] = sprintf(
                    /* translators: %s: PHP extension name */
                    __('Install PHP extension: %s', 'vmpfence-security'), $ext
                );
            }
        }

        if ($test['status'] !== 'passed') {
            $test['message'] = __('Some system requirements are not met', 'vmpfence-security');
        }

        return $test;
    }

    /**
     * Test database health
     *
     * @since 1.0.0
     * @return array
     */
    private static function test_database_health() {
        global $wpdb;

        $test = array(
            'name' => __('Database Health', 'vmpfence-security'),
            'status' => 'passed',
            'message' => __('Database is healthy', 'vmpfence-security'),
            'details' => array(),
            'recommendations' => array()
        );

        // Check database connection
        $connection_test = $wpdb->check_connection();
        $test['details']['connection'] = array(
            'name' => __('Database Connection', 'vmpfence-security'),
            'status' => $connection_test ? 'passed' : 'failed',
            'message' => $connection_test ? __('Connected', 'vmpfence-security') : __('Failed', 'vmpfence-security')
        );

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

        // Check VMPFence tables
        $tables_to_check = array(
            VMPFence_Constants::TABLE_SCANS,
            VMPFence_Constants::TABLE_THREATS,
            VMPFence_Constants::TABLE_AUDIT_LOG,
            VMPFence_Constants::TABLE_CONFIG,
            VMPFence_Constants::TABLE_BLOCKED_IPS
        );

        $missing_tables = array();
        foreach ($tables_to_check as $table) {
            $table_name = VMPFence_Constants::get_table_name($table);
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
            $exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
            
            $test['details']['table_' . $table] = array(
                /* translators: %s: database table name */
                'name' => sprintf(__('Table: %s', 'vmpfence-security'), $table),
                'status' => $exists ? 'passed' : 'failed',
                'message' => $exists ? __('Exists', 'vmpfence-security') : __('Missing', 'vmpfence-security')
            );

            if (!$exists) {
                $missing_tables[] = $table;
                $test['status'] = 'failed';
            }
        }

        if (!empty($missing_tables)) {
            $test['recommendations'][] = __('Reinstall or repair VMPFence database tables', 'vmpfence-security');
        }

        // Check database size and performance
        $total_size = 0;
        foreach ($tables_to_check as $table) {
            $table_name = VMPFence_Constants::get_table_name($table);
            // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
            $size = $wpdb->get_var("
                SELECT ROUND(((data_length + index_length) / 1024 / 1024), 2) 
                FROM information_schema.TABLES 
                WHERE table_schema = DATABASE() AND table_name = '$table_name'
            ");
            // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $total_size += (float)$size;
        }

        $test['details']['total_size'] = array(
            'name' => __('Total Database Size', 'vmpfence-security'),
            'status' => $total_size < 1000 ? 'passed' : 'warning',
            /* translators: %s: database size in MB */
            'message' => sprintf(__('%.2f MB', 'vmpfence-security'), $total_size)
        );

        if ($total_size > 1000) {
            if ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Consider database optimization or cleanup', 'vmpfence-security');
        }

        return $test;
    }

    /**
     * Test file permissions
     *
     * @since 1.0.0
     * @return array
     */
    private static function test_file_permissions() {
        $test = array(
            'name' => __('File Permissions', 'vmpfence-security'),
            'status' => 'passed',
            'message' => __('File permissions are correct', 'vmpfence-security'),
            'details' => array(),
            'recommendations' => array()
        );

        $paths_to_check = array(
            'wp_content' => array(
                'path' => WP_CONTENT_DIR,
                'required' => 0755,
                'type' => 'directory'
            ),
            'uploads' => array(
                'path' => wp_upload_dir()['basedir'],
                'required' => 0755,
                'type' => 'directory'
            ),
            'plugins' => array(
                'path' => WP_PLUGIN_DIR,
                'required' => 0755,
                'type' => 'directory'
            ),
            'vmpfence_plugin' => array(
                'path' => dirname(dirname(__FILE__)),
                'required' => 0755,
                'type' => 'directory'
            ),
            'wp_config' => array(
                'path' => ABSPATH . 'wp-config.php',
                'required' => 0644,
                'type' => 'file'
            )
        );

        foreach ($paths_to_check as $key => $check) {
            if (!file_exists($check['path'])) {
                $test['details'][$key] = array(
                    /* translators: %s: path type (e.g., "Uploads", "Config") */
                    'name' => sprintf(__('%s Path', 'vmpfence-security'), ucwords(str_replace('_', ' ', $key))),
                    'status' => 'failed',
                    'message' => __('Path does not exist', 'vmpfence-security'),
                    'path' => $check['path']
                );
                $test['status'] = 'failed';
                continue;
            }

            $current_perms = fileperms($check['path']) & 0777;
            $status = 'passed';
            /* translators: %o: file permissions in octal format */
            $message = sprintf(__('Permissions: %o', 'vmpfence-security'), $current_perms);

            // Check if permissions are too permissive
            if ($current_perms > $check['required']) {
                $status = 'warning';
                if ($test['status'] === 'passed') {
                    $test['status'] = 'warning';
                }
                $test['recommendations'][] = sprintf(
                    /* translators: %1$s: file path, %2$o: recommended permissions in octal format */
                    __('Reduce permissions for %1$s to %2$o', 'vmpfence-security'),
                    $check['path'], $check['required']
                );
            }

            // Check if we can read/write as needed
            if ($check['type'] === 'directory') {
                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable -- Checking filesystem permissions for diagnostics
                if (!is_readable($check['path']) || !is_writable($check['path'])) {
                    $status = 'failed';
                    $test['status'] = 'failed';
                    $test['recommendations'][] = sprintf(
                        /* translators: %s: directory path */
                        __('Fix read/write permissions for %s', 'vmpfence-security'),
                        $check['path']
                    );
                }
            } else {
                if (!is_readable($check['path'])) {
                    $status = 'failed';
                    $test['status'] = 'failed';
                    $test['recommendations'][] = sprintf(
                        /* translators: %s: file path */
                        __('Fix read permissions for %s', 'vmpfence-security'),
                        $check['path']
                    );
                }
            }

            $test['details'][$key] = array(
                /* translators: %s: path type (e.g., "Uploads", "Config") */
                'name' => sprintf(__('%s Path', 'vmpfence-security'), ucwords(str_replace('_', ' ', $key))),
                'status' => $status,
                'message' => $message,
                'path' => $check['path'],
                'current' => sprintf('%o', $current_perms),
                'required' => sprintf('%o', $check['required'])
            );
        }

        return $test;
    }

    /**
     * Test plugin configuration
     *
     * @since 1.0.0
     * @return array
     */
    private static function test_plugin_configuration() {
        $test = array(
            'name' => __('Plugin Configuration', 'vmpfence-security'),
            'status' => 'passed',
            'message' => __('Plugin is properly configured', 'vmpfence-security'),
            'details' => array(),
            'recommendations' => array()
        );

        // Check license status
        $license_valid = VMPFence_License::validate_license();
        $test['details']['license'] = array(
            'name' => __('License Status', 'vmpfence-security'),
            'status' => $license_valid ? 'passed' : 'warning',
            'message' => $license_valid ? __('Valid', 'vmpfence-security') : __('Invalid or expired', 'vmpfence-security')
        );

        if (!$license_valid) {
            if ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Activate or renew your license', 'vmpfence-security');
        }

        // Check critical settings
        $critical_settings = array(
            'waf_enabled' => __('WAF Protection', 'vmpfence-security'),
            'login_protection_enabled' => __('Login Protection', 'vmpfence-security'),
            'enable_audit_log' => __('Audit Logging', 'vmpfence-security')
        );

        foreach ($critical_settings as $setting => $name) {
            $enabled = VMPFence_Config::get($setting, false);
            $test['details'][$setting] = array(
                'name' => $name,
                'status' => $enabled ? 'passed' : 'warning',
                'message' => $enabled ? __('Enabled', 'vmpfence-security') : __('Disabled', 'vmpfence-security')
            );

            if (!$enabled) {
                if ($test['status'] === 'passed') {
                    $test['status'] = 'warning';
                }
                /* translators: %s: security setting name */
                $test['recommendations'][] = sprintf(__('Consider enabling %s', 'vmpfence-security'), $name);
            }
        }

        // Check scan schedule
        $scan_schedule = VMPFence_Config::get('scan_schedule', 'never');
        $test['details']['scan_schedule'] = array(
            'name' => __('Scan Schedule', 'vmpfence-security'),
            'status' => $scan_schedule !== 'never' ? 'passed' : 'warning',
            'message' => ucfirst($scan_schedule)
        );

        if ($scan_schedule === 'never') {
            if ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Configure automated security scans', 'vmpfence-security');
        }

        return $test;
    }

    /**
     * Test security status
     *
     * @since 1.0.0
     * @return array
     */
    private static function test_security_status() {
        global $wpdb;

        $test = array(
            'name' => __('Security Status', 'vmpfence-security'),
            'status' => 'passed',
            'message' => __('Security status is good', 'vmpfence-security'),
            'details' => array(),
            'recommendations' => array()
        );

        // Check for recent threats
        $threats_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_THREATS);
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
        $recent_threats = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $threats_table WHERE first_seen >= %d AND status != 'resolved'",
            time() - (7 * 86400)
        ));
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        $test['details']['recent_threats'] = array(
            'name' => __('Recent Threats (7 days)', 'vmpfence-security'),
            'status' => $recent_threats == 0 ? 'passed' : ($recent_threats < 10 ? 'warning' : 'failed'),
            /* translators: %d: number of threats detected */
            'message' => sprintf(__('%d threats detected', 'vmpfence-security'), $recent_threats)
        );

        if ($recent_threats > 0) {
            if ($recent_threats >= 10) {
                $test['status'] = 'failed';
            } elseif ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Review and address detected threats', 'vmpfence-security');
        }

        // Check failed login attempts
        $audit_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_AUDIT_LOG);
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
        $failed_logins = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $audit_table WHERE event_type = %s AND time >= %d",
            VMPFence_Constants::EVENT_LOGIN_FAILURE,
            time() - (24 * 3600)
        ));
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        $test['details']['failed_logins'] = array(
            'name' => __('Failed Logins (24 hours)', 'vmpfence-security'),
            'status' => $failed_logins < 20 ? 'passed' : ($failed_logins < 100 ? 'warning' : 'failed'),
            /* translators: %d: number of failed login attempts */
            'message' => sprintf(__('%d failed attempts', 'vmpfence-security'), $failed_logins)
        );

        if ($failed_logins >= 20) {
            if ($failed_logins >= 100) {
                $test['status'] = 'failed';
            } elseif ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Review login security settings and consider additional protection', 'vmpfence-security');
        }

        // Check last scan
        $scans_table = VMPFence_Constants::get_table_name(VMPFence_Constants::TABLE_SCANS);
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name properly escaped via VMPFence_Constants
        $last_scan = $wpdb->get_var("SELECT MAX(start_time) FROM $scans_table WHERE status = 'completed'");
        
        $days_since_scan = $last_scan ? floor((time() - $last_scan) / 86400) : 999;
        
        $test['details']['last_scan'] = array(
            'name' => __('Last Security Scan', 'vmpfence-security'),
            'status' => $days_since_scan <= 7 ? 'passed' : ($days_since_scan <= 30 ? 'warning' : 'failed'),
            'message' => $last_scan 
                /* translators: %d: number of days since last scan */
                ? sprintf(__('%d days ago', 'vmpfence-security'), $days_since_scan)
                : __('Never', 'vmpfence-security')
        );

        if ($days_since_scan > 7) {
            if ($days_since_scan > 30) {
                $test['status'] = 'failed';
            } elseif ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Run a security scan', 'vmpfence-security');
        }

        return $test;
    }

    /**
     * Test performance metrics
     *
     * @since 1.0.0
     * @return array
     */
    private static function test_performance_metrics() {
        $test = array(
            'name' => __('Performance Metrics', 'vmpfence-security'),
            'status' => 'passed',
            'message' => __('Performance is optimal', 'vmpfence-security'),
            'details' => array(),
            'recommendations' => array()
        );

        // Check memory usage
        $memory_usage = memory_get_usage(true);
        $memory_limit = self::convert_to_bytes(ini_get('memory_limit'));
        $memory_percent = ($memory_usage / $memory_limit) * 100;

        $test['details']['memory_usage'] = array(
            'name' => __('Memory Usage', 'vmpfence-security'),
            'status' => $memory_percent < 80 ? 'passed' : ($memory_percent < 95 ? 'warning' : 'failed'),
            /* translators: %1$.1f: memory percentage, %2$s: current memory usage, %3$s: memory limit */
            'message' => sprintf(__('%1$.1f%% (%2$s / %3$s)', 'vmpfence-security'), 
                $memory_percent, 
                size_format($memory_usage), 
                size_format($memory_limit)
            )
        );

        if ($memory_percent >= 80) {
            if ($memory_percent >= 95) {
                $test['status'] = 'failed';
            } elseif ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Consider increasing memory limit or optimizing memory usage', 'vmpfence-security');
        }

        // Check cache efficiency
        $cache_hits = VMPFence_Config::get('cache_hits', 0);
        $cache_misses = VMPFence_Config::get('cache_misses', 0);
        $cache_total = $cache_hits + $cache_misses;
        $cache_efficiency = $cache_total > 0 ? ($cache_hits / $cache_total) * 100 : 0;

        $test['details']['cache_efficiency'] = array(
            'name' => __('Cache Efficiency', 'vmpfence-security'),
            'status' => $cache_efficiency > 80 ? 'passed' : ($cache_efficiency > 60 ? 'warning' : 'failed'),
            /* translators: %1$.1f: cache efficiency percentage, %2$d: cache hits, %3$d: cache misses */
            'message' => sprintf(__('%1$.1f%% (%2$d hits, %3$d misses)', 'vmpfence-security'), 
                $cache_efficiency, $cache_hits, $cache_misses)
        );

        if ($cache_total > 100 && $cache_efficiency < 80) {
            if ($cache_efficiency < 60) {
                $test['status'] = 'failed';
            } elseif ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Optimize caching configuration', 'vmpfence-security');
        }

        return $test;
    }

    /**
     * Test network connectivity
     *
     * @since 1.0.0
     * @return array
     */
    private static function test_network_connectivity() {
        $test = array(
            'name' => __('Network Connectivity', 'vmpfence-security'),
            'status' => 'passed',
            'message' => __('Network connectivity is good', 'vmpfence-security'),
            'details' => array(),
            'recommendations' => array()
        );

        // Test external API connectivity
        $api_endpoints = array(
            'vmpfence_api' => 'https://api.vmpfence.com/v1/status',
            'threat_intelligence' => 'https://feeds.vmpfence.com/threats'
        );

        foreach ($api_endpoints as $name => $url) {
            $response = wp_remote_get($url, array('timeout' => 10));
            $status = !is_wp_error($response) && wp_remote_retrieve_response_code($response) == 200 
                ? 'passed' : 'warning';

            $test['details'][$name] = array(
                /* translators: %s: API service name (e.g., "Reputation", "Malware") */
                'name' => sprintf(__('%s API', 'vmpfence-security'), ucwords(str_replace('_', ' ', $name))),
                'status' => $status,
                'message' => $status === 'passed' ? __('Connected', 'vmpfence-security') : __('Connection failed', 'vmpfence-security'),
                'url' => $url
            );

            if ($status === 'warning' && $test['status'] === 'passed') {
                $test['status'] = 'warning';
                $test['recommendations'][] = sprintf(
                    /* translators: %s: API URL */
                    __('Check network connectivity to %s', 'vmpfence-security'), $url
                );
            }
        }

        return $test;
    }

    /**
     * Test WordPress environment
     *
     * @since 1.0.0
     * @return array
     */
    private static function test_wp_environment() {
        $test = array(
            'name' => __('WordPress Environment', 'vmpfence-security'),
            'status' => 'passed',
            'message' => __('WordPress environment is properly configured', 'vmpfence-security'),
            'details' => array(),
            'recommendations' => array()
        );

        // Check WordPress debug mode
        $debug_enabled = defined('WP_DEBUG') && WP_DEBUG;
        $test['details']['wp_debug'] = array(
            'name' => __('WordPress Debug Mode', 'vmpfence-security'),
            'status' => !$debug_enabled ? 'passed' : 'warning',
            'message' => $debug_enabled ? __('Enabled', 'vmpfence-security') : __('Disabled', 'vmpfence-security')
        );

        if ($debug_enabled) {
            if ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Disable WP_DEBUG in production', 'vmpfence-security');
        }

        // Check file editing
        $file_edit_disabled = defined('DISALLOW_FILE_EDIT') && DISALLOW_FILE_EDIT;
        $test['details']['file_edit'] = array(
            'name' => __('File Editing', 'vmpfence-security'),
            'status' => $file_edit_disabled ? 'passed' : 'warning',
            'message' => $file_edit_disabled ? __('Disabled', 'vmpfence-security') : __('Enabled', 'vmpfence-security')
        );

        if (!$file_edit_disabled) {
            if ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Disable file editing by adding DISALLOW_FILE_EDIT to wp-config.php', 'vmpfence-security');
        }

        // Check automatic updates
        $auto_updates_disabled = defined('AUTOMATIC_UPDATER_DISABLED') && AUTOMATIC_UPDATER_DISABLED;
        $test['details']['auto_updates'] = array(
            'name' => __('Automatic Updates', 'vmpfence-security'),
            'status' => !$auto_updates_disabled ? 'passed' : 'warning',
            'message' => $auto_updates_disabled ? __('Disabled', 'vmpfence-security') : __('Enabled', 'vmpfence-security')
        );

        if ($auto_updates_disabled) {
            if ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Consider enabling automatic updates for security', 'vmpfence-security');
        }

        // Check SSL
        $is_ssl = is_ssl();
        $test['details']['ssl'] = array(
            'name' => __('SSL/HTTPS', 'vmpfence-security'),
            'status' => $is_ssl ? 'passed' : 'warning',
            'message' => $is_ssl ? __('Enabled', 'vmpfence-security') : __('Not enabled', 'vmpfence-security')
        );

        if (!$is_ssl) {
            if ($test['status'] === 'passed') {
                $test['status'] = 'warning';
            }
            $test['recommendations'][] = __('Enable SSL/HTTPS for security', 'vmpfence-security');
        }

        return $test;
    }

    /**
     * Generate diagnostic report
     *
     * @since 1.0.0
     * @param array $results Diagnostic results
     * @return string
     */
    public static function generate_report($results) {
        $report = array();
        
        $report[] = "=== VMPFence Diagnostic Report ===";
        $report[] = "Generated: " . date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $results['timestamp']);
        $report[] = "Overall Status: " . strtoupper($results['overall_status']);
        $report[] = "";
        
        $report[] = "=== Summary ===";
        $report[] = sprintf("Total Tests: %d", $results['summary']['total_tests']);
        $report[] = sprintf("Passed: %d", $results['summary']['passed']);
        $report[] = sprintf("Warnings: %d", $results['summary']['warnings']);
        $report[] = sprintf("Failed: %d", $results['summary']['failed']);
        $report[] = "";

        foreach ($results['tests'] as $test_name => $test) {
            $report[] = sprintf("=== %s ===", $test['name']);
            $report[] = sprintf("Status: %s", strtoupper($test['status']));
            $report[] = sprintf("Message: %s", $test['message']);
            $report[] = "";

            if (!empty($test['details'])) {
                $report[] = "Details:";
                foreach ($test['details'] as $detail) {
                    $report[] = sprintf("  - %s: %s (%s)", 
                        $detail['name'], 
                        $detail['message'], 
                        strtoupper($detail['status'])
                    );
                }
                $report[] = "";
            }

            if (!empty($test['recommendations'])) {
                $report[] = "Recommendations:";
                foreach ($test['recommendations'] as $rec) {
                    $report[] = "  - " . $rec;
                }
                $report[] = "";
            }
        }

        if (!empty($results['recommendations'])) {
            $report[] = "=== Overall Recommendations ===";
            foreach ($results['recommendations'] as $rec) {
                $report[] = "- " . $rec;
            }
            $report[] = "";
        }

        return implode("\n", $report);
    }

    /**
     * Export diagnostic results
     *
     * @since 1.0.0
     * @param array $results Diagnostic results
     * @param string $format Export format
     * @return string File path
     */
    public static function export_results($results, $format = 'json') {
        $filename = 'vmpfence-diagnostic-' . gmdate('Y-m-d-H-i-s') . '.' . $format;
        
        switch ($format) {
            case 'txt':
                $content = self::generate_report($results);
                break;
            case 'json':
                $content = wp_json_encode($results, JSON_PRETTY_PRINT);
                break;
            default:
                $content = serialize($results);
        }

        $upload_dir = wp_upload_dir();
        $filepath = $upload_dir['path'] . '/' . $filename;
        
        file_put_contents($filepath, $content);
        
        return $filepath;
    }

    /**
     * Fix common issues automatically
     *
     * @since 1.0.0
     * @param array $issues Issues to fix
     * @return array
     */
    public static function auto_fix_issues($issues) {
        $results = array(
            'fixed' => array(),
            'failed' => array(),
            'skipped' => array()
        );

        foreach ($issues as $issue) {
            $method = 'fix_' . $issue;
            if (method_exists(__CLASS__, $method)) {
                try {
                    $result = self::$method();
                    if ($result) {
                        $results['fixed'][] = $issue;
                    } else {
                        $results['failed'][] = $issue;
                    }
                } catch (Exception $e) {
                    $results['failed'][] = $issue;
                }
            } else {
                $results['skipped'][] = $issue;
            }
        }

        return $results;
    }

    /**
     * Helper methods
     */
    
    private static function convert_to_bytes($value) {
        $value = trim($value);
        $last = strtolower($value[strlen($value) - 1]);
        $number = (int)$value;
        
        switch ($last) {
            case 'g':
                $number *= 1024 * 1024 * 1024;
                break;
            case 'm':
                $number *= 1024 * 1024;
                break;
            case 'k':
                $number *= 1024;
                break;
        }
        
        return $number;
    }

    private static function fix_database_tables() {
        $database = new VMPFence_Database();
        return $database->create_tables();
    }

    private static function fix_cache_configuration() {
        VMPFence_Config::set('cache_enabled', true);
        VMPFence_Config::set('cache_duration', 3600);
        return true;
    }

    private static function fix_scan_schedule() {
        VMPFence_Config::set('scan_schedule', 'daily');
        VMPFence_Config::set('scan_time', '02:00');
        return true;
    }
}
