<?php
require_once __DIR__ . '/config/database.php';
$settings = getAllSettings($pdo);

$catId = (int)($_GET['id'] ?? 0);
$sort  = $_GET['sort'] ?? 'newest';

$category = null;
if ($catId) {
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ?");
    $stmt->execute([$catId]);
    $category = $stmt->fetch();
}

$orderBy = match($sort) {
    'price_asc'  => 'p.price ASC',
    'price_desc' => 'p.price DESC',
    'name_asc'   => 'p.name ASC',
    'name_desc'  => 'p.name DESC',
    default      => 'p.created_at DESC',
};

$params = [];
$where  = 'WHERE 1=1';
if ($catId) { $where .= ' AND p.category_id = ?'; $params[] = $catId; }

$query = "SELECT p.*, c.name AS cat_name FROM products p
          LEFT JOIN categories c ON p.category_id = c.id
          $where ORDER BY $orderBy";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$products = $stmt->fetchAll();

$allCats = $pdo->query("SELECT * FROM categories WHERE status=1 ORDER BY name")->fetchAll();

// Get first variation id for a product
function firstVarId($pdo, $pid) {
    $s = $pdo->prepare("SELECT id FROM product_variations WHERE product_id=? LIMIT 1");
    $s->execute([$pid]);
    $r = $s->fetch();
    return $r ? $r['id'] : '';
}
function hasVariations($pdo, $pid) {
    $s = $pdo->prepare("SELECT COUNT(*) FROM product_variations WHERE product_id=?");
    $s->execute([$pid]);
    return $s->fetchColumn() > 0;
}

include __DIR__ . '/includes/header.php';
?>

