<?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);
  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;">
    <?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;">

</section>

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