<?php
$pageTitle = 'Shop';
require_once __DIR__ . '/includes/header.php';

// Get category filter if set
$categoryFilter = isset($_GET['category']) ? intval($_GET['category']) : null;

// Build SQL query
$sql = "SELECT p.*, c.name as category_name 
        FROM products p 
        LEFT JOIN categories c ON p.category_id = c.category_id
        " . ($categoryFilter ? "WHERE p.category_id = $categoryFilter" : "") . "
        ORDER BY p.created_at DESC";
$result = $conn->query($sql);
?>

<main class="shop-page">
    <div class="container">
        <h1>Our Products</h1>
        
        <div class="product-filters">
            <h3>Filter by Category</h3>
            <ul class="category-list">
                <li><a href="shop.php" <?php echo !$categoryFilter ? 'class="active"' : ''; ?>>All Products</a></li>
                <?php
                // Get all categories
                $catSql = "SELECT * FROM categories ORDER BY name";
                $catResult = $conn->query($catSql);
                
                if ($catResult->num_rows > 0) {
                    while($cat = $catResult->fetch_assoc()) {
                        $activeClass = $categoryFilter == $cat['category_id'] ? 'class="active"' : '';
                        echo '<li><a href="shop.php?category=' . $cat['category_id'] . '" ' . $activeClass . '>' . 
                             htmlspecialchars($cat['name']) . '</a></li>';
                    }
                }
                ?>
            </ul>
        </div>
        
        <div class="product-grid">
            <?php if ($result->num_rows > 0): ?>
                <?php while($row = $result->fetch_assoc()): ?>
                    <div class="product-card">
                        <div class="product-image">
                            <img src="<?php echo BASE_URL; ?>/images/products/<?php echo htmlspecialchars($row['image_url']); ?>" alt="<?php echo htmlspecialchars($row['name']); ?>">
                        </div>
                        <div class="product-details">
                            <h3><?php echo htmlspecialchars($row['name']); ?></h3>
                            <p class="category"><?php echo htmlspecialchars($row['category_name']); ?></p>
                            <p class="price">From KShs <?php echo number_format($row['base_price'], 2); ?></p>
                            <a href="product.php?id=<?php echo $row['product_id']; ?>" class="btn">View Details</a>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <p>No products found.</p>
            <?php endif; ?>
        </div>
    </div>
</main>

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