<?php
require_once __DIR__ . '/includes/functions.php';

$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$page = get_page_num();
$total = count_news($q);
$total_pages = max(1, (int)ceil($total / NEWS_PER_PAGE));
$page = min($page, $total_pages);
$offset = ($page - 1) * NEWS_PER_PAGE;
$items = get_latest_news(NEWS_PER_PAGE, $offset, $q);

$page_title = ($q ? 'Search: ' . $q . ' - ' : '') . 'Online Game News & Updates | ' . SITE_NAME;
$page_description = 'Browse the latest online, mobile and multiplayer game news, patch notes and esports updates. Fresh stories added automatically every day.';
$page_url = SITE_URL . '/news.php' . ($q ? '?q=' . urlencode($q) : '');

require __DIR__ . '/includes/header.php';
?>
<section class="container section">
  <div class="section-head">
    <h1 style="font-size:1.8rem;margin:0">Online Game News &amp; Updates</h1>
  </div>
  <div class="games-toolbar">
    <form action="<?= SITE_URL ?>/news.php" method="get">
      <input type="text" name="q" placeholder="Search news e.g. Free Fire update, esports..." value="<?= e($q) ?>">
      <button class="btn btn-primary" type="submit">Search</button>
    </form>
  </div>

  <?php if ($items): ?>
  <div class="news-grid">
    <?php foreach ($items as $n): ?>
    <a class="card" href="<?= SITE_URL ?>/news-detail.php?slug=<?= e($n['slug']) ?>">
      <span class="tag"><?= e($n['source']) ?></span>
      <h3><?= e($n['title']) ?></h3>
      <p><?= e(mb_strimwidth(strip_tags($n['summary']), 0, 140, '...')) ?></p>
      <div class="meta"><time><?= e(time_ago($n['published_at'])) ?></time></div>
    </a>
    <?php endforeach; ?>
  </div>
  <?= paginate_links($page, $total_pages, SITE_URL . '/news.php', $q ? ['q' => $q] : []) ?>
  <?php else: ?>
  <div class="empty-state">
    <p>No news found<?= $q ? ' for "' . e($q) . '"' : '' ?>. New updates are fetched automatically — check back soon.</p>
  </div>
  <?php endif; ?>
</section>
<?php require __DIR__ . '/includes/footer.php'; ?>
