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

$slug = isset($_GET['slug']) ? $_GET['slug'] : '';
$news = $slug ? get_news_by_slug($slug) : null;

if (!$news) {
    http_response_code(404);
    $page_title = 'Story not found | ' . SITE_NAME;
    require __DIR__ . '/includes/header.php';
    echo '<div class="container empty-state"><h1>Story not found</h1><p>This update may have been removed. <a class="btn btn-primary" href="'.SITE_URL.'/news.php">Browse all news</a></p></div>';
    require __DIR__ . '/includes/footer.php';
    exit;
}

$page_title = $news['title'] . ' | ' . SITE_NAME;
$page_description = mb_strimwidth(strip_tags($news['summary']), 0, 155, '...');
$page_url = SITE_URL . '/news-detail.php?slug=' . $news['slug'];
$page_type = 'article';
$page_image = $news['image'] ?: (SITE_URL . '/assets/icons/icon-512.png');

$json_ld = json_encode([
    "@context" => "https://schema.org",
    "@type" => "NewsArticle",
    "headline" => $news['title'],
    "description" => $page_description,
    "datePublished" => date('c', strtotime($news['published_at'])),
    "image" => [$page_image],
    "author" => ["@type" => "Organization", "name" => $news['source'] ?: SITE_NAME],
    "publisher" => ["@type" => "Organization", "name" => SITE_NAME],
    "mainEntityOfPage" => $page_url
], JSON_UNESCAPED_SLASHES);

require __DIR__ . '/includes/header.php';

$related = get_latest_news(4, 0);
?>
<article class="article-wrap">
  <span class="tag"><?= e($news['source']) ?></span>
  <h1><?= e($news['title']) ?></h1>
  <div class="article-meta">
    <time><?= e(time_ago($news['published_at'])) ?></time>
    <span>&middot;</span>
    <span>Source: <?= e($news['source']) ?></span>
  </div>

  <div class="ad-slot">
    <?php if (ADSENSE_CLIENT_ID): ?>
      <ins class="adsbygoogle" style="display:block" data-ad-client="<?= e(ADSENSE_CLIENT_ID) ?>" data-ad-slot="<?= e(ADSENSE_SLOT_INARTICLE) ?>" data-ad-format="auto" data-full-width-responsive="true"></ins>
      <script>(adsbygoogle = window.adsbygoogle || []).push({});</script>
    <?php else: ?>
      Ad slot — in-article unit
    <?php endif; ?>
  </div>

  <div class="article-body">
    <p><?= nl2br(e($news['summary'])) ?></p>
  </div>

  <a class="source-link" href="<?= e($news['link']) ?>" target="_blank" rel="noopener nofollow">Read full story at <?= e($news['source']) ?> &rarr;</a>
</article>

<section class="container section">
  <div class="section-head"><h2>More Game Updates</h2></div>
  <div class="news-grid">
    <?php foreach ($related as $n): if ($n['slug'] === $news['slug']) continue; ?>
    <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>
      <div class="meta"><time><?= e(time_ago($n['published_at'])) ?></time></div>
    </a>
    <?php endforeach; ?>
  </div>
</section>
<?php require __DIR__ . '/includes/footer.php'; ?>
