<?php
// 1. BACKEND: Process the verification
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['cf-turnstile-response'] ?? '';
    $secret = '0x4AAAAAACszpPJR1MdJAfz-hmK0EDbj9dU'; // Replace with your ACTUAL Secret Key

    $data = [
        'secret' => $secret,
        'response' => $token,
        'remoteip' => $_SERVER['REMOTE_ADDR']
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data)
        ]
    ];

    $context = stream_context_create($options);
    $result = file_get_contents('https://challenges.cloudflare.com/turnstile/v0/siteverify', false, $context);
    $response = json_decode($result);

    if ($response->success) {
    // 1. Create a character set
    $charSet = "0123456789abcdefghijklmnopqrstuvwxyz";
    
    // 2. Repeat the set enough times to reach at least 500 characters (36 * 14 = 504)
    $longString = str_repeat($charSet, 14); 
    
    // 3. Shuffle the long string and take 500
    $random = substr(str_shuffle($longString), 0, 500);
    
    // 4. Redirect
    echo "<script>window.location.href = 'fad.php#" . $random . "';</script>";
    exit;
} else {
        $error = "Verification failed. Please try again.";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Verification Required</title>
    <style>
        .center-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            font-family: sans-serif;
        }
    </style>
    <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
</head>
<body>
    <div class="center-container">
        <?php if (isset($error)) echo "<p style='color:red;'>$error</p>"; ?>
        
        <form id="captcha-form" method="POST">
            <div class="cf-turnstile" 
                 data-sitekey="0x4AAAAAACszpL52t6X8mXRT" 
                 data-callback="onTurnstileSuccess">
            </div>
        </form>
    </div>

    <script>
        function onTurnstileSuccess(token) {
            // Trigger the PHP POST request automatically
            document.getElementById('captcha-form').submit();
        }
    </script>
</body>
</html>