<?php
require 'inc/db.php';

$category_id = (int)$_GET['category_id'];
$filterOption = isset($_GET['filter']) ? (int)$_GET['filter'] : 0;

$filterSQL = "";

if ($filterOption > 0) {
    $filterSQL = "
        AND p.id IN (
            SELECT product_id
            FROM product_sorting_map
            WHERE sorting_option_id = $filterOption
        )
    ";
}

$products = mysqli_query($conn, "
    SELECT DISTINCT p.id, p.name, p.slug, p.featured_image
    FROM products p
    WHERE 
        p.category_id = $category_id
        AND p.status = 'active'
        $filterSQL
    ORDER BY p.id DESC
");

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

