<?php
// reCAPTCHA v3 secret key
$recaptcha_secret = "YOUR_RECAPTCHA_SECRET_KEY";

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    print "<pre>";
    print_r($_POST);
    exit;
    // Verify reCAPTCHA v3
    $recaptcha_response = $_POST['g-recaptcha-response'];
    $verify_url = "https://www.google.com/recaptcha/api/siteverify";
    $verify_data = [
        'secret' => $recaptcha_secret,
        'response' => $recaptcha_response,
        'remoteip' => $_SERVER['REMOTE_ADDR']
    ];

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

    $context = stream_context_create($options);
    $verify_response = file_get_contents($verify_url, false, $context);
    $response_data = json_decode($verify_response);

    // Check if score is above 0.5 (you can adjust this threshold)
    if ($response_data->success && $response_data->score >= 0.5) {
        // Get form data
        $name = strip_tags(trim($_POST["name"]));
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $subject = strip_tags(trim($_POST["subject"]));
        $message = strip_tags(trim($_POST["message"]));

        // Recipient email
        $to = "Info@birlonengineering.com";

        // Email headers
        $email_headers = "From: $name <$email>";

        // Email content
        $email_content = "Name: $name\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "Subject: $subject\n\n";
        $email_content .= "Message:\n$message\n";

        // Send email
        if (mail($to, "Contact Form: $subject", $email_content, $email_headers)) {
            $response = ['status' => 'success', 'message' => 'Thank you! Your message has been sent.'];
        } else {
            $response = ['status' => 'error', 'message' => 'Oops! Something went wrong, please try again.'];
        }
    } else {
        $response = ['status' => 'error', 'message' => 'Please complete the reCAPTCHA verification.'];
    }
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}
?>
