<?php
include 'header.php';

// Group items by category for the home page (Max 5 per category)
$categories_with_items = [];
foreach ($nav_categories as $cat) {
    $stmt = $conn->prepare("SELECT * FROM items WHERE category_id = ? ORDER BY total_points DESC LIMIT 5");
    $stmt->execute([$cat['id']]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (count($items) > 0) {
        $categories_with_items[] = [
            'category' => $cat,
            'items' => $items
        ];
    }
}
?>

<div class="container py-5">
    <?php if (count($categories_with_items) === 0): ?>
        <div class="text-center py-5">
            <h4 class="text-muted">No items found. Admin needs to add items first.</h4>
        </div>
    <?php endif; ?>

    <?php foreach($categories_with_items as $cgroup): ?>
        <div class="mb-5">
            <div class="section-title">
                <?php echo htmlspecialchars($cgroup['category']['name']); ?>
            </div>
            <div class="horizontal-scroll-container pb-2">
                <?php foreach($cgroup['items'] as $item): ?>
                    <a href="category.php?slug=<?php echo htmlspecialchars($cgroup['category']['slug']); ?>" class="text-decoration-none text-dark">
                        <div class="item-card">
                            <?php 
                                $img = !empty($item['image_path']) ? htmlspecialchars($item['image_path']) : 'https://ui-avatars.com/api/?size=200&background=random&name=No+Photo';
                            ?>
                            <img src="<?php echo $img; ?>" alt="<?php echo htmlspecialchars($item['title']); ?>">
                            <div class="card-body">
                                <h6 class="card-title"><?php echo htmlspecialchars($item['title']); ?></h6>
                                <div class="like-badge">
                                    <i class="fa-solid fa-heart"></i>
                                    <span><?php echo number_format($item['total_points']); ?></span>
                                </div>
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<?php include 'footer.php'; ?>
