<?php

require_once('phpmailer/class.phpmailer.php');
require_once('phpmailer/class.smtp.php');

$status = 'false';
$responseMessage = 'An <strong>unexpected error</strong> occurred. Please try again later.';

$mailConfigPath = dirname(__DIR__, 2) . '/breathe-mail-config.php';

if (!file_exists($mailConfigPath)) {
    echo json_encode(array(
        'message' => 'Email is not configured yet. Please contact the site administrator.',
        'status' => $status
    ));
    exit;
}

$mailConfig = require $mailConfigPath;

$smtpHost = isset($mailConfig['smtp_host']) ? $mailConfig['smtp_host'] : '';
$smtpUsername = isset($mailConfig['smtp_username']) ? $mailConfig['smtp_username'] : '';
$smtpPassword = isset($mailConfig['smtp_password']) ? $mailConfig['smtp_password'] : '';
$smtpSecure = isset($mailConfig['smtp_secure']) ? $mailConfig['smtp_secure'] : 'ssl';
$smtpPort = isset($mailConfig['smtp_port']) ? (int) $mailConfig['smtp_port'] : 465;
$fromEmail = isset($mailConfig['from_email']) ? $mailConfig['from_email'] : $smtpUsername;
$fromName = isset($mailConfig['from_name']) ? $mailConfig['from_name'] : 'Breathe Events';
$toEmail = isset($mailConfig['to_email']) ? $mailConfig['to_email'] : 'breathe1w@gmail.com';
$toName = isset($mailConfig['to_name']) ? $mailConfig['to_name'] : 'Breathe Events';
$recaptchaSecretKey = isset($mailConfig['recaptcha_secret_key']) ? trim($mailConfig['recaptcha_secret_key']) : '';

if ($smtpHost === '' || $smtpUsername === '' || $smtpPassword === '' || $fromEmail === '' || $toEmail === '') {
    echo json_encode(array(
        'message' => 'Email configuration is incomplete. Please contact the site administrator.',
        'status' => $status
    ));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['form_name']) ? trim($_POST['form_name']) : '';
    $email = isset($_POST['form_email']) ? trim($_POST['form_email']) : '';
    $subject = isset($_POST['form_subject']) ? trim($_POST['form_subject']) : '';
    $phone = isset($_POST['form_phone']) ? trim($_POST['form_phone']) : '';
    $message = isset($_POST['form_message']) ? trim($_POST['form_message']) : '';
    $botcheck = isset($_POST['form_botcheck']) ? trim($_POST['form_botcheck']) : '';
    $recaptchaResponse = isset($_POST['g-recaptcha-response']) ? trim($_POST['g-recaptcha-response']) : '';

    if ($botcheck !== '') {
        $responseMessage = 'Bot <strong>detected</strong>. Please try again.';
    } elseif ($name === '' || $email === '' || $subject === '' || $message === '') {
        $responseMessage = 'Please <strong>fill in</strong> all required fields and try again.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $responseMessage = 'Please enter a valid email address and try again.';
    } elseif ($recaptchaSecretKey !== '' && $recaptchaResponse === '') {
        $responseMessage = 'Please confirm that you are not a robot and try again.';
    } elseif ($recaptchaSecretKey !== '' && !verifyRecaptcha($recaptchaSecretKey, $recaptchaResponse)) {
        $responseMessage = 'reCAPTCHA verification failed. Please try again.';
    } else {
        $mail = new PHPMailer();

        $mail->isSMTP();
        $mail->Host = $smtpHost;
        $mail->SMTPAuth = true;
        $mail->Username = $smtpUsername;
        $mail->Password = $smtpPassword;
        $mail->SMTPSecure = $smtpSecure;
        $mail->Port = $smtpPort;

        $mail->SetFrom($fromEmail, $fromName);
        $mail->AddAddress($toEmail, $toName);
        $mail->AddReplyTo($email, $name);
        $mail->Subject = $subject;

        $safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
        $safeEmail = htmlspecialchars($email, ENT_QUOTES, 'UTF-8');
        $safePhone = htmlspecialchars($phone, ENT_QUOTES, 'UTF-8');
        $safeMessage = nl2br(htmlspecialchars($message, ENT_QUOTES, 'UTF-8'));
        $safeReferrer = isset($_SERVER['HTTP_REFERER']) ? htmlspecialchars($_SERVER['HTTP_REFERER'], ENT_QUOTES, 'UTF-8') : '';

        $body = '';
        $body .= "Name: {$safeName}<br><br>";
        $body .= "Email: {$safeEmail}<br><br>";
        $body .= "Phone: {$safePhone}<br><br>";
        $body .= "Message:<br>{$safeMessage}<br><br>";

        if ($safeReferrer !== '') {
            $body .= "<br><br>This form was submitted from: {$safeReferrer}";
        }

        $mail->MsgHTML($body);

        if ($mail->Send()) {
            $responseMessage = 'We have <strong>successfully</strong> received your message and will get back to you as soon as possible.';
            $status = 'true';
        } else {
            $responseMessage = 'Email <strong>could not</strong> be sent. Please try again later.<br><br><strong>Reason:</strong><br>' . $mail->ErrorInfo;
        }
    }
}

echo json_encode(array(
    'message' => $responseMessage,
    'status' => $status
));

function verifyRecaptcha($secretKey, $responseToken)
{
    $postData = http_build_query(array(
        'secret' => $secretKey,
        'response' => $responseToken,
        'remoteip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''
    ));

    $context = stream_context_create(array(
        'http' => array(
            'method' => 'POST',
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
            'content' => $postData,
            'timeout' => 10
        )
    ));

    $result = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);

    if ($result === false) {
        return false;
    }

    $decoded = json_decode($result, true);

    return isset($decoded['success']) && $decoded['success'] === true;
}
?>
