<?php
session_start();
require __DIR__ . '/auth.php';
require __DIR__ . '/includes/admin_lib.php';
$file = __DIR__ . '/../data/requests.txt';
$statusFile = __DIR__ . '/../data/request_status.json';
$statusMap = smurf_read_json($statusFile, []);
if (!is_array($statusMap)) $statusMap = [];

function almostheaven_parse_requests(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('/(^|\n)\w+\s*:/', $raw)) {
    foreach (smurf_parse_blocks($file) as $item) {
      $name = trim((string)($item['Name'] ?? ''));
      $song = trim((string)($item['Song'] ?? ''));
      $artist = trim((string)($item['Artist'] ?? ''));
      $dedication = trim((string)($item['Dedication'] ?? ($item['Message'] ?? '')));
      $email = trim((string)($item['Email'] ?? ''));
      if ($name === '' && $song === '' && $artist === '' && $dedication === '' && $email === '') continue;
      $item['_key'] = smurf_entry_stable_key($item);
      $out[] = $item;
    }
    return $out;
  }
  $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
  foreach (array_reverse($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 = '';
    if (strpos($song, ' - ') !== false) {
      [$artistMaybe, $songMaybe] = array_map('trim', explode(' - ', $song, 2));
      if ($songMaybe !== '') { $artist = $artistMaybe; $song = $songMaybe; }
    }
    if (trim($name) === '' && trim($song) === '' && trim($artist) === '' && trim($message) === '') continue;
    $rawBlock = "ID: $id\nName: $name\nEmail: \nSong: $song\nArtist: $artist\nDedication: $message\nIP: $ip\nTimestamp: $timestamp\nApproved: " . ((strtolower((string)$approved)==='yes'||(string)$approved==='1')?'1':'0');
    $item = ['ID'=>$id,'Name'=>$name,'Email'=>'','Song'=>$song,'Artist'=>$artist,'Dedication'=>$message,'IP'=>$ip,'Timestamp'=>$timestamp,'Approved'=>((strtolower((string)$approved)==='yes'||(string)$approved==='1')?'1':'0'),'_raw'=>$rawBlock];
    $item['_key'] = smurf_entry_stable_key($item);
    $out[] = $item;
  }
  return $out;
}
function almostheaven_write_requests(string $file, array $items): void {
  $blocks = [];
  foreach (array_reverse($items) as $it) {
    $rows = [
      'ID: ' . trim((string)($it['ID'] ?? '')),
      'Name: ' . str_replace(["\n","\r"], ' ', (string)($it['Name'] ?? '')),
      'Email: ' . str_replace(["\n","\r"], ' ', (string)($it['Email'] ?? '')),
      'Song: ' . str_replace(["\n","\r"], ' ', (string)($it['Song'] ?? '')),
      'Artist: ' . str_replace(["\n","\r"], ' ', (string)($it['Artist'] ?? '')),
      'Dedication: ' . str_replace(["\r"], '', (string)($it['Dedication'] ?? ($it['Message'] ?? ''))),
      'IP: ' . str_replace(["\n","\r"], ' ', (string)($it['IP'] ?? '')),
      'Timestamp: ' . str_replace(["\n","\r"], ' ', (string)($it['Timestamp'] ?? '')),
      'Approved: ' . (((string)($it['Approved'] ?? '0') === '1') ? '1' : '0'),
    ];
    $blocks[] = implode("\n", $rows);
  }
  file_put_contents($file, $blocks ? implode("\n---\n", $blocks) . "\n---\n" : '', LOCK_EX);
}

