<?php
$name = trim((string)($_POST['name'] ?? ''));
$email = trim((string)($_POST['email'] ?? ''));
$song = trim((string)($_POST['song'] ?? ''));
$artist = trim((string)($_POST['artist'] ?? ''));
$genre = trim((string)($_POST['genre'] ?? ''));
$djName = trim((string)($_POST['dj_name'] ?? ''));
$company = trim((string)($_POST['company'] ?? 'Radio Galaxy FX'));
$dedication = trim((string)($_POST['dedication'] ?? $_POST['message'] ?? ''));

$clean = function ($value) {
    $value = str_replace(["\r\n", "\r"], "\n", (string)$value);
    $value = preg_replace("/\n{3,}/", "\n\n", $value);
    return trim($value);
};

if ($name === '' || $song === '' || $artist === '' || $djName === '') {
    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) . "\n"
       . "Email: " . $clean($email) . "\n"
       . "DJ_Name: " . $clean($djName) . "\n"
       . "Company: " . $clean($company) . "\n"
       . "Song: " . $clean($song) . "\n"
       . "Artist: " . $clean($artist) . "\n"
       . "Genre: " . $clean($genre) . "\n"
       . "Dedication: " . $clean($dedication) . "\n"
       . "Req_From: Website\n"
       . "---\n";
file_put_contents($saveFile, $entry, FILE_APPEND | LOCK_EX);

$url = 'https://broadcasturself.com/request/insert_request.php';
$postData = [
    'DJ_Name' => $djName,
    'Company' => $company,
    'Message' => $dedication,
    'Song_Name' => $song,
    'Artist' => $artist,
    'Genre' => $genre,
    'Req_From' => 'Website',
    'DJ_ID' => $djName,
    'Req_User_ID' => $name,
];

$sent = false;
if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($postData),
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_TIMEOUT => 10,
    ]);
    $response = curl_exec($ch);
    if ($response !== false) {
        $sent = true;
    } else {
        error_log('Request API Error: ' . curl_error($ch));
    }
    curl_close($ch);
}

if (!$sent) {
    $opts = [
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
            'content' => http_build_query($postData),
            'timeout' => 10,
        ]
    ];
    $context = stream_context_create($opts);
    $response = @file_get_contents($url, false, $context);
    if ($response === false) {
        error_log('Request API Error: stream fallback failed');
    }
}

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