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

<?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))) : [];

$filterTag = isset($_GET['tag']) ? strtolower(trim($_GET['tag'])) : '';
$filterAuthor = isset($_GET['author']) ? strtolower(trim($_GET['author'])) : '';
$filterDate = isset($_GET['date']) ? trim($_GET['date']) : '';

$filteredEntries = [];

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)] = strtolower(trim($matches[2][$i]));
    }
  }

  if ($filterTag && $meta['tag'] !== $filterTag) continue;
  if ($filterAuthor && $meta['author'] !== $filterAuthor) continue;
  if ($filterDate && $meta['date'] !== $filterDate) continue;

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

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$perPage = 5;
$offset = ($page - 1) * $perPage;
$totalPages = ceil(count($filteredEntries) / $perPage);
$visibleEntries = array_slice($filteredEntries, $offset, $perPage);
?>

<div class="container mt-5">
  <div class="content-box">
    <h2>📰 Station News</h2>
    <p class="mb-4">Catch the latest updates, show announcements, and thunderous happenings from the mountain.</p>

    <!-- Filter Form -->
    <form method="GET" class="mb-4">
      <div class="row g-2">
        <div class="col-md-3"><input type="text" name="tag" class="form-control" placeholder="Filter by tag" value="<?= htmlspecialchars($filterTag) ?>"></div>
        <div class="col-md-3"><input type="text" name="author" class="form-control" placeholder="Filter by author" value="<?= htmlspecialchars($filterAuthor) ?>"></div>
        <div class="col-md-3"><input type="date" name="date" class="form-control" value="<?= htmlspecialchars($filterDate) ?>"></div>
        <div class="col-md-3"><button type="submit" class="btn btn-primary w-100">Apply Filters</button></div>
      </div>
    </form>

    <?php if (!empty($visibleEntries)): ?>
      <?php foreach ($visibleEntries as $item): ?>
        <div class="mb-4 border-bottom pb-3">
          <h4 class="text-warning"><?= $item['pinned'] ? '📌 ' : '' ?><?= htmlspecialchars($item['title']) ?></h4>
          <p><?= nl2br(htmlspecialchars($item['body'])) ?></p>
        </div>
      <?php endforeach; ?>

      <!-- Page Navigation -->
      <nav class="mt-4">
        <ul class="pagination justify-content-center">
          <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <li class="page-item <?= $i === $page ? 'active' : '' ?>">
              <a class="page-link" href="?page=<?= $i ?>&tag=<?= urlencode($filterTag) ?>&author=<?= urlencode($filterAuthor) ?>&date=<?= urlencode($filterDate) ?>"><?= $i ?></a>
            </li>
          <?php endfor; ?>
        </ul>
      </nav>

      <div class="text-center mt-3">
        <a href="#top" class="btn btn-outline-secondary">⬆ Back to Top</a>
      </div>
    <?php else: ?>
      <p>No news yet. Stay tuned!</p>
    <?php endif; ?>
  </div>
</div>


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