<?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 ($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/contact.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/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; display:flex; gap:10px; flex-wrap:wrap;">
    <?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;">
    <?php if (empty($items)): ?>
      <p>No contact messages yet.</p>
    <?php else: ?>
      <?php foreach ($items as $n => $item): ?>
        <div class="content-card" style="text-align:left; margin-bottom:14px;">
          <div style="display:flex; justify-content:space-between; gap:12px; align-items:flex-start; flex-wrap:wrap;">
            <div style="flex:1; min-width:280px;">
              <h3 style="margin:0 0 8px;"><?= smurf_h((string)($item['Name'] ?? 'Unknown')) ?></h3>
              <?php if (!empty($item['Email'])): ?><div><strong>Email:</strong> <?= smurf_h((string)$item['Email']) ?></div><?php endif; ?>
              <?php if (!empty($item['Subject'])): ?><div><strong>Subject:</strong> <?= smurf_h((string)$item['Subject']) ?></div><?php endif; ?>
              <?php if (!empty($item['Message'])): ?><div style="margin-top:10px;"><?= nl2br(smurf_h((string)$item['Message'])) ?></div><?php endif; ?>
            </div>
            <?php if ($CAN_EDIT): ?>
              <div><a class="admin-btn" href="/admin/contact.php?action=delete&i=<?= (int)$n ?>" onclick="return confirm('Delete this message?');">Delete</a></div>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
