<?php

declare(strict_types=1);

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

$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',
};

$slug = trim((string) ($_GET['slug'] ?? ''));
$post = null;
$relatedPosts = [];

if ($slug !== '') {
    try {
        $post = db_fetch_one(
            'SELECT title, slug, category, fixture_id, body, featured_image, published_at, created_at
             FROM news_posts
             WHERE slug = :slug AND status = :status
             LIMIT 1',
            ['slug' => $slug, 'status' => 'published']
        );

        if ($post !== null) {
            $relatedPosts = db_fetch_all(
                'SELECT title, slug, category, fixture_id, published_at, created_at
                 FROM news_posts
                 WHERE status = :status AND slug <> :slug
                 ORDER BY COALESCE(published_at, created_at) DESC
                 LIMIT 4',
                ['status' => 'published', 'slug' => $slug]
            );
        }
    } catch (Throwable) {
    }
}

$pageTitle = $post['title'] ?? 'News Story';
$lead = $post !== null
    ? 'Published league story from the JLFC newsroom.'
    : 'Published league updates, announcements, and competition stories.';

$shareUrl = $post !== null
    ? absolute_url('app/public/news-details.php?slug=' . urlencode((string) $post['slug']))
    : absolute_url('app/public/news.php');
$shareTitle = $post !== null ? (string) $post['title'] : 'JLFC News';
$shareDescription = $post !== null
    ? mb_strimwidth(trim(preg_replace('/\s+/', ' ', strip_tags((string) $post['body']))), 0, 180, '...')
    : 'Published league updates, announcements, and competition stories.';
$shareImage = null;

if ($post !== null && !empty($post['featured_image'])) {
    $shareImage = absolute_url((string) $post['featured_image']);
}

$whatsAppShareUrl = 'https://wa.me/?text=' . rawurlencode($shareTitle . ' ' . $shareUrl);
$facebookShareUrl = 'https://www.facebook.com/sharer/sharer.php?u=' . rawurlencode($shareUrl);

render_public_page($pageTitle, $lead, static function () use ($post, $relatedPosts, $newsCategoryBadgeClass, $newsCategoryLabel, $whatsAppShareUrl, $facebookShareUrl): void {
?>
    <section class="panel-card mb-4">
        <?php if ($post === null): ?>
            <p class="text-muted mb-3">The requested news story could not be found.</p>
            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/news.php')); ?>">Back to news</a>
        <?php else: ?>
            <p class="eyebrow mb-2"><?php echo e((string) ($post['published_at'] ?? $post['created_at'])); ?></p>
            <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>
            <h2 class="h3 mb-3"><?php echo e($post['title']); ?></h2>
            <?php if (!empty($post['featured_image'])): ?>
                <img class="img-fluid rounded-4 mb-4" src="<?php echo e(base_url((string) $post['featured_image'])); ?>" alt="<?php echo e($post['title']); ?>">
            <?php endif; ?>
            <div class="public-story-body">
                <p class="mb-0"><?php echo nl2br(e((string) $post['body'])); ?></p>
            </div>
            <div class="d-flex gap-2 flex-wrap mt-4">
                <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/news.php')); ?>">Back to news</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'])); ?>">Open match details</a>
                <?php endif; ?>
                <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e($whatsAppShareUrl); ?>" target="_blank" rel="noopener noreferrer">
                    <i class="bi bi-whatsapp"></i> Share to WhatsApp
                </a>
                <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e($facebookShareUrl); ?>" target="_blank" rel="noopener noreferrer">
                    <i class="bi bi-facebook"></i> Share to Facebook
                </a>
            </div>
        <?php endif; ?>
    </section>

    <?php if ($post !== null): ?>
        <section class="panel-card">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Newsroom</p>
                    <h3 class="h5 mb-0">More published stories</h3>
                </div>
            </div>
            <?php if ($relatedPosts === []): ?>
                <p class="text-muted mb-0">No additional published stories are available yet.</p>
            <?php else: ?>
                <div class="row g-3">
                    <?php foreach ($relatedPosts as $relatedPost): ?>
                        <div class="col-md-6">
                            <div class="feature-tile h-100">
                                <i class="bi bi-newspaper"></i>
                                <div>
                                    <p class="eyebrow mb-1"><?php echo e((string) ($relatedPost['published_at'] ?? $relatedPost['created_at'])); ?></p>
                                    <h4><?php echo e($relatedPost['title']); ?></h4>
                                    <div class="d-flex gap-2 flex-wrap mt-2">
                                        <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/news-details.php?slug=' . urlencode((string) $relatedPost['slug']))); ?>">Read story</a>
                                        <?php if (!empty($relatedPost['fixture_id'])): ?>
                                            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/match-details.php?id=' . (int) $relatedPost['fixture_id'])); ?>">Match details</a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
    <?php endif; ?>
<?php
}, [
    'description' => $shareDescription,
    'url' => $shareUrl,
    'image' => $shareImage,
    'type' => 'article',
]);
