<?php
include("inc/header.php");

if (!isset($_GET['category'])) {
    die("Category not specified");
}

$slug = mysqli_real_escape_string($conn, $_GET['category']);
$currentSubSlug = $_GET['sub'] ?? '';
$currentSubSlug = mysqli_real_escape_string($conn, $currentSubSlug);

/* CURRENT CATEGORY */
$category = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT id, name
    FROM categories
    WHERE slug='$slug' AND status='active'
"));

if (!$category) die("Category not found");

/* SIDEBAR CATEGORIES */
$categories = mysqli_query($conn, "
    SELECT name, slug
    FROM categories
    WHERE status='active'
    ORDER BY sort_order ASC
");

/* GET SUBCATEGORY CONDITION FOR INITIAL PRODUCTS */
$whereCondition = "p.category_id = {$category['id']}";
if (!empty($currentSubSlug)) {
    $subData = mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT id FROM subcategories
        WHERE slug='$currentSubSlug' AND category_id={$category['id']} AND status='active'
    "));
    if ($subData) $whereCondition .= " AND p.subcategory_id = {$subData['id']}";
}

/* INITIAL PRODUCTS */
$products = mysqli_query($conn, "
    SELECT DISTINCT p.id, p.name, p.slug, p.featured_image
    FROM products p
    WHERE ($whereCondition) AND p.status = 'active'
    ORDER BY p.id DESC
");

/* SORTING OPTIONS (RESPECT SUBCATEGORY) */
$subcatCondition = "";
if (!empty($currentSubSlug) && $subData) {
    $subcatCondition = "AND p.subcategory_id = {$subData['id']}";
}

$optionsRes = mysqli_query($conn, "
    SELECT so.name, so.id, p.subcategory_id
    FROM sorting_options so
    JOIN product_sorting_map psm ON psm.sorting_option_id = so.id
    JOIN products p ON p.id = psm.product_id
    WHERE p.category_id = {$category['id']}
    ".(!empty($subData) ? "AND p.subcategory_id = {$subData['id']}" : "")."
    ORDER BY so.name ASC
");

$options = [];
$seen = [];
while($row = mysqli_fetch_assoc($optionsRes)) {
    $lowerName = strtolower($row['name']);
    if(!in_array($lowerName, $seen)){
        $seen[] = $lowerName;
        $options[] = [
            'name' => $row['name'],
            'ids'  => []  // we’ll fill with all IDs of this name
        ];
    }
}

// Map all IDs to their lowercase name
$optionIdsMap = [];
mysqli_data_seek($optionsRes, 0); // reset pointer
while($row = mysqli_fetch_assoc($optionsRes)){
    $nameLower = strtolower($row['name']);
    if(!isset($optionIdsMap[$nameLower])) $optionIdsMap[$nameLower] = [];
    $optionIdsMap[$nameLower][] = $row['id'];
}

// Attach IDs to each option
foreach($options as &$opt){
    $opt['ids'] = $optionIdsMap[strtolower($opt['name'])];
}
unset($opt);
?>
<style>
.pagination .page-item.active .page-link {
    background: #ff2e2e;
    border-color: #ff2e2e;
    cursor: pointer;
}
li.page-item {
    cursor: pointer;
}
.page-link.page-btn {
    background: transparent;
    color: #efefef;
    border: none;
}

</style>

<section class="inner-banner-row">
    <div class="container">
        <div class="inner-banner-sec"></div>
    </div>
</section>

<section class="product-category-row">
    <div class="container">

        <!-- HEADER -->
        <div class="nectar-shop-header">
            <div>
                <nav class="shop-breadcrumb">
                    <span><a href="./">Home</a></span>
                    <i class="fa fa-angle-right"></i>
                    <span><?= htmlspecialchars($category['name']); ?></span>
                </nav>
            </div>

            <!-- SORTING DROPDOWN -->
            <div class="shop-head-right">
                <select id="filterSelect" class="form-control" style="min-width:220px;">
    <option value="">Sort by Material</option>
    <?php foreach ($options as $opt): ?>
        <option value="<?= implode(',', $opt['ids']); ?>">
            <?= htmlspecialchars($opt['name']); ?>
        </option>
    <?php endforeach; ?>
</select>
            </div>
        </div>
        

        <div class="row">

            <!-- SIDEBAR -->
            <div class="col-md-3">
                <div class="category-sidebar-sec">
                   <ul>
<?php while ($c = mysqli_fetch_assoc($categories)) { ?>

    <?php
    $isCategoryActive = ($c['slug'] === $slug && empty($currentSubSlug));
    ?>

    <li>
        <a href="product-category.php?category=<?= $c['slug']; ?>"
            class="<?= $isCategoryActive ? 'active' : ''; ?>">
            <?= htmlspecialchars($c['name']); ?>
        </a>
    </li>

    <?php
    /* GET SUBCATEGORIES FOR THIS CATEGORY */
   $subcats = mysqli_query($conn, "
    SELECT id, name, slug 
    FROM subcategories 
    WHERE category_id = (
        SELECT id FROM categories WHERE slug = '{$c['slug']}'
    )
    AND status='active'
    ORDER BY sort_order ASC
");

    while ($sub = mysqli_fetch_assoc($subcats)) {

        $isSubActive = ($c['slug'] === $slug && $currentSubSlug === $sub['slug']);
    ?>
        <li style="padding-left:60px;">
            <a href="product-category.php?category=<?= $c['slug']; ?>&sub=<?= $sub['slug']; ?>"
               class="<?= $isSubActive ? 'active' : ''; ?>">
                <?= htmlspecialchars($sub['name']); ?>
            </a>
        </li>
    <?php } ?>

<?php } ?>
</ul>
                </div>
            </div>

            <!-- PRODUCTS -->
            <div class="col-md-9">
                <div class="row" id="productGrid">

                    <?php if (mysqli_num_rows($products) > 0) { ?>
                    <?php while ($p = mysqli_fetch_assoc($products)) { ?>
                    <div class="col-md-4">
                        <div class="product-sec">
                               <img src="<?php 
                                           echo !empty($p['featured_image']) 
                                          ? 'admin/uploads/products/' . $p['featured_image'] 
                                          : 'assets/images/product-img1.jpg'; 
                                       ?>" alt="">
                            <div class="product-box-sec">
                                <h3><?= htmlspecialchars($p['name']); ?></h3>
                             <a href="single-product.php?id=<?= $p['id']; ?>">
                                    <button class="btn btn-primary w-btn">Shop Now</button>
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php } ?>
                    <?php } else { ?>
                    <div class="col-12">
                        <p class="no-product">No products found.</p>
                    </div>
                    <?php } ?>

                </div>

                <div id="paginationBox" class="text-center mt-4"></div>

            </div>

        </div>
    </div>
</section>

<?php include("inc/footer.php"); ?>

<script>
let currentPage = 1;

function loadProducts(page = 1) {

    currentPage = page;

    const filterValue = document.getElementById('filterSelect').value;
    const categoryId = <?= $category['id']; ?>;

   const subSlug = "<?= $currentSubSlug ?>";

let url = `load_products_ajax.php?category_id=${categoryId}&page=${page}`;
if(filterValue) url += `&filter=${filterValue}`;
else if(subSlug) url += `&sub=${subSlug}`;

fetch(url)
    .then(res => res.json())
    .then(res => {
        document.getElementById('productGrid').innerHTML = res.products;
        document.getElementById('paginationBox').innerHTML = res.pagination;
    });
}

/* ✅ FILTER CHANGE */
document.getElementById('filterSelect').addEventListener('change', () => {
    loadProducts(1);
});

/* ✅ PAGINATION CLICK */
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('page-btn')) {
        e.preventDefault();
        loadProducts(e.target.dataset.page);
    }
});

/* ✅ INITIAL LOAD */
loadProducts(1);
</script>

