<?php
session_start();
$secret = "6LdpAvArAAAAACf8aW-yRjqso92elDzcd8oPB7r8"; // Secret key
$sitekey = "6LdpAvArAAAAADJ-O7v7KHgVKx0tBp1psi0tCKXE"; // Site key 
$logFile = __DIR__ . "/visits.log"; 

function logVisit($status, $ip, $logFile) {
    $time = date("Y-m-d H:i:s");
    $line = "[$time] IP: $ip | Status: $status" . PHP_EOL;
    file_put_contents($logFile, $line, FILE_APPEND);
}

// Original reCAPTCHA verification logic
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $recaptcha = $_POST['g-recaptcha-response'] ?? '';
    
    if (empty($recaptcha)) {
        $error = "Please complete the CAPTCHA.";
        logVisit("❌ CAPTCHA not completed", $_SERVER['REMOTE_ADDR'], $logFile);
    } else {
        $url = "https://www.google.com/recaptcha/api/siteverify";
        $data = [
            'secret' => $secret,
            'response' => $recaptcha,
            '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($url, false, $context);
        $resultJson = json_decode($result);
        
        if ($resultJson->success) {
            $_SESSION["verified"] = true;
            logVisit("✅ CAPTCHA verified successfully", $_SERVER['REMOTE_ADDR'], $logFile);
            header("Location: index.php");
            exit();
        } else {
            $error = "CAPTCHA verification failed. Please try again.";
            logVisit("❌ CAPTCHA verification failed", $_SERVER['REMOTE_ADDR'], $logFile);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Verification...</title>
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  <style>
    body {
      text-align: center;
      margin-top: 100px;
      font-family: Arial, sans-serif;
      background-color: #f9f9f9;
    }

    button {
      background-color: #0052cc;
      color: white;
      padding: 12px 28px;
      border: none;
      border-radius: 8px;
      font-size: 16px;
      cursor: pointer;
      transition: background-color 0.3s ease, transform 0.2s ease;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }

    button:hover {
      background-color: #003d99;
      transform: scale(1.03);
    }

    .g-recaptcha {
      display: inline-block;
    }
  </style>
</head>
<body>
  <h2>Please verify that you are not a robot</h2>
  <?php if (!empty($error)) echo "<p style='color:red;'>$error</p>"; ?>
  <form method="POST">
    <div class="g-recaptcha" data-sitekey="6LdpAvArAAAAADJ-O7v7KHgVKx0tBp1psi0tCKXE"></div>
    <br><br>
    <button type="submit">Continue</button>
  </form>
</body>
</html>