<?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;
    $imageVal = trim((string)($json['image'] ?? ''));
    $image = '';
    if ($imageVal !== '') {
        if (preg_match('~^(https?:)?//~i', $imageVal) || strpos($imageVal, '/img/') === 0) $image = $imageVal;
        else $image = '/img/content/' . ltrim($imageVal, '/');
    }
    $posts[] = ['type'=>'json','title'=>(string)($json['title'] ?? ''),'author'=>(string)($json['author'] ?? ''),'date'=>(string)($json['date'] ?? ''),'tag'=>(string)($json['tag'] ?? ''),'content'=>(string)($json['content'] ?? ''),'image'=>$image];
}
$legacyFile = __DIR__ . '/data/news.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 $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[] = ['type'=>'legacy','title'=>$title,'author'=>$meta['author'],'date'=>$meta['date'],'tag'=>$meta['tag'],'content'=>trim($cleanBody),'image'=>''];
    }
  }
}
?>
<main class="content-area">
  <div class="smurf-divider"></div>
  <div class="content-wrapper"><section class="content-card center-text"><h1>📰 Station News</h1><p>Catch the latest updates, show announcements, and thunderous happenings from the mountain.</p></section></div>
  <div class="smurf-divider"></div>
  <?php if (empty($posts)): ?>
    <div class="content-wrapper"><section class="content-card center-text"><p>No news posts available.</p></section></div><div class="smurf-divider"></div>
  <?php else: foreach ($posts as $post): ?>
    <div class="content-wrapper"><section class="content-card news-post" style="text-align:left;"><div style="display:flex;gap:18px;align-items:flex-start;flex-wrap:wrap;"><?php if (!empty($post['image'])): ?><div class="news-image" style="flex:0 0 auto;"><img src="<?= htmlspecialchars($post['image'], ENT_QUOTES, 'UTF-8') ?>" alt="News Image" style="width:140px;height:180px;object-fit:cover;border-radius:14px;display:block;"></div><?php endif; ?><div style="flex:1 1 320px;min-width:0;"><h2 class="news-title"><?= htmlspecialchars($post['title'], ENT_QUOTES, 'UTF-8') ?></h2><div class="news-meta"><?php if ($post['author'] !== ''): ?><span class="news-author">👤 <?= htmlspecialchars($post['author'], ENT_QUOTES, 'UTF-8') ?></span><?php endif; ?><?php if ($post['date'] !== ''): ?><span class="news-date">📅 <?= htmlspecialchars($post['date'], ENT_QUOTES, 'UTF-8') ?></span><?php endif; ?><?php if ($post['tag'] !== ''): ?><span class="news-tag">🏷️ <?= htmlspecialchars($post['tag'], ENT_QUOTES, 'UTF-8') ?></span><?php endif; ?></div><div class="news-content"><?= nl2br(htmlspecialchars($post['content'], ENT_QUOTES, 'UTF-8')) ?></div></div></div></section></div><div class="smurf-divider"></div>
  <?php endforeach; endif; ?>
</main>
<?php include __DIR__ . '/includes/footer.php'; ?>