$items = almostheaven_parse_requests($file);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) die('<h1>Access Denied</h1><p>You do not have permission to manage requests.</p>');
  if (isset($_POST['clear_all'])) {
    almostheaven_write_requests($file, []);
    smurf_write_json($statusFile, []);
    header('Location: requests.php?saved=1'); exit;
  }
  $action = trim((string)($_POST['bulk_action'] ?? ''));
  $key = trim((string)($_POST['request_key'] ?? ''));
  $foundIndex = null;
  foreach ($items as $idx => $item) { if ((string)($item['_key'] ?? '') === $key) { $foundIndex = $idx; break; } }
  if ($foundIndex !== null) {
    if ($action === 'delete') {
      unset($statusMap[$key]);
      array_splice($items, $foundIndex, 1);
    } elseif ($action === 'approve') {
      $items[$foundIndex]['Approved'] = '1';
      $statusMap[$key] = array_merge((array)($statusMap[$key] ?? []), ['status'=>'Approved','note'=>(string)(($statusMap[$key]['note'] ?? '') ?: 'Approved for air'),'ts'=>time()]);
    } elseif ($action === 'unapprove') {
      $items[$foundIndex]['Approved'] = '0';
      unset($statusMap[$key]);
    } elseif ($action === 'played') {
      $items[$foundIndex]['Approved'] = '1';
      $statusMap[$key] = ['status'=>'Played','note'=>'Played on air','ts'=>time()];
    }
    almostheaven_write_requests($file, $items);
    smurf_write_json($statusFile, $statusMap);
    header('Location: requests.php?saved=1'); exit;
  }
}
$items = almostheaven_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;align-items:center;"><?php if ($CAN_EDIT): ?><form method="post" onsubmit="return confirm('Clear ALL entries?');" style="margin:0;"><input type="hidden" name="clear_all" value="1"><button class="admin-btn danger" type="submit">Clear All</button></form><?php endif; ?><a class="admin-btn" href="index.php">Back</a></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 $item):
    $approved = (string)($item['Approved'] ?? '0') === '1';
    $key = (string)($item['_key'] ?? '');
    $meta = $statusMap[$key] ?? [];
    $displayName = $item['Name'] ?? 'Listener';
    $displaySong = $item['Song'] ?? 'Request';
    $displayArtist = $item['Artist'] ?? '';
    $displayDedication = $item['Dedication'] ?? ($item['Message'] ?? '');
  ?>
    <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((string)$displaySong) ?><?= $displayArtist !== '' ? ' — ' . smurf_h((string)$displayArtist) : '' ?></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((string)$meta['status']) ?></span><?php endif; ?><?php if ($CAN_EDIT): ?>
        <form method="post" style="margin:0;"><input type="hidden" name="request_key" value="<?= smurf_h($key) ?>"><?php if (!$approved): ?><button class="admin-btn" name="bulk_action" value="approve" type="submit">Approve</button><?php else: ?><button class="admin-btn" name="bulk_action" value="unapprove" type="submit">Unapprove</button><?php endif; ?></form>
        <form method="post" style="margin:0;"><input type="hidden" name="request_key" value="<?= smurf_h($key) ?>"><button class="admin-btn" name="bulk_action" value="played" type="submit">Mark Played</button></form>
        <form method="post" style="margin:0;" onsubmit="return confirm('Delete this request?');"><input type="hidden" name="request_key" value="<?= smurf_h($key) ?>"><button class="admin-btn" name="bulk_action" value="delete" type="submit">Delete</button></form>
      <?php endif; ?></div></div>
      <div style="margin-top:10px;display:grid;gap:8px;">
        <div><strong>Name:</strong> <?= smurf_h((string)$displayName) ?></div>
        <?php if (!empty($item['Email'])): ?><div><strong>Email:</strong> <?= smurf_h((string)$item['Email']) ?></div><?php endif; ?>
        <?php if ($displayDedication !== ''): ?><div><strong>Dedication:</strong><br><?= nl2br(smurf_h((string)$displayDedication)) ?></div><?php endif; ?>
        <?php if (!empty($item['Timestamp'])): ?><div><strong>Timestamp:</strong> <?= smurf_h((string)$item['Timestamp']) ?></div><?php endif; ?>
      </div>
      <?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((string)$meta['note']) ?></div><?php endif; ?>
    </div>
  <?php endforeach; endif; ?>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
