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

$file = __DIR__ . '/../data/contact_messages.txt';
$legacyFile = __DIR__ . '/../data/contact.txt';
if ((!file_exists($file) || trim((string)@file_get_contents($file)) === '') && file_exists($legacyFile) && trim((string)@file_get_contents($legacyFile)) !== '') {
  @file_put_contents($file, (string)file_get_contents($legacyFile), LOCK_EX);
}

function almostheaven_contact_parse(string $file): array {
  if (!file_exists($file)) return [];
  $raw = trim((string)@file_get_contents($file));
  if ($raw === '') return [];
  $blocks = preg_split("/\R---\s*\R/", $raw) ?: [];
  $items = [];
  foreach ($blocks as $block) {
    $block = trim((string)$block);
    if ($block === '') continue;
    $entry = ['_raw' => $block];
    if (strpos($block, '|') !== false && strpos($block, 'Name:') === false) {
      $parts = array_map('trim', explode('|', $block, 4));
      $entry['Timestamp'] = $parts[0] ?? '';
      $entry['Name'] = $parts[1] ?? '';
      $entry['Email'] = $parts[2] ?? '';
      $entry['Message'] = $parts[3] ?? '';
    } else {
      foreach (preg_split('/\R/', $block) as $line) {
        if (strpos($line, ':') === false) continue;
        [$k,$v] = explode(':', $line, 2);
        $entry[trim($k)] = trim($v);
      }
    }
    $name = trim((string)($entry['Name'] ?? ''));
    $email = trim((string)($entry['Email'] ?? ''));
    $subject = trim((string)($entry['Subject'] ?? ''));
    $message = trim((string)($entry['Message'] ?? ''));
    if ($name === '' && $email === '' && $subject === '' && $message === '') continue;
    $entry['_key'] = md5(str_replace("\r", '', $block));
    $items[] = $entry;
  }
  return array_reverse($items);
}

function almostheaven_contact_render(array $items): string {
  $blocks = [];
  foreach (array_reverse($items) as $item) {
    $raw = trim((string)($item['_raw'] ?? ''));
    if ($raw !== '') $blocks[] = $raw;
  }
  return $blocks ? implode("\n---\n", $blocks) . "\n---\n" : '';
}

function almostheaven_contact_write_many(array $files, array $items): void {
  $payload = almostheaven_contact_render($items);
  foreach ($files as $file) {
    file_put_contents($file, $payload, LOCK_EX);
  }
}

$items = almostheaven_contact_parse($file);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to manage contact messages.</p>");
  if (isset($_POST['clear_all'])) {
    almostheaven_contact_write_many([$file, $legacyFile], []);
    header('Location: contact.php?saved=1');
    exit;
  }
  if (isset($_POST['delete_key'])) {
    $deleteKey = trim((string)($_POST['delete_key'] ?? ''));
    $items = array_values(array_filter($items, fn($item) => (string)($item['_key'] ?? '') !== $deleteKey));
    almostheaven_contact_write_many([$file, $legacyFile], $items);
    header('Location: contact.php?saved=1');
    exit;
  }
}

$items = almostheaven_contact_parse($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): ?>
      <form method="post" onsubmit="return confirm('Clear ALL entries?');" style="margin:0;">
        <input type="hidden" name="clear_all" value="1">
        <button class="admin-btn" type="submit">Clear All</button>
      </form>
    <?php endif; ?>
    <a class="admin-btn" href="index.php">Back</a>
  </div>

  <?php if (!empty($_GET['saved'])): ?><div class="msg success" style="margin-bottom:12px;">Saved.</div><?php endif; ?>

  <?php if (empty($items)): ?>
    <p>No entries yet.</p>
  <?php else: ?>
    <?php foreach ($items as $item): ?>
      <div class="content-card" style="text-align:left;">
        <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
          <strong><?= smurf_h((string)($item['Name'] ?? 'Unknown')) ?></strong>
          <?php if ($CAN_EDIT): ?>
            <form method="post" onsubmit="return confirm('Delete this entry?');" style="margin:0;">
              <input type="hidden" name="delete_key" value="<?= smurf_h((string)($item['_key'] ?? '')) ?>">
              <button class="admin-btn" type="submit">Delete</button>
            </form>
          <?php endif; ?>
        </div>
        <div style="margin-top:10px;display:grid;gap:8px;">
          <?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['Timestamp'])): ?><div><strong>Timestamp:</strong> <?= smurf_h((string)$item['Timestamp']) ?></div><?php endif; ?>
          <?php if (!empty($item['Message'])): ?><div><strong>Message:</strong><br><?= nl2br(smurf_h((string)$item['Message'])) ?></div><?php endif; ?>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
