<?php
error_reporting(0);

class RequestProcessor {
    private $entropy;
    private $fingerprint;
    private $headers = [];
    private $browser_signatures = [
        'chrome' => ['Chrome/', 'CriOS/'],
        'firefox' => ['Firefox/', 'FxiOS/'],
        'safari' => ['Safari/', 'AppleWebKit/'],
        'edge' => ['Edge/', 'Edg/'],
        'opera' => ['OPR/', 'Opera/']
    ];
    
    private $legitimate_patterns = [
        'accept' => [
            'text/html', 'application/xhtml+xml', 'application/xml',
            'image/webp', 'image/apng', '*/*'
        ],
        'accept_language' => ['en-US', 'en-GB', 'en', 'de', 'fr', 'es'],
        'accept_encoding' => ['gzip', 'deflate', 'br']
    ];

    private $canvas_fingerprints = [];
    private $mouse_movements = 0;
    private $keyboard_events = 0;
    private $webgl_data = '';
    private $screen_metrics = [];

    public function __construct() {
        $this->entropy = random_bytes(32);
        $this->initializeHeaders();
        $this->generateFingerprint();
    }

    private function initializeHeaders() {
        $headers = getallheaders();
        array_walk($headers, function($value, $key) {
            $this->headers[strtolower($key)] = $value;
        });
    }

    private function generateFingerprint() {
        $components = [
            $this->headers['user-agent'] ?? '',
            $this->headers['accept-language'] ?? '',
            $this->headers['accept'] ?? '',
            $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '',
            $_SERVER['REMOTE_ADDR'],
            $_SERVER['HTTP_SEC_CH_UA'] ?? ''
        ];
        $this->fingerprint = hash('sha256', implode('|', $components));
    }

    private function validateBrowserProfile(): bool {
        // Check for consistent browser signatures
        $ua = $this->headers['user-agent'] ?? '';
        $detected = false;
        
        foreach ($this->browser_signatures as $browser => $sigs) {
            foreach ($sigs as $sig) {
                if (strpos($ua, $sig) !== false) {
                    $detected = true;
                    // Verify corresponding headers match browser profile
                    if ($browser === 'chrome' && !strpos($ua, 'Chrome/')) {
                        return false;
                    }
                }
            }
        }
        
        return $detected;
    }

    private function validateHeaders(): bool {
        // Check Accept header contains valid MIME types
        $accept = $this->headers['accept'] ?? '';
        $valid_mime = false;
        foreach ($this->legitimate_patterns['accept'] as $mime) {
            if (strpos($accept, $mime) !== false) {
                $valid_mime = true;
                break;
            }
        }
        if (!$valid_mime) return false;

        // Validate Accept-Language format
        $accept_lang = $this->headers['accept-language'] ?? '';
        if (!preg_match('/^[a-zA-Z\-,;=\d\s\.]+$/', $accept_lang)) {
            return false;
        }

        return true;
    }

    private function validateTiming(): bool {
        // Check for natural timing patterns
        $timing = isset($_SERVER['REQUEST_TIME_FLOAT']) ? 
                 (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) : 0;
        
        // Most bots are either too fast or too slow
        if ($timing < 0.1 || $timing > 30) {
            return false;
        }

        return true;
    }

    private function generateChallengeResponse(): string {
        return base64_encode(hash_hmac('sha256', $this->fingerprint, $this->entropy, true));
    }

    private function validateJavaScript(): bool {
        if (isset($_POST['challenge_response'])) {
            $expected = $this->generateChallengeResponse();
            return hash_equals($expected, $_POST['challenge_response']);
        }
        return false;
    }

