<?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(string $block): string { return sha1($block); }

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

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;
}

if ($action === 'delete' && $idx >= 0) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to delete entries.');
  smurf_delete_block($file, $idx);
  header('Location: /admin/requests.php');
  exit;
}

if ($action === 'clear') {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to clear entries.');
  smurf_clear_file($file);
  smurf_write_json($statusFile, []);
  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>

  <div style="margin:10px 0 18px; display:flex; gap:10px; flex-wrap:wrap;">
    <?php if ($CAN_EDIT): ?>
      <a class="admin-btn" href="/admin/requests.php?action=clear" onclick="return confirm('Clear ALL entries?');">Clear All</a>
    <?php endif; ?>
    <a class="admin-btn" href="/admin/index.php">Back</a>
  </div>

  <div class="content-card" style="text-align:left;">
    <?php if (empty($items)): ?>
      <p>No requests yet.</p>
    <?php else: ?>
      <?php foreach ($items as $n => $item): $k = smurf_req_key((string)($item['_raw'] ?? '')); $meta = $statusMap[$k] ?? ['status'=>'Pending','note'=>'']; ?>
        <div class="content-card" style="text-align:left; margin-bottom:14px;">
          <div style="display:flex; justify-content:space-between; gap:14px; align-items:flex-start; flex-wrap:wrap;">
            <div style="flex:1; min-width:320px;">
              <h3 style="margin:0 0 8px;"><?= smurf_h((string)($item['Name'] ?? 'Listener')) ?></h3>
              <?php if (!empty($item['Email'])): ?><div><strong>Email:</strong> <?= smurf_h((string)$item['Email']) ?></div><?php endif; ?>
              <?php if (!empty($item['Song'])): ?><div><strong>Song:</strong> <?= smurf_h((string)$item['Song']) ?></div><?php endif; ?>
              <?php if (!empty($item['Artist'])): ?><div><strong>Artist:</strong> <?= smurf_h((string)$item['Artist']) ?></div><?php endif; ?>
              <?php if (!empty($item['Dedication'])): ?><div style="margin-top:10px;"><strong>Dedication:</strong><br><?= nl2br(smurf_h((string)$item['Dedication'])) ?></div><?php endif; ?>
              <?php if (!empty($meta['note'])): ?><div style="margin-top:10px; opacity:.85;"><strong>Admin note:</strong> <?= smurf_h((string)$meta['note']) ?></div><?php endif; ?>
            </div>
            <div style="min-width:260px;">
              <div style="margin-bottom:10px;"><strong>Status:</strong> <?= smurf_h((string)($meta['status'] ?? 'Pending')) ?></div>
              <?php if ($CAN_EDIT): ?>
              <form method="post" action="/admin/requests.php" style="display:grid; gap:8px;">
                <input type="hidden" name="set_status" value="1">
                <input type="hidden" name="k" value="<?= smurf_h($k) ?>">
                <select class="input-field" name="status">
                  <?php foreach (['Pending','Accepted','Played','Declined'] as $status): ?>
                    <option value="<?= smurf_h($status) ?>" <?= (($meta['status'] ?? 'Pending') === $status) ? 'selected' : '' ?>><?= smurf_h($status) ?></option>
                  <?php endforeach; ?>
                </select>
                <input class="input-field" type="text" name="note" value="<?= smurf_h((string)($meta['note'] ?? '')) ?>" placeholder="Optional admin note">
                <div style="display:flex; gap:8px; flex-wrap:wrap;">
                  <button class="admin-btn" type="submit">Save Status</button>
                  <a class="admin-btn" href="/admin/requests.php?action=delete&i=<?= (int)$n ?>" onclick="return confirm('Delete this request?');">Delete</a>
                </div>
              </form>
              <?php endif; ?>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
