<?php
$name    = trim((string)($_POST['name'] ?? ''));
$email   = trim((string)($_POST['email'] ?? ''));
$subject = trim((string)($_POST['subject'] ?? ''));
$message = trim((string)($_POST['message'] ?? ''));
if ($name === '' || $email === '' || $message === '') {
    header('Location: contact.php?err=1');
    exit;
}
$clean = function (string $value): string {
    $value = str_replace(["\r\n", "\r"], "\n", $value);
    $value = preg_replace("/\n{3,}/", "\n\n", $value);
    $value = str_replace(["\0"], '', $value);
    return trim($value);
};
$saveFile = __DIR__ . '/data/contact_messages.txt';
$entry = "Name: " . $clean($name) . "\n"
       . "Email: " . $clean($email) . "\n"
       . "Subject: " . $clean($subject) . "\n"
       . "Message: " . $clean($message) . "\n---\n";
file_put_contents($saveFile, $entry, FILE_APPEND | LOCK_EX);
header('Location: contact.php?sent=1');
exit;
