<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

$items = [];

try {
    $items = db_fetch_all(
        'SELECT mg.id, mg.title, mg.file_path, mg.media_type, mg.created_at,
            mg.fixture_id,
                f.matchday, f.match_date,
                hc.name AS home_club_name, ac.name AS away_club_name,
                c.name AS club_name
         FROM media_gallery mg
         LEFT JOIN fixtures f ON f.id = mg.fixture_id
         LEFT JOIN clubs hc ON hc.id = f.home_club_id
         LEFT JOIN clubs ac ON ac.id = f.away_club_id
         LEFT JOIN clubs c ON c.id = mg.club_id
         ORDER BY mg.created_at DESC, mg.id DESC
         LIMIT 24'
    );
} catch (Throwable) {
}

render_public_page('Gallery', 'Match visuals, club media, and league content curated from the JLFC media desk.', static function () use ($items): void {
?>
    <section class="row g-4">
        <?php if ($items === []): ?>
            <div class="col-12">
                <div class="panel-card">
                    <p class="text-muted mb-0">No gallery items are available yet.</p>
                </div>
            </div>
        <?php else: ?>
            <?php foreach ($items as $item): ?>
                <div class="col-md-6 col-xl-4">
                    <article class="panel-card h-100">
                        <?php if (($item['media_type'] ?? '') === 'video'): ?>
                            <video class="w-100 rounded-4 mb-3" controls src="<?php echo e(base_url((string) $item['file_path'])); ?>"></video>
                        <?php else: ?>
                            <img class="img-fluid rounded-4 mb-3" src="<?php echo e(base_url((string) $item['file_path'])); ?>" alt="<?php echo e($item['title']); ?>">
                        <?php endif; ?>
                        <p class="eyebrow mb-2"><?php echo e(date('d M Y', strtotime((string) $item['created_at']))); ?></p>
                        <h2 class="h4 mb-2"><?php echo e($item['title']); ?></h2>
                        <p class="text-muted mb-0">
                            <?php echo e($item['fixture_id'] ? (($item['home_club_name'] ?? '') . ' vs ' . ($item['away_club_name'] ?? '')) : 'General league media'); ?>
                            <?php echo $item['club_name'] ? ' · ' . e((string) $item['club_name']) : ''; ?>
                        </p>
                        <div class="mt-3">
                            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/gallery-item.php?id=' . (int) $item['id'])); ?>">Open media</a>
                        </div>
                    </article>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </section>
<?php
});
