<?php
// Include the database connection
require 'db_connection.php';

// Get the page number from the AJAX request, default to 1
$page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
$limit = 8; // Number of products to display per page
$offset = ($page - 1) * $limit; // Calculate the offset

// Fetch products with the limit and offset
$query = "
    SELECT 
        p.id AS product_id, 
        p.product_name, 
        p.current_price, 
        pi.image_path 
    FROM products p
    LEFT JOIN product_images pi ON p.id = pi.product_id
    GROUP BY p.id
    LIMIT $offset, $limit
";

$products = mysqli_query($conn, $query);

// Loop through products and display them
if ($products && mysqli_num_rows($products) > 0) {
    while ($product = mysqli_fetch_assoc($products)) {
        // Use a placeholder image if no image path exists
        $image_path = !empty($product['image_path']) ? htmlspecialchars($product['image_path']) : 'placeholder.jpg';
        ?>
        <div class="single-product-item product-item--style-1 product-item--bg-lime-green">
            <a href="single-product.php?product_id=<?= $product['product_id']; ?>" class="image">
                <img width="127" height="98" class="img-fluid" src="adm/<?= $image_path; ?>" alt="<?= htmlspecialchars($product['product_name']); ?>">
            </a>
            <div class="content">
                <div class="content--left">
                    <ul class="review-star">
                        <li class="items fill"><i class="icon icon-carce-star-full"></i></li>
                        <li class="items fill"><i class="icon icon-carce-star-full"></i></li>
                        <li class="items fill"><i class="icon icon-carce-star-full"></i></li>
                        <li class="items fill"><i class="icon icon-carce-star-full"></i></li>
                        <li class="items fill"><i class="icon icon-carce-star-full"></i></li>
                    </ul>
                    <a href="single-product.php?product_id=<?= $product['product_id']; ?>" class="title"><?= htmlspecialchars($product['product_name']); ?></a>
                    <span class="price">$<?= number_format($product['current_price'], 2); ?></span>
                </div>
                <div class="content--right">
                    <a href="wishlist.php?product_id=<?= $product['product_id']; ?>" aria-label="Wishlist" class="btn btn--size-33-33 btn--center btn--round btn--color-radical-red btn--bg-white btn--box-shadow">
                        <i class="icon icon-carce-heart"></i>
                    </a>
                </div>
            </div>
        </div>
        <?php
    }
} else {
    echo '<p>No products found.</p>';
}

$conn->close();
?>
