<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $captcha_response = $_POST["cf-turnstile-response"] ?? '';

    if (!$captcha_response) {
        $_SESSION['captcha_error'] = "CAPTCHA verification failed. Please try again.";
        header("Location: index.php");
        exit();
    }

    $secretKey = "0x4AAAAAACNarQTvzSfPxKCbRreFTvoBfwI";
    $verifyURL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
    
    $data = [
        'secret' => $secretKey,
        'response' => $captcha_response
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded",
            'method'  => 'POST',
            'content' => http_build_query($data)
        ]
    ];
    
    $context  = stream_context_create($options);
    $result = file_get_contents($verifyURL, false, $context);
    $verification = json_decode($result, true);

    if ($verification["success"]) {
        $_SESSION['captcha_valid'] = true; // Store success in session
        header("Location: /"); // Redirect to home page
        exit();
    } else {
        $_SESSION['captcha_error'] = "CAPTCHA verification failed. Please try again.";
        header("Location: index.php");
        exit();
    }
}
?>
