<?php
require_once __DIR__ . '/includes/mail-helper.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    gx_json(false, 'Invalid request method.');
}

// ---- Collect + basic validate fields ----
$firstName = $_POST['first_name'] ?? '';
$lastName  = $_POST['last_name']  ?? '';
$email     = $_POST['email']      ?? '';
$phone     = $_POST['phone']      ?? '';
$country   = $_POST['country']    ?? '';
$interest  = $_POST['interest']   ?? '';
$message   = $_POST['message']    ?? '';
$recaptchaToken = $_POST['g-recaptcha-response'] ?? '';

if (trim($firstName) === '' || trim($lastName) === '') {
    gx_json(false, 'Please enter your first and last name.');
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    gx_json(false, 'Please enter a valid email address.');
}

// ---- reCAPTCHA ----
if (!gx_verify_recaptcha($recaptchaToken)) {
    gx_json(false, 'reCAPTCHA verification failed. Please try again.');
}

// ---- Build + send email ----
$subject = 'New Contact Form Submission — ' . $firstName . ' ' . $lastName;
$body = '
<table style="font-family: Arial, sans-serif; font-size:14px; color:#111;" cellpadding="6">
  <tr><td><b>First Name</b></td><td>' . gx_e($firstName) . '</td></tr>
  <tr><td><b>Last Name</b></td><td>' . gx_e($lastName) . '</td></tr>
  <tr><td><b>Email</b></td><td>' . gx_e($email) . '</td></tr>
  <tr><td><b>Phone</b></td><td>' . gx_e($phone) . '</td></tr>
  <tr><td><b>Country</b></td><td>' . gx_e($country) . '</td></tr>
  <tr><td><b>Interested In</b></td><td>' . gx_e($interest) . '</td></tr>
  <tr><td><b>Description</b></td><td>' . nl2br(gx_e($message)) . '</td></tr>
</table>';

$sent = gx_send_mail(GX_CONTACT_TO_EMAIL, $subject, $body, $email, $firstName . ' ' . $lastName);

if ($sent) {
    gx_json(true, 'Thanks — your message has been sent. Our team will be in touch shortly.');
} else {
    gx_json(false, 'Something went wrong while sending your message. Please try again later.');
}
