<?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 smurf_req_key(array $item): string { return smurf_entry_stable_key($item); }


$action = $_GET['action'] ?? '';
$idx = isset($_GET['i']) ? (int)$_GET['i'] : -1;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission.</p>");
  $bulkAction = (string)($_POST['bulk_action'] ?? '');
  $bulkIndex = (int)($_POST['bulk_index'] ?? -1);
  if ($bulkAction === 'delete' && $bulkIndex >= 0) {
    smurf_delete_block($file, $bulkIndex);
  } elseif ($bulkAction === 'clear') {
    smurf_clear_file($file);
  }
  smurf_redirect_self(['saved'=>1], ['action','i']);
}


if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['set_status']) && $CAN_EDIT) {
  $k = (string)($_POST['k'] ?? '');
  $st = (string)($_POST['status'] ?? 'Pending');
  $note = trim((string)($_POST['note'] ?? ''));
  if ($k !== '') {
    $statusMap[$k] = [
      'status' => $st,
      'note' => $note,
      'updated_at' => time(),
    ];
    smurf_write_json($statusFile, $statusMap);
  }
  header('Location: /admin/requests.php');
  exit;
}

$items = smurf_parse_blocks($file);
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">🎶 Song Requests</h1>
  <p style="opacity:.8;">File: <code>/data/requests.txt</code></p>

  <?php if (!empty($_GET['saved'])): ?><div class="msg success" style="margin-top:10px;">Saved.</div><?php endif; ?>

  <div style="margin:10px 0 18px;">
    <?php if ($CAN_EDIT): ?>
      <form method="post" style="display:inline;" onsubmit="return confirm('Clear ALL entries?');">
        <input type="hidden" name="bulk_action" value="clear">
        <button class="admin-btn" type="submit">Clear All</button>
      </form>
    <?php endif; ?>
    <a class="admin-btn" href="/admin/index.php">Back</a>
  </div>

  <div class="content-card" style="text-align:left;">
    <h3 style="margin-top:0;">Expected format (from site forms)</h3>
    <pre style="white-space:pre-wrap;opacity:.9;margin:0;">Name: ...\nEmail: ...\nSong: ...\nArtist: ...\nDedication: ...\n---</pre>
  </div>

  <?php if (empty($items)): ?>
    <p>No entries yet.</p>
  <?php else: ?>
    <?php foreach ($items as $i => $item): ?>
      <div class="content-card" style="text-align:left;">
        <?php $k = smurf_req_key($item); $meta = $statusMap[$k] ?? ['status'=>'Pending','note'=>'']; ?>
        <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
          <strong>#<?= $i ?></strong>
          <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <span style="opacity:.85;padding:3px 10px;border:1px solid rgba(255,215,120,.4);border-radius:999px;">Status: <b><?= htmlspecialchars($meta['status'] ?? 'Pending') ?></b></span>
            <?php if ($CAN_EDIT): ?>
              <form method="post" style="display:inline;" onsubmit="return confirm('Delete this entry?');">
                <input type="hidden" name="bulk_action" value="delete">
                <input type="hidden" name="bulk_index" value="<?= $i ?>">
                <button class="admin-btn" type="submit">Delete</button>
              </form>
            <?php endif; ?>
          </div>
        </div>

        <pre style="white-space:pre-wrap;margin:10px 0 0;opacity:.95;"><?= smurf_h($item['_raw'] ?? '') ?></pre>
      </div>
      <?php if ($CAN_EDIT): ?>
        <form method="post" action="/admin/requests.php" style="margin-top:10px;display:grid;gap:10px;grid-template-columns:160px 1fr auto;align-items:end;">
          <input type="hidden" name="set_status" value="1">
          <input type="hidden" name="k" value="<?= htmlspecialchars($k) ?>">
          <div>
            <label style="display:block;font-size:.9em;opacity:.9;margin-bottom:4px;">Update status</label>
            <select name="status" class="admin-input">
              <?php foreach (['Pending','Accepted','Played','Rejected'] as $opt): ?>
                <option value="<?= $opt ?>" <?= (($meta['status'] ?? 'Pending')===$opt?'selected':'') ?>><?= $opt ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label style="display:block;font-size:.9em;opacity:.9;margin-bottom:4px;">DJ Note</label>
            <input type="text" name="note" value="<?= htmlspecialchars($meta['note'] ?? '') ?>" class="admin-input" placeholder="e.g. Played at 8:15pm 🎶">
          </div>
          <button class="admin-btn" type="submit">Save</button>
        </form>
      <?php endif; ?>
    <?php endforeach; ?>
  <?php endif; ?>
</section>

<?php include __DIR__ . '/includes/admin_footer.php'; ?>
