<?php
$name    = trim((string)($_POST['name'] ?? ''));
$email   = trim((string)($_POST['email'] ?? ''));
$subject = trim((string)($_POST['subject'] ?? ''));
$message = trim((string)($_POST['message'] ?? ''));

$clean = function ($value) {
    $value = str_replace(["\r\n", "\r"], "\n", (string)$value);
    $value = preg_replace("/\n{3,}/", "\n\n", $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;
