
<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';
$file = __DIR__ . '/../data/requests.txt';
$bannedFile = __DIR__ . '/../data/banned_ips.txt';
$statusFile = __DIR__ . '/../data/request_status.json';
$statusMap = smurf_read_json($statusFile, []);
if (!is_array($statusMap)) $statusMap = [];
function thunder_parse_requests(string $file): array {
  if (!file_exists($file) || filesize($file) === 0) return [];
  $raw = trim((string)file_get_contents($file));
  if ($raw === '') return [];
  if (strpos($raw, '---') !== false && preg_match('/(^|
)\w+\s*:/', $raw)) return smurf_parse_blocks($file);
  $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
  $out = [];
  foreach (array_reverse($lines) as $line) {
    $p = explode('|', trim($line));
    if (count($p) >= 7) {
      [$id,$name,$song,$message,$ip,$timestamp,$approved] = array_pad($p, 7, '');
      $rawBlock = "ID: $id
Name: $name
Song: $song
Message: $message
IP: $ip
Timestamp: $timestamp
Approved: ".(($approved==='yes'||$approved==='1')?'1':'0');
      $out[] = ['ID'=>$id,'Name'=>$name,'Song'=>$song,'Message'=>$message,'IP'=>$ip,'Timestamp'=>$timestamp,'Approved'=>($approved==='yes'||$approved==='1')?'1':'0','_raw'=>$rawBlock,'_legacy_line'=>$line];
    }
  }
  return $out;
}
function thunder_write_requests(string $file, array $items): void {
  $legacy = true;
  foreach ($items as $it) { if (!isset($it['_legacy_line'])) { $legacy = false; break; } }
  if ($legacy) {
    $lines=[]; foreach (array_reverse($items) as $it) {
      $id=$it['ID']??''; $name=str_replace(["
","
","|"],' ',(string)($it['Name']??'')); $song=str_replace(["
","
","|"],' ',(string)($it['Song']??''));
      $msg=str_replace(["
","
","|"],' ',(string)($it['Message']??'')); $ip=str_replace('|',' ',(string)($it['IP']??'')); $ts=str_replace('|',' ',(string)($it['Timestamp']??'')); $ap=(($it['Approved']??'0')==='1')?'yes':'no';
      $lines[]="$id|$name|$song|$msg|$ip|$ts|$ap";
    }
    file_put_contents($file, implode("
", $lines) . (count($lines)?"
":"")); return;
  }
  $blocks=[]; foreach (array_reverse($items) as $it) { $blocks[] = trim((string)($it['_raw'] ?? '')); }
  file_put_contents($file, implode("
---
", array_filter($blocks)) . (count($blocks)?"
---
":""));
}
function thunder_request_key(array $item): string { return sha1((string)($item['_raw'] ?? json_encode($item))); }
$action = $_GET['action'] ?? '';
$idx = isset($_GET['i']) ? (int)$_GET['i'] : -1;
$items = thunder_parse_requests($file);
if ($action === 'clear' && $CAN_EDIT) { thunder_write_requests($file, []); smurf_redirect_self([], ['action','i']); }
if ($action === 'delete' && $idx >= 0 && isset($items[$idx]) && $CAN_EDIT) { array_splice($items,$idx,1); thunder_write_requests($file,$items); smurf_redirect_self([], ['action','i']); }
if (($action === 'approve' || $action === 'unapprove') && $idx >= 0 && isset($items[$idx]) && $CAN_EDIT) { $items[$idx]['Approved'] = ($action === 'approve') ? '1' : '0'; thunder_write_requests($file,$items); smurf_redirect_self(['saved'=>1], ['action','i']); }
if ($action === 'mark_played' && $idx >= 0 && isset($items[$idx]) && $CAN_EDIT) { $k = thunder_request_key($items[$idx]); $statusMap[$k] = ['status'=>'Played','note'=>trim((string)($_GET['note'] ?? 'Played on air')),'ts'=>time()]; smurf_write_json($statusFile, $statusMap); smurf_redirect_self(['saved'=>1], ['action','i']); }
$items = thunder_parse_requests($file);
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;"><h1 class="admin-title" style="margin:0;">🎶 Requests</h1><div style="display:flex;gap:10px;flex-wrap:wrap;"><a class="admin-btn" href="/admin/index.php">Back</a><?php if ($CAN_EDIT): ?><a class="admin-btn danger" href="/admin/requests.php?action=clear" onclick="return confirm('Clear ALL entries?');">Clear All</a><?php endif; ?></div></div>
  <?php if (!empty($_GET['saved'])): ?><div class="msg success" style="margin-top:10px;">Saved.</div><?php endif; ?>
  <?php if (empty($items)): ?><p>No entries yet.</p><?php else: foreach ($items as $i => $item): $approved = (string)($item['Approved'] ?? '0') === '1'; $k = thunder_request_key($item); $meta = $statusMap[$k] ?? []; ?>
    <div class="content-card" style="text-align:left;">
      <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;"><strong><?= smurf_h($item['Song'] ?? 'Request') ?></strong><div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;"><span style="font-weight:700;<?= $approved ? 'color:#7CFFB5' : 'color:#ffd27a' ?>;"><?= $approved ? 'Approved' : 'Pending' ?></span><?php if (!empty($meta['status'])): ?><span class="preview-badge"><?= smurf_h($meta['status']) ?></span><?php endif; ?><?php if ($CAN_EDIT): ?><?php if (!$approved): ?><a class="admin-btn" href="/admin/requests.php?action=approve&i=<?= $i ?>">Approve</a><?php else: ?><a class="admin-btn" href="/admin/requests.php?action=unapprove&i=<?= $i ?>">Unapprove</a><?php endif; ?><a class="admin-btn" href="/admin/requests.php?action=mark_played&i=<?= $i ?>">Mark Played</a><a class="admin-btn" href="/admin/requests.php?action=delete&i=<?= $i ?>" onclick="return confirm('Delete this request?');">Delete</a><?php endif; ?></div></div>
      <pre style="white-space:pre-wrap;margin:10px 0 0;opacity:.95;"><?= smurf_h($item['_raw'] ?? '') ?></pre>
      <?php if (!empty($meta['note'])): ?><div style="margin-top:10px;padding:10px;border:1px solid rgba(255,215,120,.35);border-radius:10px;opacity:.95;">🎧 <?= smurf_h($meta['note']) ?></div><?php endif; ?>
    </div>
  <?php endforeach; endif; ?>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
