<?php
session_start();
require __DIR__ . '/auth.php';
require __DIR__ . '/includes/admin_lib.php';


$file = __DIR__ . '/../data/contact_messages.txt';

$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']);
}


$items = smurf_parse_blocks($file);
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">📨 Contact Messages</h1>
  <p style="opacity:.8;">File: <code>/data/contact_messages.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>
  <?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;">
        <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;">
          <strong>#<?= $i ?></strong>
          <?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>

        <pre style="white-space:pre-wrap;margin:10px 0 0;opacity:.95;"><?= smurf_h($item['_raw'] ?? '') ?></pre>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</section>

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