<?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(["\r\n", "\r"], "\n", (string)$value);
    $value = preg_replace("/\n{3,}/", "\n\n", $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) . "\n"
       . "Email: " . $clean($email) . "\n"
       . "Role: " . $clean($role) . "\n"
       . "Experience: " . $clean($experience) . "\n"
       . "Why: " . $clean($why) . "\n"
       . "Demo: " . $clean($demoFile) . "\n---\n";
file_put_contents($saveFile, $entry, FILE_APPEND | LOCK_EX);

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