<?php
require __DIR__ . '/vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(__DIR__ . '/../');
$dotenv->safeLoad();

// Get form values
$first_name = $_POST['first_name'] ?? '';
$last_name = $_POST['last_name'] ?? '';
$name = trim("$first_name $last_name") ?: 'No Name';

// Drinks can be an array
$drinks = $_POST['drinks'] ?? 'None';
if (is_array($drinks)) {
    $drinks = implode(', ', $drinks);
}

// Allergies
$allergies = $_POST['allergies'] ?? 'None';

// Convert to UTF-8
$name = mb_convert_encoding($name, 'UTF-8', 'auto');
$drinks = mb_convert_encoding($drinks, 'UTF-8', 'auto');
$allergies = mb_convert_encoding($allergies, 'UTF-8', 'auto');

// PHPMailer setup
$mail = new PHPMailer(true);
try {
    $mail->CharSet = 'UTF-8';
    $mail->isSMTP();
    $mail->Host       = $_ENV['SMTP_HOST'];
    $mail->SMTPAuth   = true;
    $mail->Username   = $_ENV['SMTP_USER'];
    $mail->Password   = $_ENV['SMTP_PASS'];
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = (int)$_ENV['SMTP_PORT'];

    $mail->setFrom($_ENV['FROM_EMAIL'], $_ENV['FROM_NAME']);
    $mail->addAddress($_ENV['TO_EMAIL']);

    $mail->Subject = mb_encode_mimeheader("New Wedding Guest: $name", 'UTF-8');

    $body = <<<EOD
Name: $name
Drinks: $drinks
Allergies: $allergies
EOD;

    $mail->Body = $body;
    $mail->send();

    echo 'RSVP submitted successfully.';
} catch (Exception $e) {
    echo "RSVP could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
