<?php include('../header.php'); ?>
<?php include('../menu.php'); ?>
<link rel="stylesheet" href="../css/style.css?v=1">

<main class="main-container">
  <section class="schedule-preview">
    <h2 class="text-warning">📰 Station News</h2>
    <p class="mb-4">Catch the latest updates, show announcements, and thunderous happenings from the mountain.</p>

    <?php
      $newsFile = '../data/news.txt';
      $pinnedFile = '../data/news_pinned.txt';

      $entries = file_exists($newsFile) ? explode("---\n", file_get_contents($newsFile)) : [];
      $pinned = file_exists($pinnedFile) ? explode("\n", trim(file_get_contents($pinnedFile))) : [];

      $newsItems = [];

      foreach ($entries as $index => $entry) {
        $lines = explode("\n", trim($entry));
        if (count($lines) < 1) continue;

        $title = array_shift($lines);
        $body = implode("\n", $lines);
        if (trim($title) === '' && trim($body) === '') continue;

        $meta = ['tag' => '', 'author' => '', 'date' => ''];
        if (preg_match_all('/

\[(tag|author|date):([^\]

]+)\]

/i', $body, $matches)) {
          foreach ($matches[1] as $i => $key) {
            $meta[strtolower($key)] = trim($matches[2][$i]);
          }
        }

        $newsItems[] = [
          'title' => $title,
          'body' => $body,
          'meta' => $meta,
          'pinned' => in_array((string)$index, $pinned)
        ];
      }

      // Show pinned first
      usort($newsItems, fn($a, $b) => $b['pinned'] <=> $a['pinned']);
    ?>

    <?php if (!empty($newsItems)): ?>
      <?php foreach ($newsItems as $item): ?>
        <div class="news-card mb-4 <?= $item['pinned'] ? 'pinned' : '' ?>">
          <h4 class="text-warning"><?= $item['pinned'] ? '📌 ' : '' ?><?= htmlspecialchars($item['title']) ?></h4>
          <p><?= nl2br(htmlspecialchars($item['body'])) ?></p>
          <small class="text-muted">
            <?php if ($item['meta']['tag']): ?>🏷️ Tag: <?= htmlspecialchars($item['meta']['tag']) ?><?php endif; ?>
            <?php if ($item['meta']['author']): ?> | ✍️ Author: <?= htmlspecialchars($item['meta']['author']) ?><?php endif; ?>
            <?php if ($item['meta']['date']): ?> | 📅 Date: <?= htmlspecialchars($item['meta']['date']) ?><?php endif; ?>
          </small>
        </div>
      <?php endforeach; ?>
    <?php else: ?>
      <div class="news-card">
        <p>No news yet. The mountain is quiet… for now.</p>
      </div>
    <?php endif; ?>
  </section>
</main>

<?php include('../footer.php'); ?>
