<?php
session_start();
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.php';
$posts = [];
$newsDir = __DIR__ . '/data/news/';
$files = glob($newsDir . '*.json') ?: [];
rsort($files);
foreach ($files as $file) {
  $json = json_decode((string)file_get_contents($file), true);
  if (!is_array($json) || empty($json['published'])) continue;
  $image = trim((string)($json['image'] ?? ''));
  if ($image !== '' && !preg_match('~^(https?:)?//~i', $image) && strpos($image, '/img/') !== 0) $image = 'img/content/' . ltrim($image, '/');
  $posts[] = [
    'title'=>(string)($json['title'] ?? ''),
    'author'=>(string)($json['author'] ?? ''),
    'date'=>(string)($json['date'] ?? ''),
    'tag'=>(string)($json['tag'] ?? ''),
    'content'=>(string)($json['content'] ?? ''),
    'image'=>$image,
    'featured'=>!empty($json['featured_home'])
  ];
}
$legacyFile = __DIR__ . '/data/news.txt';
$pinned = file_exists(__DIR__ . '/data/news_pinned.txt') ? array_filter(array_map('trim', file(__DIR__ . '/data/news_pinned.txt'))) : [];
if (file_exists($legacyFile)) {
  $raw = trim((string)file_get_contents($legacyFile));
  if ($raw !== '') {
    $entries = preg_split("/\n---\s*\n/", $raw);
    foreach (array_reverse($entries) as $idx => $entry) {
      $entry = trim($entry); if ($entry === '') continue;
      $lines = preg_split("/\R/", $entry);
      $title = trim((string)array_shift($lines));
      $body = trim(implode("\n", $lines));
      if ($title === '' && $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]);
      }
      $cleanBody = preg_replace('/\s*\[(tag|author|date):[^\]]+\]\s*/i', ' ', $body);
      $posts[] = ['title'=>$title,'author'=>$meta['author'],'date'=>$meta['date'],'tag'=>$meta['tag'],'content'=>trim($cleanBody),'image'=>'','featured'=>in_array((string)$idx,$pinned,true)];
    }
  }
}
?>
<main class="content-area">
  <div class="content-wrapper page-shell">
    <section class="content-card center-text">
      <div class="page-intro">
        <h1>📰 Station News</h1>
        <p>Catch the latest updates, show announcements, and thunderous happenings from the mountain.</p>
      </div>
      <?php if (empty($posts)): ?>
        <p>No news yet. Stay tuned.</p>
      <?php else: ?>
        <?php foreach ($posts as $post): ?>
          <div class="content-card" style="margin-top:18px;text-align:left;">
            <h3><?= !empty($post['featured']) ? '📌 ' : '' ?><?= htmlspecialchars($post['title']) ?></h3>
            <?php if (!empty($post['image'])): ?><p><img src="<?= htmlspecialchars($post['image']) ?>" alt="News image" style="max-width:220px;width:100%;height:auto;border-radius:12px;"></p><?php endif; ?>
            <p class="small text-muted mb-2">
              <?php if ($post['author'] !== ''): ?>By <?= htmlspecialchars($post['author']) ?><?php endif; ?>
              <?php if ($post['date'] !== ''): ?><?= $post['author'] !== '' ? ' • ' : '' ?><?= htmlspecialchars($post['date']) ?><?php endif; ?>
              <?php if ($post['tag'] !== ''): ?><?= ($post['author'] !== '' || $post['date'] !== '') ? ' • ' : '' ?><?= htmlspecialchars($post['tag']) ?><?php endif; ?>
            </p>
            <p><?= nl2br(htmlspecialchars($post['content'])) ?></p>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </section>
  </div>
</main>
<?php include __DIR__ . '/includes/footer.php'; ?>
