<?php
require 'vendor/autoload.php'; // if you used Composer

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    $name     = htmlspecialchars($_POST['name'] ?? '');
    $email    = htmlspecialchars($_POST['email'] ?? '');
    $phone    = htmlspecialchars($_POST['phone'] ?? '');
    $pref     = htmlspecialchars($_POST['preferred_contact'] ?? '');
    $message  = htmlspecialchars($_POST['message'] ?? '');

    if (!$name || !$email || !$phone || !$pref || !$message) {
        http_response_code(400);
        echo "All fields are required.";
        exit;
    }


    if (!empty($_POST['website'])) {
        // Bot filled out the honeypot
        http_response_code(400);
        die("Bot detected. Submission rejected.");
    }


    $body = <<<EOT
You have a new contact form submission:

Name: $name
Email: $email
Phone: $phone
Preferred Contact: $pref

Message:
$message
EOT;

    // SMTP config
    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
    $dotenv->load();

    $mail->isSMTP();
    $mail->Host       = $_ENV['SMTP_HOST'];
    $mail->SMTPAuth   = true;
    $mail->Username   = $_ENV['SMTP_USER'];
    $mail->Password   = $_ENV['SMTP_PASS'];
    $mail->SMTPSecure = $_ENV['SMTP_SECURE'];
    $mail->Port       = $_ENV['SMTP_PORT'];

    // Email headers
    $mail->setFrom($_ENV['MAIL_TO'], $name);   // sender = SMTP account
    $mail->addAddress($_ENV['MAIL_TO']);     // recipient
    $mail->addReplyTo($email, $name);               // visitor’s email

    $mail->Subject = 'New Contact Form Submission From Company Site';
    $mail->Body    = $body;

    $mail->send();
    echo "OK";

} catch (Exception $e) {
    http_response_code(500);
    echo "Mailer Error: " . $mail->ErrorInfo;
}
