<?php
session_start();
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.php';
$sent = isset($_GET['sent']) && $_GET['sent'] === '1';
$errorCode = $_GET['err'] ?? '';
$requestsFile = __DIR__ . '/data/requests.txt';
$statusFile = __DIR__ . '/data/request_status.json';
$statusMap = file_exists($statusFile) ? json_decode((string)file_get_contents($statusFile), true) : [];
if (!is_array($statusMap)) $statusMap = [];

function thunder_request_key(array $item): string {
    $raw = str_replace(["
", "
"], "
", trim((string)($item['_raw'] ?? '')));
    if ($raw === '') return md5(json_encode($item));
    $lines = preg_split("/
+/", $raw);
    $keep = [];
    foreach ($lines as $line) {
        if (preg_match('/^Approved\s*:/i', $line)) continue;
        $keep[] = trim((string)$line);
    }
    return md5(implode("
", $keep));
}

function thunder_parse_requests_public(string $file): array {
    if (!file_exists($file) || filesize($file) === 0) return [];
    $raw = trim((string)file_get_contents($file));
    if ($raw === '') return [];

    $out = [];

    if (strpos($raw, '---') !== false && preg_match('/(^|
)\w+\s*:/', $raw)) {
        $parts = preg_split("/
---\s*
/", $raw);
        foreach ($parts as $p) {
            $p = trim((string)$p);
            if ($p === '') continue;
            $item = ['_raw' => $p];
            foreach (preg_split('/\R/', $p) as $line) {
                if (strpos($line, ':') === false) continue;
                [$k,$v] = array_map('trim', explode(':', $line, 2));
                if ($k === '') continue;
                $item[strtolower($k)] = $v;
            }
            $out[] = $item;
        }
        return array_reverse($out);
    }

    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
    foreach ($lines as $line) {
        $p = explode('|', trim((string)$line));
        if (count($p) < 7) continue;
        [$id,$name,$song,$message,$ip,$timestamp,$approved] = array_pad($p, 7, '');
        $artist = '';
        $dedication = $message;
        if (strpos($song, ' - ') !== false) {
            [$artistMaybe, $songMaybe] = array_map('trim', explode(' - ', $song, 2));
            if ($songMaybe !== '') {
                $artist = $artistMaybe;
                $song = $songMaybe;
            }
        }
        $rawBlock = "ID: $id
Name: $name
Song: $song
Artist: $artist
Dedication: $dedication
IP: $ip
Timestamp: $timestamp
Approved: " . ((strtolower((string)$approved) === 'yes' || (string)$approved === '1') ? '1' : '0');
        $out[] = [
            '_raw' => $rawBlock,
            'id' => $id,
            'name' => $name,
            'song' => $song,
            'artist' => $artist,
            'dedication' => $dedication,
            'ip' => $ip,
            'timestamp' => $timestamp,
            'approved' => ((strtolower((string)$approved) === 'yes' || (string)$approved === '1') ? '1' : '0'),
        ];
    }
    return array_reverse($out);
}

$recent = [];
foreach (thunder_parse_requests_public($requestsFile) as $item) {
    $approvedFlag = strtolower((string)($item['approved'] ?? '0'));
    $isApproved = in_array($approvedFlag, ['1', 'yes', 'true'], true);
    $meta = $statusMap[thunder_request_key($item)] ?? null;
    $status = strtolower((string)($meta['status'] ?? ($isApproved ? 'approved' : 'pending')));
    if (!in_array($status, ['approved', 'accepted', 'played'], true)) continue;
    $item['_status'] = $meta['status'] ?? ($isApproved ? 'Approved' : '');
    $item['_note'] = $meta['note'] ?? '';
    $recent[] = $item;
    if (count($recent) >= 5) break;
}
?>
<main class="content-area">
  <div class="content-wrapper page-shell">
    <?php if ($sent): ?><div class="alert alert-success">Thanks! Your request has been received.</div><?php endif; ?>
    <?php if ($errorCode !== ''): ?><div class="alert alert-danger"><?php
      if ($errorCode === 'missing') echo 'Please complete your name, email, song, and artist before sending your request.';
      else echo 'We could not send your request. Please try again.';
    ?></div><?php endif; ?>
    <section class="content-card center-text">
      <h1>📬 Send a Request</h1>
      <p>Want to hear something specific? Drop your request below.</p>
      <form method="post" action="send_request.php" class="form-shell" style="text-align:left;" style="max-width:760px;">
        <input type="text" name="name" class="form-control mb-3" placeholder="Your name or DJ handle" required>
        <input type="email" name="email" class="form-control mb-3" placeholder="Your email" required>
        <input type="text" name="song" class="form-control mb-3" placeholder="Song title" required>
        <input type="text" name="artist" class="form-control mb-3" placeholder="Artist" required>
        <textarea name="dedication" class="form-control mb-3" placeholder="Your dedication or shoutout" rows="4"></textarea>
        <button type="submit" class="button play-btn">Send Request</button>
      </form>
    </section>
  </div>
  <div class="content-wrapper page-shell">
    <section class="content-card">
      <h2>🎧 Recent Approved Requests</h2>
      <?php if (empty($recent)): ?>
        <p>No approved requests yet.</p>
      <?php else: ?>
        <?php foreach ($recent as $item): ?>
          <div class="comment-box">
            <strong><?= htmlspecialchars((string)($item['name'] ?? 'Listener')) ?></strong>
            requested <em><?= htmlspecialchars((string)($item['song'] ?? '')) ?></em>
            <?php if (!empty($item['artist'])): ?> by <em><?= htmlspecialchars((string)$item['artist']) ?></em><?php endif; ?>
            <?php if (!empty($item['_status'])): ?><span class="badge bg-primary rounded-pill" style="margin-left:8px;"><?= htmlspecialchars((string)$item['_status']) ?></span><?php endif; ?><br>
            <?= nl2br(htmlspecialchars((string)($item['dedication'] ?? ($item['message'] ?? '')))) ?>
            <?php if (!empty($item['_note'])): ?><div style="margin-top:8px;opacity:.85;"><strong>DJ note:</strong> <?= htmlspecialchars((string)$item['_note']) ?></div><?php endif; ?>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </section>
  </div>
</main>
<?php include __DIR__ . '/includes/footer.php'; ?>
