<?php
$pageTitle = 'Requests — Home Time Radio';
include __DIR__ . '/includes/header.php';
$requestsFile = __DIR__ . '/data/requests.txt';
?>
<div class="container content-box mt-5">
  <?php if (!empty($_GET['sent'])): ?><div class="alert alert-success">Your request has been sent and is waiting for approval.</div><?php endif; ?>

  <div class="text-center mb-5">
    <h1>Song Requests</h1>
    <p class="subtext">Send in a song request or a shoutout for the Home Time team.</p>
  </div>

  <div class="htr-box mb-5">
    <form method="POST" action="send_request.php">
      <div class="mb-3">
        <label for="request-name" class="form-label">Your Name</label>
        <input type="text" name="name" id="request-name" class="form-control" required>
      </div>
      <div class="mb-3">
        <label for="request-song" class="form-label">Song / Artist</label>
        <input type="text" name="song" id="request-song" class="form-control" placeholder="Optional">
      </div>
      <div class="mb-3">
        <label for="request-message" class="form-label">Message</label>
        <textarea name="message" id="request-message" class="form-control" rows="5" placeholder="Your request or shoutout" required></textarea>
      </div>
      <button type="submit" class="btn btn-primary">Send Request</button>
    </form>
  </div>

  <div class="htr-box">
    <h4>Recent Approved Requests</h4>
    <?php
    $requests = file_exists($requestsFile) ? file($requestsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
    $approved = array_filter($requests, function($line) {
        $parts = explode('|', $line);
        return isset($parts[6]) && strtolower(trim((string)$parts[6])) === 'yes';
    });
    $recent = array_slice(array_reverse($approved), 0, 8);
    if (empty($recent)) {
        echo '<p class="mb-0">No approved requests are showing yet.</p>';
    } else {
        foreach ($recent as $line) {
            $parts = explode('|', $line);
            if (count($parts) >= 7) {
                [$id, $name, $song, $message, $ip, $timestamp, $approvedFlag] = $parts;
                echo '<div class="border-bottom pb-3 mb-3">';
                echo '<strong>' . htmlspecialchars((string)$name, ENT_QUOTES, 'UTF-8') . '</strong>';
                if (trim((string)$song) !== '') {
                    echo ' requested <em>' . htmlspecialchars((string)$song, ENT_QUOTES, 'UTF-8') . '</em>';
                }
                echo '<div><small>' . htmlspecialchars((string)$timestamp, ENT_QUOTES, 'UTF-8') . '</small></div>';
                echo '<p class="mb-0 mt-2">' . nl2br(htmlspecialchars((string)$message, ENT_QUOTES, 'UTF-8')) . '</p>';
                echo '</div>';
            }
        }
    }
    ?>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
