<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $secretKey = '0x4AAAAAAAfzrZTwiOl4nj_BPeAt3ngqJSA'; // Replace with your actual secret key
    $token = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_STRING);
    $remoteIp = getClientIp();

    if (empty($token)) {
        sendJsonResponse(400, ['success' => false, 'error' => 'Token is missing']);
        exit;
    }

    $url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
    $data = [
        'secret' => $secretKey,
        'response' => $token,
        'remoteip' => $remoteIp
    ];

    $response = makeCurlRequest($url, $data);

    if ($response === false) {
        sendJsonResponse(500, ['success' => false, 'error' => 'Verification request failed']);
        exit;
    }

    $decodedResponse = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        sendJsonResponse(500, ['success' => false, 'error' => 'Invalid response from verification server']);
        exit;
    }

    sendJsonResponse(200, $decodedResponse);
}

function getClientIp() {
    $ipKeys = [
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'REMOTE_ADDR'
    ];

    foreach ($ipKeys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = explode(',', $_SERVER[$key]);
            $ip = trim(end($ip)); // Return the last IP address in the list (most reliable)

            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }

    return 'UNKNOWN'; // Default to UNKNOWN if no valid IP found
}

function makeCurlRequest(string $url, array $data)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);

    $result = curl_exec($ch);

    if (curl_errno($ch)) {
        error_log('cURL error: ' . curl_error($ch));
        curl_close($ch);
        return false;
    }

    curl_close($ch);
    return $result;
}

function sendJsonResponse(int $statusCode, array $data)
{
    http_response_code($statusCode);
    header('Content-Type: application/json');
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: DENY');
    echo json_encode($data);
}

?>
