<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once dirname(__DIR__) . '/modules/media/helpers.php';

$posts = [];
$selectedCategory = trim((string) ($_GET['category'] ?? ''));
$newsCategoryOptions = ['general', 'competition_update', 'fixture_postponement', 'fixture_reschedule', 'transfer_update', 'match_report', 'fixture_kit_confirmation'];
$newsCategoryLabel = static fn(string $category): string => match ($category) {
    'competition_update' => 'Competition update',
    'fixture_postponement' => 'Fixture postponement',
    'fixture_reschedule' => 'Fixture reschedule',
    'transfer_update' => 'Transfer update',
    'match_report' => 'Match report',
    'match_update' => 'Match update draft',
    'fixture_kit_confirmation' => 'Matchday kit confirmation',
    default => 'General',
};
$newsCategoryBadgeClass = static fn(string $category): string => match ($category) {
    'competition_update' => 'bg-info-subtle text-info-emphasis',
    'fixture_postponement' => 'bg-warning-subtle text-warning-emphasis',
    'fixture_reschedule' => 'bg-primary-subtle text-primary-emphasis',
    'transfer_update' => 'bg-success-subtle text-success-emphasis',
    'match_report' => 'badge-soft-success',
    'match_update' => 'bg-secondary-subtle text-secondary-emphasis',
    'fixture_kit_confirmation' => 'bg-dark-subtle text-dark-emphasis',
    default => 'text-bg-light',
};
$publicCategories = [
    '' => 'All news',
    'competition_update' => 'Competition updates',
    'match_report' => 'Match reports',
    'fixture_kit_confirmation' => 'Matchday kits',
    'fixture_postponement' => 'Fixture postponements',
    'fixture_reschedule' => 'Fixture reschedules',
    'transfer_update' => 'Transfers',
];

try {
    $sql = 'SELECT title, slug, category, fixture_id, published_at, created_at, body, featured_image
            FROM news_posts
            WHERE status = :status';
    $params = ['status' => 'published'];

    if ($selectedCategory !== '' && in_array($selectedCategory, $newsCategoryOptions, true)) {
        $sql .= ' AND category = :category';
        $params['category'] = $selectedCategory;
    }

    $sql .= ' ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20';
    $posts = db_fetch_all($sql, $params);
} catch (Throwable) {
}

render_public_page('News', 'Published league updates, announcements, and competition stories.', static function () use ($posts, $publicCategories, $selectedCategory, $newsCategoryBadgeClass, $newsCategoryLabel): void {
?>
    <section class="panel-card mb-3">
        <div class="d-flex flex-wrap gap-2">
            <?php foreach ($publicCategories as $categoryKey => $categoryLabel): ?>
                <a class="btn <?php echo $selectedCategory === $categoryKey ? 'btn-jlfc' : 'btn-outline-jlfc'; ?> btn-sm" href="<?php echo e(base_url('app/public/news.php' . ($categoryKey !== '' ? '?category=' . urlencode($categoryKey) : ''))); ?>"><?php echo e($categoryLabel); ?></a>
            <?php endforeach; ?>
        </div>
    </section>
    <section class="row g-3">
        <?php if ($posts === []): ?>
            <div class="col-12">
                <div class="panel-card">
                    <p class="text-muted mb-0">No published news posts are available yet.</p>
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($posts as $post): ?>
                <?php $postUrl = absolute_url('app/public/news-details.php?slug=' . urlencode((string) $post['slug'])); ?>
                <?php $postShareTitle = (string) $post['title']; ?>
                <?php $postWhatsAppShareUrl = 'https://wa.me/?text=' . rawurlencode($postShareTitle . ' ' . $postUrl); ?>
                <?php $postFacebookShareUrl = 'https://www.facebook.com/sharer/sharer.php?u=' . rawurlencode($postUrl); ?>
                <div class="col-md-6">
                    <article class="panel-card h-100">
                        <?php if (!empty($post['featured_image'])): ?>
                            <img class="img-fluid rounded-4 mb-3" src="<?php echo e(base_url((string) $post['featured_image'])); ?>" alt="<?php echo e($post['title']); ?>">
                        <?php endif; ?>
                        <div class="mb-2"><span class="badge <?php echo e($newsCategoryBadgeClass((string) ($post['category'] ?? 'general'))); ?>"><?php echo e($newsCategoryLabel((string) ($post['category'] ?? 'general'))); ?></span></div>
                        <p class="eyebrow mb-2"><?php echo e((string) ($post['published_at'] ?? $post['created_at'])); ?></p>
                        <h2 class="h4 mb-2"><?php echo e($post['title']); ?></h2>
                        <p class="text-muted mb-3"><?php echo e(mb_strimwidth(strip_tags($post['body']), 0, 220, '...')); ?></p>
                        <div class="d-flex gap-2 flex-wrap">
                            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/news-details.php?slug=' . urlencode((string) $post['slug']))); ?>">Read story</a>
                            <?php if (!empty($post['fixture_id'])): ?>
                                <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/match-details.php?id=' . (int) $post['fixture_id'])); ?>">Match details</a>
                            <?php endif; ?>
                            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e($postWhatsAppShareUrl); ?>" target="_blank" rel="noopener noreferrer">
                                <i class="bi bi-whatsapp"></i> WhatsApp
                            </a>
                            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e($postFacebookShareUrl); ?>" target="_blank" rel="noopener noreferrer">
                                <i class="bi bi-facebook"></i> Facebook
                            </a>
                        </div>
                    </article>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </section>
<?php
});
