<?php
require_once __DIR__ . '/includes/redirect_helper.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'] ?? ''));

if ($name === '' || $email === '' || $role === '' || $experience === '' || $why === '') {
    ah_redirect_back('/team.php', ['err' => 1]);
}

$clean = static function (string $value): string {
    $value = str_replace(["
", "
"], "
", $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 = "Timestamp: " . date('Y-m-d H:i:s') . "
"
       . "IP: " . $clean((string)($_SERVER['REMOTE_ADDR'] ?? '')) . "
"
       . "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);

ah_redirect_back('/team.php', ['sent' => 1]);
