<?php
session_start();
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.php';

// Folder where news posts are stored
$newsDir = __DIR__ . '/data/news/';

// Get all JSON files
$files = glob($newsDir . '*.json');

// Sort newest first
rsort($files);
?>

<main class="content-area">

    <div class="smurf-divider"></div>

    <div class="content-wrapper">
        <section class="content-card center-text">
            <h1>📰 Latest News</h1>
            <p>Updates, stories, and announcements from Smurfette’s Country Delights</p>
        </section>
    </div>

    <div class="smurf-divider"></div>

    <?php if (empty($files)): ?>

        <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: ?>

        <?php foreach ($files as $file): 
            $json = json_decode(file_get_contents($file), true);

            $title   = htmlspecialchars($json['title']);
            $author  = htmlspecialchars($json['author']);
            $date    = htmlspecialchars($json['date']);
            $tag     = htmlspecialchars($json['tag']);
            $content = nl2br(htmlspecialchars($json['content']));
            $image   = !empty($json['image']) ? '/img/content/' . htmlspecialchars($json['image']) : '';
        ?>

            <div class="smurf-divider"></div>

            <div class="content-wrapper">
                <section class="content-card news-post">

                    <?php if ($image): ?>
                        <div class="news-image">
                            <img src="<?= $image ?>" alt="News Image">
                        </div>
                    <?php endif; ?>

                    <h2 class="news-title"><?= $title ?></h2>

                    <div class="news-meta">
                        <span class="news-author">👤 <?= $author ?></span>
                        <span class="news-date">📅 <?= $date ?></span>
                        <span class="news-tag">🏷️ <?= $tag ?></span>
                    </div>

                    <div class="news-content">
                        <?= $content ?>
                    </div>

                </section>
            </div>

            <div class="smurf-divider"></div>

        <?php endforeach; ?>

    <?php endif; ?>

</main>

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