<div class="category-page" style="padding:28px 0 56px;">
    <div class="container">

        <!-- Breadcrumb -->
        <div class="breadcrumb">
            <a href="<?= BASE_URL ?>/index.php">হোম</a>
            <span>/</span>
            <?= $category ? e($category['name']) : 'সব পণ্য' ?>
        </div>

        <!-- Layout: sidebar + products -->
        <div class="cat-layout">

            <!-- Sidebar (hidden on mobile via CSS) -->
            <div class="cat-sidebar">
                <div class="checkout-card" style="padding:16px;">
                    <h4 style="font-size:.95rem;font-weight:700;color:var(--navy);margin-bottom:12px;padding-bottom:8px;border-bottom:2px solid var(--g100);">ক্যাটেগরি</h4>
                    <a href="<?= BASE_URL ?>/category.php"
                       style="display:block;padding:8px 10px;border-radius:6px;font-size:.88rem;margin-bottom:3px;transition:all .2s;color:var(--g600);<?= !$catId ? 'background:var(--gold);color:var(--navy);font-weight:700;' : '' ?>">
                       সব পণ্য
                    </a>
                    <?php foreach ($allCats as $cat): ?>
                        <a href="<?= BASE_URL ?>/category.php?id=<?= $cat['id'] ?>"
                           style="display:block;padding:8px 10px;border-radius:6px;font-size:.88rem;margin-bottom:3px;transition:all .2s;color:var(--g600);<?= $catId==$cat['id'] ? 'background:var(--gold);color:var(--navy);font-weight:700;' : '' ?>">
                            <?= e($cat['name']) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Products Area -->
            <div style="flex:1;min-width:0;">

                <!-- Mobile category chips -->
                <div style="display:flex;gap:8px;overflow-x:auto;padding-bottom:10px;scrollbar-width:none;margin-bottom:16px;" class="mobile-cat-chips">
                    <a href="<?= BASE_URL ?>/category.php"
                       style="flex-shrink:0;padding:7px 16px;border-radius:50px;font-size:.83rem;font-weight:600;border:1.5px solid <?= !$catId ? 'var(--gold)' : 'var(--g200)' ?>;background:<?= !$catId ? 'var(--gold)' : 'white' ?>;color:<?= !$catId ? 'var(--navy)' : 'var(--g600)' ?>;">
                       সব পণ্য
                    </a>
                    <?php foreach ($allCats as $cat): ?>
                        <a href="<?= BASE_URL ?>/category.php?id=<?= $cat['id'] ?>"
                           style="flex-shrink:0;padding:7px 16px;border-radius:50px;font-size:.83rem;font-weight:600;border:1.5px solid <?= $catId==$cat['id'] ? 'var(--gold)' : 'var(--g200)' ?>;background:<?= $catId==$cat['id'] ? 'var(--gold)' : 'white' ?>;color:<?= $catId==$cat['id'] ? 'var(--navy)' : 'var(--g600)' ?>;">
                            <?= e($cat['name']) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
                <style>.mobile-cat-chips::-webkit-scrollbar{display:none}
                @media(min-width:700px){.mobile-cat-chips{display:none!important}}</style>

                <!-- Filter bar -->
                <div class="filter-bar">
                    <span style="font-weight:700;color:var(--navy);font-size:.93rem;">
                        <?= $category ? e($category['name']) : 'সব পণ্য' ?>
                        <span style="color:var(--g400);font-weight:400;">(<?= count($products) ?> টি)</span>
                    </span>
                    <div style="margin-left:auto;display:flex;align-items:center;gap:8px;">
                        <label style="font-size:.85rem;color:var(--g600);white-space:nowrap;">সাজান:</label>
                        <select class="filter-select" onchange="applySort(this.value)">
                            <option value="newest"     <?= $sort=='newest'    ?'selected':''?>>নতুন আগে</option>
                            <option value="price_asc"  <?= $sort=='price_asc' ?'selected':''?>>মূল্য: কম → বেশি</option>
                            <option value="price_desc" <?= $sort=='price_desc'?'selected':''?>>মূল্য: বেশি → কম</option>
                            <option value="name_asc"   <?= $sort=='name_asc'  ?'selected':''?>>নাম: ক → খ</option>
                        </select>
                    </div>
                </div>

                <!-- Products Grid -->
                <?php if (empty($products)): ?>
                    <div class="empty-cart">
                        <i class="fas fa-box-open"></i>
                        <p>এই ক্যাটেগরিতে কোনো পণ্য নেই।</p>
                        <a href="<?= BASE_URL ?>/index.php" class="btn-primary" style="display:inline-block;width:auto;padding:10px 24px;margin-top:14px;">হোমে যান</a>
                    </div>
                <?php else: ?>
                    <div class="products-grid" id="productsGrid">
                        <?php foreach ($products as $p):
                            $hasVars   = hasVariations($pdo, $p['id']);
                            $fvid      = firstVarId($pdo, $p['id']);
                            // Variable → product page; Simple → direct checkout
                            $buyHref   = $hasVars
                                ? BASE_URL . '/product.php?id=' . $p['id']
                                : BASE_URL . '/checkout-add.php?product_id=' . $p['id'] . '&variation_id=&qty=1';
                            $outOfStock = $p['stock'] <= 0;
                        ?>
                        <div class="product-card">
                            <?php if ($p['is_flash']): ?><span class="flash-tag">🔥 সেল</span><?php endif; ?>
                            <?php if ($outOfStock): ?><span class="out-of-stock-tag">স্টক নেই</span><?php endif; ?>

                            <a href="<?= BASE_URL ?>/product.php?id=<?= $p['id'] ?>">
                                <?php if ($p['image']): ?>
                                    <img class="card-img"
                                         src="<?= UPLOADS_URL . e($p['image']) ?>"
                                         alt="<?= e($p['name']) ?>" loading="lazy">
                                <?php else: ?>
                                    <div class="card-img-placeholder"><i class="fas fa-image"></i></div>
                                <?php endif; ?>
                            </a>

                            <div class="card-body">
                                <div class="card-title">
                                    <a href="<?= BASE_URL ?>/product.php?id=<?= $p['id'] ?>"><?= e($p['name']) ?></a>
                                </div>
                                <div class="card-price">৳<?= number_format($p['price'], 2) ?></div>

                                <?php if ($hasVars): ?>
                                    <div style="font-size:.74rem;color:var(--g600);margin-bottom:6px;">
                                        <i class="fas fa-palette"></i> ভ্যারিয়েশন আছে
                                    </div>
                                <?php endif; ?>

                                <?php if (!$outOfStock): ?>
                                    <a href="<?= $buyHref ?>" class="btn-buy">
                                        <i class="fas fa-bolt"></i> এখনই কিনুন
                                    </a>
                                <?php else: ?>
                                    <button class="btn-buy" disabled style="opacity:.45;cursor:not-allowed;">স্টক নেই</button>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
function applySort(val) {
    const url = new URL(window.location.href);
    url.searchParams.set('sort', val);
    window.location.href = url.toString();
}
</script>

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