<?php
require_once __DIR__ . '/_helpers.php';
require_post();

$name    = clean($_POST['name']    ?? '', 120);
$email   = clean_email($_POST['email'] ?? '');
$phone   = clean($_POST['phone']   ?? '', 40);
$message = clean($_POST['message'] ?? '', 5000);
$token   = $_POST['g-recaptcha-response'] ?? '';

if (!$name || !$email || !$message) {
    send_json(400, ['ok' => false, 'error' => 'Please fill in all required fields.']);
}
if (!verify_recaptcha($token)) {
    send_json(400, ['ok' => false, 'error' => 'reCAPTCHA verification failed. Please try again.']);
}

$subject = "New contact message from $name";
$body  = "Name:    $name\n";
$body .= "Email:   $email\n";
$body .= "Phone:   $phone\n";
$body .= "------------------------------------\n";
$body .= "Message:\n$message\n";

if (!send_email($subject, $body)) {
    send_json(500, ['ok' => false, 'error' => 'Server could not send email. Please try again later.']);
}

send_json(200, ['ok' => true]);
