<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // --- Cloudflare Turnstile ---
    $secretKey = '0x4AAAAAABM25eGlhpJjtI2N7jRBBNZZaTQ';
    $captchaResponse = $_POST['cf-turnstile-response'] ?? '';
    $remoteIp = $_SERVER['REMOTE_ADDR'];
    $verifyUrl = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';

    $data = [
        'secret' => $secretKey,
        'response' => $captchaResponse,
        'remoteip' => $remoteIp
    ];

    // Verificação com cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $verifyUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded'
    ]);
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        curl_close($ch);
        header('Location: contato.html?error=captcha');
        exit();
    }

    curl_close($ch);
    $responseKeys = json_decode($response, true);

    if (intval($responseKeys['success']) !== 1) {
        header('Location: contato.html?error=captcha');
        exit();
    }

    // --- Validação e Sanitização dos dados ---
    $name = htmlspecialchars(trim($_POST['name']));
    $email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
    $subject = htmlspecialchars(trim($_POST['subject']));
    $message = htmlspecialchars(trim($_POST['message']));

    if (!$email || preg_match("/[\r\n]/", $email)) {
        header('Location: contato.html?error=invalid_email');
        exit();
    }

    // --- Enviar com PHPMailer ---
    $mail = new PHPMailer(true);

    try {
        // Configurações SMTP
        $mail->isSMTP();
        $mail->Host = 'mail.welcomehost.com.br'; // ou smtp.seudominio.com.br
        $mail->SMTPAuth = true;
        $mail->Username = 'contato@welcomehost.com.br'; // SEU EMAIL
        $mail->Password = 'n{?G#=)ffo25'; // SENHA DO EMAIL
        $mail->SMTPSecure = 'tls'; // ou 'ssl'
        $mail->Port = 587; // porta TLS: 587 | SSL: 465

        // Remetente e destinatário
        $mail->setFrom('contato@welcomehost.com.br', 'Contato WelcomeHost');
        $mail->addAddress('contato@welcomehost.com.br');
        $mail->addReplyTo($email, $name);

        // Conteúdo
        $mail->isHTML(false);
        $mail->Subject = "Formulario de Contato: $subject";
        $mail->Body = "Nome: $name\nEmail: $email\nAssunto: $subject\nMensagem:\n$message";

        $mail->send();
        header('Location: contato.html?success=true');
        exit();
    } catch (Exception $e) {
        error_log("Erro PHPMailer: " . $mail->ErrorInfo);
        header('Location: contato.html?error=email');
        exit();
    }
}
?>