<?php
session_start();

// Honeypot: if a bot filled in a hidden field, silently discard
if (!empty($_POST['website'])) {
    header('Location: index.php?sent=1#contact');
    exit;
}

$name    = trim($_POST['name']    ?? '');
$email   = trim($_POST['email']   ?? '');
$message = trim($_POST['message'] ?? '');
$captcha = intval($_POST['captcha'] ?? -9999);
$expected = intval($_SESSION['captcha_answer'] ?? -1);

// Always clear session captcha after use
unset($_SESSION['captcha_answer']);

// Validate
$valid = true;
if (empty($name) || strlen($name) > 200) {
    $valid = false;
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $valid = false;
}
if (empty($message) || strlen($message) > 5000) {
    $valid = false;
}
if ($captcha !== $expected || $expected === -1) {
    $valid = false;
}

if (!$valid) {
    header('Location: index.php?error=1#contact');
    exit;
}

// Sanitize for email body
$safeName    = strip_tags($name);
$safeEmail   = strip_tags($email);
$safeMessage = strip_tags($message);

$to      = 'wizard@fraxle.net';
$subject = "Fraxle.net enquiry from $safeName";
$body    = "You have a new enquiry from your website.\n\n"
         . "Name:    $safeName\n"
         . "Email:   $safeEmail\n"
         . "Message:\n$safeMessage\n\n"
         . "---\nSent via fraxle.net contact form";

$headers  = "From: noreply@fraxle.net\r\n";
$headers .= "Reply-To: $safeEmail\r\n";
$headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

if (mail($to, $subject, $body, $headers)) {
    header('Location: index.php?sent=1#contact');
} else {
    header('Location: index.php?error=1#contact');
}
exit;
