<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  header('Location: /contact.php');
  exit;
}

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

$clean = function ($value) {
    $value = str_replace(["
", "
"], "
", (string)$value);
    $value = preg_replace("/
{3,}/", "

", $value);
    return trim($value);
};

if ($name === '' || $email === '' || $message === '') {
  header('Location: /contact.php?error=missing');
  exit;
}

$saveFile = __DIR__ . '/../data/contact_messages.txt';
if (!is_dir(dirname($saveFile))) @mkdir(dirname($saveFile), 0777, true);
$entry = "Name: " . $clean($name) . "
"
       . "Email: " . $clean($email) . "
"
       . "Subject: " . $clean($subject) . "
"
       . "Message: " . $clean($message) . "
---
";
file_put_contents($saveFile, $entry, FILE_APPEND | LOCK_EX);

header('Location: /contact.php?sent=1');
exit;
