<?php
$name       = trim((string)($_POST['name'] ?? ''));
$email      = trim((string)($_POST['email'] ?? ''));
$role       = trim((string)($_POST['role'] ?? ''));
$experience = trim((string)($_POST['experience'] ?? ''));
$why        = trim((string)($_POST['why'] ?? ''));

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

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

$demoFile = '';
if (!empty($_FILES['demo']['name'])) {
    $uploadDir = __DIR__ . '/uploads/demos/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
    $filename = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]+/', '-', basename((string)$_FILES['demo']['name']));
    $targetPath = $uploadDir . $filename;
    if (!empty($_FILES['demo']['tmp_name']) && move_uploaded_file($_FILES['demo']['tmp_name'], $targetPath)) $demoFile = $filename;
}

$saveFile = __DIR__ . '/data/applications.txt';
$entry = "Name: " . $clean($name) . "
"
       . "Email: " . $clean($email) . "
"
       . "Role: " . $clean($role) . "
"
       . "Experience: " . $clean($experience) . "
"
       . "Why: " . $clean($why) . "
"
       . "Demo: " . $clean($demoFile) . "
---
";
file_put_contents($saveFile, $entry, FILE_APPEND | LOCK_EX);

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