<?php
require 'inc/db.php';
header('Content-Type: application/json');

$category_id = (int)($_GET['category_id'] ?? 0);
$filter      = (int)($_GET['filter'] ?? 0);
$page        = max(1, (int)($_GET['page'] ?? 1));
$limit       = 9;
$offset      = ($page - 1) * $limit;
$sub_slug    = $_GET['sub'] ?? '';
$sub_slug    = mysqli_real_escape_string($conn, $sub_slug);

/* GET SUBCATEGORY ID */
$sub_id = 0;
if (!empty($sub_slug)) {
    $subData = mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT id FROM subcategories
        WHERE slug='$sub_slug' AND category_id=$category_id AND status='active'
    "));
    $sub_id = $subData['id'] ?? 0;
}



/* WHERE CONDITION */
$filter = $_GET['filter'] ?? '';
$filter = trim($filter);

$whereCondition = "p.category_id = $category_id";

// If filter is selected, match ANY of the IDs
if(!empty($filter)){
    $filterIds = array_map('intval', explode(',', $filter));
    $idsStr = implode(',', $filterIds);

    $whereCondition .= " AND EXISTS (
        SELECT 1 FROM product_sorting_map m
        WHERE m.product_id = p.id AND m.sorting_option_id IN ($idsStr)
    )";
}
// Else filter by subcategory if present
elseif($sub_id > 0){
    $whereCondition .= " AND p.subcategory_id = $sub_id";
}

$where = "WHERE $whereCondition AND p.status='active'";

/* TOTAL COUNT */
$countQ = mysqli_query($conn, "SELECT COUNT(DISTINCT p.id) as total FROM products p $where");
$total = mysqli_fetch_assoc($countQ)['total'] ?? 0;
$totalPages = ceil($total / $limit);

/* FETCH PRODUCTS */
$q = mysqli_query($conn, "
    SELECT DISTINCT p.id, p.name, p.slug, p.featured_image, p.base_price, c.name as category_name
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    $where
    ORDER BY p.id DESC
    LIMIT $limit OFFSET $offset
");

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

/* PAGINATION HTML */
ob_start();
if ($totalPages > 1) {
    echo '<ul class="pagination justify-content-center">';
    for ($i = 1; $i <= $totalPages; $i++) {
        $active = $i == $page ? 'active' : '';
        echo "<li class='page-item $active'><a class='page-link page-btn' data-page='$i'>$i</a></li>";
    }
    echo '</ul>';
}
$paginationHtml = ob_get_clean();

/* JSON RESPONSE */
echo json_encode([
    'products'   => $productsHtml,
    'pagination' => $paginationHtml
]);