<?php
require_once __DIR__ . '/../includes/redirect_helper.php';
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/../includes/auth.php';
requireRole(['master','admin','dj']);

$comments_file = __DIR__ . '/../data/comments.json';
$comments = file_exists($comments_file) ? json_decode((string)file_get_contents($comments_file), true) : [];
if (!is_array($comments)) $comments = [];

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

  if ($action === 'clear_all') {
    $comments = [];
  } elseif ($action === 'approve' && isset($comments[$index])) {
    $comments[$index]['approved'] = true;
  } elseif ($action === 'unapprove' && isset($comments[$index])) {
    $comments[$index]['approved'] = false;
  } elseif ($action === 'delete' && isset($comments[$index])) {
    array_splice($comments, $index, 1);
  } elseif ($action === 'reply' && isset($comments[$index])) {
    $comments[$index]['reply'] = trim((string)($_POST['reply'] ?? ''));
  }

  file_put_contents($comments_file, json_encode(array_values($comments), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
  ah_redirect_back('/admin/comments.php', ['saved' => 1]);
}
?>
<?php include __DIR__ . '/../header.php'; ?>
<?php include __DIR__ . '/../menu.php'; ?>
<link rel="stylesheet" href="/css/style.css?v=1">

<main class="main-container">
  <section class="admin-card">
    <h2 class="text-warning mb-4">💬 Manage Comments</h2>

    <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 comments? This cannot be undone.');">
        <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/admin/comments.php') ?>">
        <button type="submit" name="action" value="clear_all" class="btn btn-danger btn-sm">Clear All Comments</button>
      </form>
    </div>

    <?php if (!empty($_GET['saved'])): ?>
      <div class="alert alert-success mb-3">Comments updated.</div>
    <?php endif; ?>

    <?php if (!empty($comments)): ?>
      <div class="comments-grid">
        <?php foreach ($comments as $i => $comment): ?>
          <div class="admin-comment-card mb-4">
            <h4><?= htmlspecialchars((string)($comment['name'] ?? 'Guest')) ?></h4>
            <p><?= nl2br(htmlspecialchars((string)($comment['message'] ?? ''))) ?></p>
            <em class="text-muted">(<?= htmlspecialchars((string)($comment['timestamp'] ?? '')) ?>)</em>
            <p>Status: <?= !empty($comment['approved']) ? '✅ Approved' : '⏳ Pending' ?></p>

            <?php if (!empty($comment['reply'])): ?>
              <div class="admin-comment-reply mt-2"><strong>Reply:</strong> <?= nl2br(htmlspecialchars((string)$comment['reply'])) ?></div>
            <?php endif; ?>

            <?php if (empty($comment['approved'])): ?>
              <form method="post" class="d-inline">
                <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/admin/comments.php') ?>">
                <input type="hidden" name="index" value="<?= $i ?>">
                <button type="submit" name="action" value="approve" class="btn btn-warning btn-sm">Approve</button>
              </form>
            <?php else: ?>
              <form method="post" class="d-inline">
                <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/admin/comments.php') ?>">
                <input type="hidden" name="index" value="<?= $i ?>">
                <button type="submit" name="action" value="unapprove" class="btn btn-secondary btn-sm">Unapprove</button>
              </form>
            <?php endif; ?>

            <form method="post" class="d-inline">
              <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/admin/comments.php') ?>">
              <input type="hidden" name="index" value="<?= $i ?>">
              <button type="submit" name="action" value="delete" class="btn btn-danger btn-sm">Delete</button>
            </form>

            <form method="post" class="mt-2">
              <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/admin/comments.php') ?>">
              <input type="hidden" name="index" value="<?= $i ?>">
              <textarea name="reply" class="form-control mb-2" placeholder="Write a reply..."><?= htmlspecialchars((string)($comment['reply'] ?? '')) ?></textarea>
              <button type="submit" name="action" value="reply" class="btn btn-info btn-sm">Save Reply</button>
            </form>
          </div>
        <?php endforeach; ?>
      </div>
    <?php else: ?>
      <p>No comments yet.</p>
    <?php endif; ?>
  </section>
</main>

<?php include __DIR__ . '/../footer.php'; ?>
