<?php include 'includes/header.php'; ?>
<?php include 'includes/menu.php'; ?>

<?php
$contactFile = __DIR__ . '/data/contact_messages.txt';
$legacyContactFile = __DIR__ . '/data/contact.txt';
if ((!file_exists($contactFile) || trim((string)@file_get_contents($contactFile)) === '') && file_exists($legacyContactFile) && trim((string)@file_get_contents($legacyContactFile)) !== '') {
  @file_put_contents($contactFile, (string)file_get_contents($legacyContactFile), LOCK_EX);
}
?>

<div class="container mt-5">
  <div class="content-box">
    <h2>📞 Contact Thunder Mountain Radio</h2>
    <p class="mb-4">Got feedback, questions, or just want to say hi? Drop us a message below and we’ll get back to you when the thunder settles.</p>

    <?php if (!empty($_GET['sent'])): ?>
      <div class="alert alert-success mb-3">Your message has been sent.</div>
    <?php endif; ?>

    <form method="POST" action="send_contact.php">
      <input type="text" name="name" class="form-control mb-3" placeholder="Your name" required>
      <input type="email" name="email" class="form-control mb-3" placeholder="Your email" required>
      <textarea name="message" class="form-control mb-3" placeholder="Your message" required></textarea>
      <button type="submit" class="btn btn-primary">Send Message</button>
    </form>
  </div>

  <div class="content-box mt-5">
    <h4>📬 Recent Messages</h4>
    <?php
    if (file_exists($contactFile)) {
      $entries = array_filter(explode("---
", (string)file_get_contents($contactFile)));
      $recent = array_slice(array_reverse($entries), 0, 3);
      foreach ($recent as $entry) {
        $parts = array_map('trim', explode('|', trim($entry), 4));
        if (count($parts) === 4) {
          [$timestamp, $name, $email, $message] = $parts;
          echo "<div class='comment-box'>";
          echo "<strong>" . htmlspecialchars($name) . "</strong> <em>[" . htmlspecialchars($timestamp) . "]</em><br>";
          echo "<small>" . htmlspecialchars($email) . "</small><br>";
          echo nl2br(htmlspecialchars($message));
          echo "</div>";
        }
      }
      if (empty($recent)) echo "<p>No messages yet. Be the first to reach out!</p>";
    } else {
      echo "<p>No messages yet. Be the first to reach out!</p>";
    }
    ?>
  </div>
</div>

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