<?php
include __DIR__ . '/includes/header.php';
require_once __DIR__ . '/admin/includes/admin_lib.php';

$file = __DIR__ . '/data/requests.txt';
$statusFile = __DIR__ . '/data/request_status.json';
$items = smurf_parse_blocks($file);
$statusMap = smurf_read_json($statusFile, []);
if (!is_array($statusMap)) $statusMap = [];
function ht_req_key(string $block): string { return sha1($block); }
?>
<div class="container content-box mt-5">
  <div class="text-center mb-5">
    <h1>Song Requests</h1>
    <p class="subtext">Send a request, dedication, or shoutout to the Home Time team.</p>
  </div>

  <?php if (!empty($_GET['sent'])): ?>
    <div class="alert alert-success">Thanks — your request has been sent.</div>
  <?php endif; ?>

  <div class="bg-light p-4 rounded mb-5">
    <form method="POST" action="/send_request.php">
      <div class="mb-3">
        <label for="name">Your Name</label>
        <input type="text" name="name" id="name" class="form-control" required>
      </div>
      <div class="mb-3">
        <label for="email">Your Email</label>
        <input type="email" name="email" id="email" class="form-control">
      </div>
      <div class="mb-3">
        <label for="song">Song Title</label>
        <input type="text" name="song" id="song" class="form-control" required>
      </div>
      <div class="mb-3">
        <label for="artist">Artist</label>
        <input type="text" name="artist" id="artist" class="form-control">
      </div>
      <div class="mb-3">
        <label for="dedication">Dedication / Message</label>
        <textarea name="dedication" id="dedication" class="form-control" rows="5" placeholder="Optional message or shoutout"></textarea>
      </div>
      <button type="submit" class="btn btn-dark">Send Request</button>
    </form>
  </div>

  <div class="content-box mt-5">
    <h4>Recent Accepted Requests</h4>
    <?php
    $shown = 0;
    foreach ($items as $item) {
      $k = ht_req_key($item['_raw'] ?? '');
      $meta = $statusMap[$k] ?? ['status' => 'Pending'];
      if (($meta['status'] ?? 'Pending') !== 'Accepted' && ($meta['status'] ?? '') !== 'Played') continue;
      $shown++;
      echo '<div class="comment-box">';
      echo '<strong>' . htmlspecialchars((string)($item['Name'] ?? 'Listener')) . '</strong>';
      if (!empty($item['Song'])) echo ' requested <em>' . htmlspecialchars((string)$item['Song']) . '</em>';
      if (!empty($item['Artist'])) echo ' by ' . htmlspecialchars((string)$item['Artist']);
      if (!empty($item['Dedication'])) echo '<br>' . nl2br(htmlspecialchars((string)$item['Dedication']));
      echo '</div>';
      if ($shown >= 5) break;
    }
    if ($shown === 0) echo '<p>No accepted requests yet.</p>';
    ?>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