    public function process() {
        // Initialize session with secure parameters
        ini_set('session.use_strict_mode', 1);
        ini_set('session.use_only_cookies', 1);
        session_start(['cookie_httponly' => true, 'cookie_samesite' => 'Strict']);

        // Check if already validated
        if (isset($_SESSION['browser_validated']) && $_SESSION['browser_validated'] === true) {
            $this->handleRequest();
            return;
        }

        // Multi-layered validation
        if (!$this->validateBrowserProfile() || 
            !$this->validateHeaders() || 
            !$this->validateTiming()) {
            
            // Handle the challenge response
            if (isset($_POST['challenge_response']) && isset($_POST['fingerprints'])) {
                if ($this->validateJavaScript() && $this->validateFingerprints($_POST['fingerprints'])) {
                    $_SESSION['browser_validated'] = true;
                    $_SESSION['fingerprint'] = $this->fingerprint;
                    $this->handleRequest();
                    return;
                }
            }
            
            // First time or failed validation - serve the challenge
            $this->serveChallenge();
            return;
        }

        // If we get here, basic validation passed
        $_SESSION['browser_validated'] = true;
        $_SESSION['fingerprint'] = $this->fingerprint;
        $this->handleRequest();
    }

    private function serveChallenge() {
        header('Content-Type: text/html; charset=UTF-8');
        // Serve an invisible challenge page instead of showing error
        echo $this->generateChallengePage();
    }

    private function generateChallengePage(): string {
        $challenge = $this->generateChallengeResponse();
        return <<<HTML
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <script>
                (function() {
                    let hasValidated = false;
                    let interactionOccurred = false;

                    function getFingerprints() {
                        return {
                            screen: getScreenMetrics(),
                            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
                            languages: navigator.languages?.join(','),
                            plugins: Array.from(navigator.plugins).map(p => p.name).join(',')
                        };
                    }

                    // Simplified screen metrics - always available
                    function getScreenMetrics() {
                        return {
                            width: window.screen.width,
                            height: window.screen.height,
                            depth: window.screen.colorDepth,
                            ratio: window.devicePixelRatio,
                            orientation: window.screen.orientation?.type
                        };
                    }

                    const validateBrowser = () => {
                        if (hasValidated) return;
                        hasValidated = true;
                        
                        const response = '$challenge';
                        const fingerprints = getFingerprints();

                        fetch(window.location.href, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: 'challenge_response=' + response + '&fingerprints=' + 
                                  encodeURIComponent(JSON.stringify(fingerprints))
                        })
                        .then(response => {
                            if (!response.ok) {
                                // Redirect away
                                window.location.href = "https://href.li/?https://support.google.com";
                            }else{
                                // Browser is valid
                                console.log('Valid Browser');
                            }
                        })
                        .catch(() => {});
                    };

                    // Start validation after a short delay
                    setTimeout(validateBrowser, 100);
                })();
            </script>
        </head>
        <body style="background:#fff;">
            <noscript>Please enable JavaScript to continue.</noscript>
        </body>
        </html>
        HTML;
    }

    private function handleRequest() {
        // Your original request handling code here
        // This will only execute for validated requests
    }

    private function isMobileDevice(): bool {
        $ua = $this->headers['user-agent'] ?? '';
        return preg_match('/(android|iphone|ipad|mobile|phone)/i', $ua);
    }

    private function validateFingerprints($data): bool {
        if (!$data) return false;
        
        $fingerprints = json_decode($data, true);
        if (!$fingerprints) return false;
        
        $isMobile = $this->isMobileDevice();

        // Validate screen metrics with mobile considerations
        $screen = $fingerprints['screen'];
        if ($isMobile) {
            if ($screen['width'] < 240 || $screen['height'] < 320 || 
                !$screen['depth'] || !$screen['ratio']) {
                return false;
            }
        } else {
            if ($screen['width'] < 320 || $screen['height'] < 240 || 
                !$screen['depth'] || !$screen['ratio']) {
                return false;
            }
        }

        // Validate timezone (same for both)
        if (!preg_match('/^[A-Za-z]+\/[A-Za-z_]+$/', $fingerprints['timezone'])) {
            return false;
        }

        return true;
    }
}

// Execute
$processor = new RequestProcessor();
$processor->process();

?>