<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');

$cfg = @include __DIR__ . '/config.php';
$secret = (is_array($cfg) && isset($cfg['recaptcha_secret'])) ? $cfg['recaptcha_secret'] : null;

$env = [
  'php_version' => PHP_VERSION,
  'curl' => function_exists('curl_init') ? 'enabled' : 'missing',
  'allow_url_fopen' => ini_get('allow_url_fopen') ? '1' : '0',
  'host' => $_SERVER['HTTP_HOST'] ?? null,
  'remote_addr' => $_SERVER['REMOTE_ADDR'] ?? null,
];

// Perform a quick siteverify check with a guaranteed-invalid token.
// If the secret is valid, Google should respond with 'invalid-input-response' (not invalid secret).
$result = null;
$errors = null;
try {
  if ($secret) {
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $post = http_build_query(['secret'=>$secret, 'response'=>'invalid-token-test', 'remoteip'=>($_SERVER['REMOTE_ADDR'] ?? '')], '', '&');
    $response = null;
    $error = null;
    if (function_exists('curl_init')) {
      $ch = curl_init($url);
      curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $post,
        CURLOPT_USERAGENT      => 'Mozilla/5.0',
        CURLOPT_SSL_VERIFYPEER => true,
      ]);
      $response = curl_exec($ch);
      if ($response === false) { $error = curl_error($ch); }
      curl_close($ch);
    } else {
      $ctx = stream_context_create([
        'http' => ['method'=>'POST', 'header'=>"Content-Type: application/x-www-form-urlencoded\r\n", 'content'=>$post, 'timeout'=>10],
        'ssl'  => ['verify_peer'=>true, 'verify_peer_name'=>true]
      ]);
      $response = @file_get_contents($url, false, $ctx);
      if ($response === false) { $error = 'file_get_contents failed'; }
    }
    $json = $response ? json_decode($response, true) : null;
    $result = $json;
    $errors = $json['error-codes'] ?? ($error ? [$error] : []);
  }
} catch (Throwable $e) {
  $errors = [$e->getMessage()];
}

echo json_encode(['env'=>$env, 'secret_present' => (bool)$secret, 'siteverify'=>$result, 'errors'=>$errors], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
