<?php
// Include your database connection
include 'shikanisha.kts.php';

// Fetch input values
$query = $_POST['query'];

// Pagination settings
$resultsPerPage = 10; // Number of results to display per page

// Calculate the starting row for the current page
$page = isset($_POST['page']) ? $_POST['page'] : 1;
$startFrom = ($page - 1) * $resultsPerPage;

// Build your SQL query based on input values and pagination
$sql = "SELECT `product_id`, `product_name`,`category`, `selling_price`, `img` FROM `products` WHERE ";
$sql .= "`product_name` LIKE '%$query%' ";
$sql .= "LIMIT $startFrom, $resultsPerPage";

// Perform the query
$result = mysqli_query($conn, $sql);

echo '<div class="section">';
echo '<div class="container">';
echo '<div class="row">';
echo '<div class="col-md-12 col-xs-12">';
echo '<div class="section-title">';
echo '<h4 class="title">Search Results</h4>';
echo '<div class="section-nav">';
echo '<div id="slick-nav-3" class="products-slick-nav"></div>';
echo '</div>';
echo '</div>';

// Check if there are results
if (mysqli_num_rows($result) > 0) {
    echo '<table class="table table-bordered">';
    echo '<thead>';
    echo '<tr>';
    echo '<th>Category</th>';
    echo '<th>Product Name</th>';
    echo '<th>Selling Price</th>';
    echo '<th>Action</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';
    
    while ($row = mysqli_fetch_assoc($result)) {
        // Output each result as a table row
        echo '<tr>';
        echo '<td>' . $row['category'] . '</td>';
        echo '<td>' . $row['product_name'] . '</td>';
        echo '<td>Ksh: ' . $row['selling_price'] . '</td>';
        echo '<td><button name="cart" class="primary-btn add-to-cart-btn cta-btn" data-product-id="' . $row['product_id'] . '"><i class="fa fa-shopping-cart"></i> <b>+</b> Cart</button></td>';
        echo '</tr>';
    }
    
    echo '</tbody>';
    echo '</table>';

    // Display pagination controls
    $totalResults = mysqli_num_rows(mysqli_query($conn, "SELECT COUNT(*) AS total FROM `products` WHERE `product_name` LIKE '%$query%'"));
    $totalPages = ceil($totalResults / $resultsPerPage);

    echo '<div class="pagination-container">';
    echo '<ul class="pagination">';
    
    // Previous button
    echo '<li><a href="#" onclick="getSearchResults(' . ($page - 1) . ')">&laquo; Previous</a></li>';
    
    // Page numbers
    for ($i = 1; $i <= $totalPages; $i++) {
        echo '<li><a href="#" onclick="getSearchResults(' . $i . ')">' . $i . '</a></li>';
    }

    // Next button
    echo '<li><a href="#" onclick="getSearchResults(' . ($page + 1) . ')">Next &raquo;</a></li>';

    echo '</ul>';
    echo '</div>'; // Close pagination-container
} else {
    // No results
    echo 'No results found.';
}

echo '</div>'; // Close col-md-12
echo '</div>'; // Close row
echo '</div>'; // Close container
echo '</div>'; // Close section

// Close the database connection
mysqli_close($conn);
?>


 <script>
    $(document).ready(function () {
        // Function to update the cart UI
  function updateCartUI(cartItems) {
            var cartList = $('.cart-list');
            var totalItems = 0;
            var subtotal = 0.0;

            // Clear existing cart items
            cartList.empty();

            // HTML string to store cart items
            var cartHTML = '';

            // Check if cartItems is an array
            if (Array.isArray(cartItems)) {
                // Populate cart items
                cartItems.forEach(function (cartItem) {
                    cartHTML += '<div class="product-widget">';
                    cartHTML += '<div class="product-img"><img src="' + cartItem.img + '" alt=""></div>';
                    cartHTML += '<div class="product-body">';
                    cartHTML += '<h3 class="product-name"><a href="#">' + cartItem.product_name + '</a></h3>';
                    cartHTML += '<p class="quantity">' + cartItem.quantity + ' </p> X';
                    cartHTML += '<p class="price">' + cartItem.price + ' </p>';
                    cartHTML += '<h4 class="product-price">Ksh' + cartItem.subtotal.toFixed(2) + '</h4>';
                    cartHTML += '<button class="delete remove-from-cart-btn" data-product-id="' + cartItem.product_id + '"><i class="fa fa-close"></i></button>';
                    cartHTML += '</div>';
                    cartHTML += '</div>';

                    // Update total items and subtotal
                    totalItems += cartItem.quantity;
                    subtotal += cartItem.price * cartItem.quantity;
                });
            } else {
                // Handle the case where cartItems is not an array
                console.error('Invalid cartItems format:', cartItems);
            }

            // Append the HTML string to the cart list
            $(cartHTML).appendTo(cartList);

            // Update total items and subtotal in the cart summary
            $('.qty').text(totalItems);
            $('.cart-summary small').text(totalItems + ' Item(s) selected');
            $('.cart-summary h5').text('SUBTOTAL: Ksh' + subtotal.toFixed(2));
        }
        // Function to fetch and load cart items on page load or reload
        function loadCartItems() {
            // Perform an Ajax request to get the initial cart items
            $.ajax({
                type: 'GET',
                url: 'engine/gci.kts.php',
                dataType: 'json',
                success: function (response) {
                    updateCartUI(response.cartItems);
                }
            });
        }

        // Call the loadCartItems function on page load
        loadCartItems();

        // Prevent default form submission behavior
        $('.add-to-cart-btn').click(function (e) {
            e.preventDefault();

            // Fetch the product details from the data attributes
            var productId = $(this).data('product-id');

            // Perform an Ajax request to add the product to the cart
            $.ajax({
                type: 'POST',
                url: 'engine/atc.kts.php',
                data: {
                    productId: productId
                },
                dataType: 'json',
                success: function (response) {
                    updateCartUI(response.cartItems);
                }
            });
        });
    });
</script>


  

