<?php
require_once __DIR__ . '/../includes/redirect_helper.php';
session_start();
$role = $_SESSION['role'] ?? 'guest';
if (!in_array($role, ['master','admin'])) {
  header('Location: /login/index.php');
  exit;
}

$requests_file = __DIR__ . '/../data/requests.json';
$requests = file_exists($requests_file) ? json_decode(file_get_contents($requests_file), true) : [];

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  $index = (int)($_POST['index'] ?? -1);

  if ($action === 'clear_all') {
    $requests = [];
  }
  if ($action === 'approve' && isset($requests[$index])) {
    $requests[$index]['approved'] = true;
  }
  if ($action === 'delete' && isset($requests[$index])) {
    array_splice($requests, $index, 1);
  }
  if ($action === 'reply' && isset($requests[$index])) {
    $requests[$index]['reply'] = trim($_POST['reply']);
  }

  file_put_contents($requests_file, json_encode(array_values($requests), JSON_PRETTY_PRINT));
  ah_redirect_back('/admin/requests.php', ['saved' => 1]);
}
?>

<?php include('../header.php'); ?>
<?php include('../menu.php'); ?>
<link rel="stylesheet" href="../css/style.css?v=1">

<main class="main-container">
  <section class="admin-card">
    <div class="d-flex flex-wrap gap-2 mb-3">
      <a href="/admin/dashboard.php" class="btn btn-dark btn-sm">← Return to Admin Dashboard</a>
      <a href="/index.php" class="btn btn-dark btn-sm">🏠 Return to Main Site</a>
      <a href="/login/logout.php" class="btn btn-dark btn-sm">Logout</a>
      <form method="post" class="d-inline" onsubmit="return confirm('Clear all requests? This cannot be undone.');">
        <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/admin/requests.php') ?>">
        <button type="submit" name="action" value="clear_all" class="btn btn-danger btn-sm">Clear All Requests</button>
      </form>
    </div>
    <h2 class="text-warning">📻 Manage Song Requests</h2>

    <?php if (!empty($requests)): ?>
      <div class="requests-grid">
        <?php foreach ($requests as $i => $req): ?>
          <div class="admin-request-card mb-4">
            <h4><?= htmlspecialchars($req['name']) ?></h4>
            <p><strong>Song:</strong> <?= htmlspecialchars($req['song']) ?></p>
            <p><?= nl2br(htmlspecialchars($req['message'])) ?></p>
            <em class="text-muted">(<?= htmlspecialchars($req['timestamp']) ?>)</em>

            <?php if (!empty($req['reply'])): ?>
              <p class="mt-2"><strong>Reply:</strong> <?= htmlspecialchars($req['reply']) ?></p>
            <?php endif; ?>

            <form method="POST" class="admin-form mt-3">
              <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/admin/requests.php') ?>">
              <input type="hidden" name="index" value="<?= $i ?>">
              <div class="form-actions">
                <button type="submit" name="action" value="approve" class="btn btn-warning btn-sm">✅ Approve</button>
                <button type="submit" name="action" value="delete" class="btn btn-danger btn-sm">🗑 Delete</button>
              </div>
              <input type="text" name="reply" placeholder="Reply..." class="admin-input mb-2">
              <button type="submit" name="action" value="reply" class="btn btn-dark btn-sm">💬 Reply</button>
            </form>
          </div>
        <?php endforeach; ?>
      </div>
    <?php else: ?>
      <p class="text-muted">No song requests yet. The mountain is quiet…</p>
    <?php endif; ?>
  </section>
</main>

<?php include('../footer.php'); ?>
