<?php
include 'includes/header.php';

$id = $_GET['id'] ?? 0;
$stmt = db()->prepare("SELECT * FROM categories WHERE id = ?");
$stmt->execute([$id]);
$cat = $stmt->fetch();

if (!$cat) {
    header("Location: index.php");
    exit;
}

// Fetch products for this category
$stmt = db()->prepare("SELECT p.*, c.name as category_name FROM products p JOIN categories c ON p.category_id = c.id WHERE p.category_id = ? ORDER BY p.id DESC");
$stmt->execute([$id]);
$cat_products = $stmt->fetchAll();
?>

<div class="row mb-5 align-items-center">
    <div class="col-md-6">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-2">
                <li class="breadcrumb-item"><a href="index.php" class="text-decoration-none text-muted">首页</a></li>
                <li class="breadcrumb-item active text-dark" aria-current="page"><?php echo htmlspecialchars($cat['name']); ?></li>
            </ol>
        </nav>
        <h1 class="fw-bold text-dark mb-0 d-flex align-items-center gap-3">
            <i class="bi <?php echo $cat['icon'] ?? 'bi-grid'; ?> text-primary"></i>
            <?php echo htmlspecialchars($cat['name']); ?>
        </h1>
    </div>
    <div class="col-md-6 text-md-end mt-3 mt-md-0">
        <span class="badge bg-primary bg-opacity-10 text-primary rounded-pill px-4 py-2 border border-primary border-opacity-25"><?php echo count($cat_products); ?> 个商品</span>
    </div>
</div>

<div class="row g-4">
    <?php if (empty($cat_products)): ?>
        <div class="col-12 text-center py-5">
            <div class="glass-card p-5 bg-white shadow-sm">
                <i class="bi bi-inbox fs-1 text-muted d-block mb-3"></i>
                <h4 class="text-dark">暂无相关商品</h4>
                <p class="text-muted">我们正在紧急补货中，请稍后再来。</p>
                <a href="index.php" class="btn btn-primary mt-3 px-5 rounded-pill">返回首页</a>
            </div>
        </div>
    <?php else: ?>
        <?php foreach ($cat_products as $product): ?>
            <div class="col-6 col-lg-3">
                <?php include 'includes/product_card.php'; ?>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

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