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

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

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

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

$saveFile = __DIR__ . '/data/requests.txt';
if (!is_dir(dirname($saveFile))) @mkdir(dirname($saveFile), 0777, true);
$entry = "Name: " . $clean($name) . "
"
       . "Email: " . $clean($email) . "
"
       . "Song: " . $clean($song) . "
"
       . "Artist: " . $clean($artist) . "
"
       . "Dedication: " . $clean($dedication) . "
---
";
file_put_contents($saveFile, $entry, FILE_APPEND | LOCK_EX);

header("Location: /requests.php?sent=1");
exit;
