<?php include 'includes/header.php'; ?>
<?php include 'includes/menu.php'; ?>

<?php
$requestsFile = __DIR__ . '/data/requests.txt';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['name']) && !empty($_POST['message'])) {
  $id = uniqid();
  $name = trim($_POST['name']);
  $song = trim($_POST['song'] ?? '');
  $message = trim($_POST['message']);
  $ip = $_SERVER['REMOTE_ADDR'];
  $timestamp = date('Y-m-d H:i:s');
  $approved = 'no';
  $entry = "$id|$name|$song|$message|$ip|$timestamp|$approved\n";
  file_put_contents($requestsFile, $entry, FILE_APPEND);
  echo "<div class='alert alert-success'>Thanks! Your request will appear once approved.</div>";
}
?>

<div class="container mt-5">
  <div class="content-box">
    <h2>📬 Send a Request</h2>
    <p class="mb-4">Want to hear something specific? Got a shoutout for a DJ? Drop it below and we’ll make it thunder.</p>

    <form method="POST">
      <input type="text" name="name" class="form-control mb-3" placeholder="Your name or DJ handle" required>
      <input type="text" name="song" class="form-control mb-3" placeholder="Song title (optional)">
      <textarea name="message" class="form-control mb-3" placeholder="Your request or shoutout" required></textarea>
      <button type="submit" class="btn btn-primary">Send Request</button>
    </form>
  </div>

  <div class="content-box mt-5">
    <h4>🎧 Recent Requests</h4>
    <?php
    $requests = file_exists($requestsFile) ? file($requestsFile, FILE_IGNORE_NEW_LINES) : [];
    $approved = array_filter($requests, function($line){ $parts = explode('|', $line); return isset($parts[6]) && $parts[6] === 'yes'; });
    $recent = array_slice(array_reverse($approved), 0, 5);
    foreach ($recent as $line) {
      $parts = explode('|', $line);
      if (count($parts) === 7) {
        [$id, $name, $song, $message, $ip, $timestamp, $approved] = $parts;
        echo "<div class='comment-box'>";
        echo "<strong>" . htmlspecialchars($name) . "</strong>";
        if ($song) echo " requested <em>" . htmlspecialchars($song) . "</em>";
        echo " <em>[" . htmlspecialchars($timestamp) . "]</em><br>";
        echo nl2br(htmlspecialchars($message));
        echo "</div>";
      }
    }
    ?>
  </div>
</div>

<?php include 'includes/footer.php'; ?>
