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


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

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

if ($action === 'delete' && $idx >= 0) {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to delete entries.</p>");
  smurf_delete_block($file, $idx);
  header("Location: /admin/contact.php");
  exit;
}

if ($action === 'clear') {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to clear entries.</p>");
  smurf_clear_file($file);
  header("Location: /admin/contact.php");
  exit;
}

$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>

  <div style="margin:10px 0 18px;">
    <?php if ($CAN_EDIT): ?>
      <a class="admin-btn" href="/admin/contact.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;">
    <h3 style="margin-top:0;">Expected format (from site forms)</h3>
    <pre style="white-space:pre-wrap;opacity:.9;margin:0;">Name: ...\nEmail: ...\nSubject: ...\nMessage: ...\n---</pre>
  </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): ?>
            <a class="admin-btn" href="/admin/contact.php?action=delete&i=<?= $i ?>" onclick="return confirm('Delete this entry?');">Delete</a>
          <?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'; ?>
