<?php
/**
 * Shared helpers used by all form handlers:
 *  - gx_verify_recaptcha(): validates the g-recaptcha-response token with Google
 *  - gx_send_mail():        sends an HTML email via SMTP (Amazon SES) using PHPMailer
 *  - gx_json():             sends a JSON response and stops execution
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../vendor/phpmailer/src/Exception.php';
require_once __DIR__ . '/../vendor/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/../vendor/phpmailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as PHPMailerException;

/**
 * Send a JSON response and stop script execution.
 */
function gx_json($success, $message, $extra = [])
{
    header('Content-Type: application/json');
    echo json_encode(array_merge(['success' => $success, 'message' => $message], $extra));
    exit;
}

/**
 * Verify the reCAPTCHA token sent from the browser against Google's siteverify API.
 * Returns true on success, false otherwise.
 */
function gx_verify_recaptcha($token)
{
    if (empty($token)) {
        return false;
    }

    $ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'secret'   => GX_RECAPTCHA_SECRET_KEY,
        'response' => $token,
        'remoteip' => $_SERVER['REMOTE_ADDR'] ?? '',
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        error_log('reCAPTCHA verify cURL error: ' . $curlError);
        return false;
    }

    $result = json_decode($response, true);
    return !empty($result['success']);
}

/**
 * Send an HTML email via SMTP using PHPMailer.
 *
 * @param string $toEmail    Recipient address
 * @param string $subject    Email subject
 * @param string $htmlBody   HTML body
 * @param string $replyToEmail Optional — sets Reply-To so admin can hit "reply" and reach the form submitter
 * @param string $replyToName  Optional
 * @return bool true on success, false on failure
 */
function gx_send_mail($toEmail, $subject, $htmlBody, $replyToEmail = '', $replyToName = '')
{
    $mail = new PHPMailer(true);
    try {
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host       = GX_SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = GX_SMTP_USERNAME;
        $mail->Password   = GX_SMTP_PASSWORD;
        $mail->SMTPSecure = GX_SMTP_SECURE === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = GX_SMTP_PORT;

        $mail->setFrom(GX_MAIL_FROM_EMAIL, GX_MAIL_FROM_NAME);
        $mail->addAddress($toEmail);

        if (!empty($replyToEmail) && filter_var($replyToEmail, FILTER_VALIDATE_EMAIL)) {
            $mail->addReplyTo($replyToEmail, $replyToName ?: $replyToEmail);
        }

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;

        $mail->send();
        return true;
    } catch (PHPMailerException $e) {
        error_log('Mail send failed: ' . $mail->ErrorInfo);
        return false;
    }
}

/**
 * Basic sanitizer for values dropped into the HTML email body.
 */
function gx_e($value)
{
    return htmlspecialchars(trim((string) $value), ENT_QUOTES, 'UTF-8');
}
