<?php
session_start();

$tablePosition = "table"; // Replace "admin" with the desired table position value


if (!isset($_SESSION['cart'])) {
  $_SESSION['cart'] = [];
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
   
    <meta charset="utf-8">
    <title id="shopname"></title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta content="" name="keywords">
    <meta content="" name="description">

    <!-- Favicon -->
    <link href="img/favicon.ico" rel="icon">

    <!-- Google Web Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Heebo:wght@400;500;600&family=Nunito:wght@600;700;800&family=Pacifico&display=swap" rel="stylesheet">

    <!-- Icon Font Stylesheet -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css" rel="stylesheet">

    <!-- Libraries Stylesheet -->
    <link href="lib/animate/animate.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="lib/tempusdominus/css/tempusdominus-bootstrap-4.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">

    <!-- Customized Bootstrap Stylesheet -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
  <style>
    #paginationContainer {
        display: flex;
        justify-content: center;
        align-items: center;
        list-style: none;
        padding: 0;
    }

    #paginationContainer li {
        margin: 0 5px;
    }
</style>
    <style>
 body {
            background-image: url("./imgs/login.jpg");
            background-size: cover;
            background-repeat: no-repeat;
            background-position: center;
            height: 100vh;
        }
  </style>
    
    
     <style>
        .tabz {
            background-color: rgba(255, 255, 255, 0.5); /* Adjust the alpha (opacity) value as needed */
        }
    </style>

    <!-- Template Stylesheet -->
    <link href="css/style.css" rel="stylesheet">
</head>

<body style="background-image: url('./imgs/login.jpg');
             background-size: cover;
             background-repeat: repeat;
             background-position: center;
            ">
         
   
       

        <div class="container-xxl py-10"  style="background-color: rgba(255, 255, 255, 0.5);">
            <div class="container ">
                <div class="text-center tabz wow fadeInUp tabz" data-wow-delay="0.1s "  style="background-color: rgba(255, 255, 255, 0.5);">
                    <h2 class=" text-center text-danger fw-normal" id="shopname1"></h2>
                    <p></p>
                    <h5 class="section-title ff-secondary text-center text-danger fw-normal">Food & beverages Menu</h5>
                   
                </div>
                <div class="tab-class text-center wow fadeInUp" data-wow-delay="0.1s  style="background-color: rgba(255, 255, 255, 0.5);"">
                    <ul class="nav nav-pills d-inline-flex justify-content-center border-bottom mb-5">
                        <li class="nav-item">
                            <a class="d-flex align-items-center text-start mx-3 ms-0 pb-3 active" data-bs-toggle="pill" href="#tab-1">
                                <i class="fa fa-coffee f text-danger"></i>
                                <div class="ps-3">
                                    <small class="text-danger">Popular</small>
                                    <h6 class="mt-n1 mb-0">Breakfast</h6>
                                </div>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="d-flex align-items-center text-start mx-3 pb-3" data-bs-toggle="pill" href="#tab-2">
                                <i class="fa fa-concierge-bell f text-danger"></i>
                                <div class="ps-3">
                                    <small class="text-danger">Lunch & Dinner</small>
                                    <h6 class="mt-n1 mb-0">Other Dishes</h6>
                                </div>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="d-flex align-items-center text-start mx-3 me-0 pb-3" data-bs-toggle="pill" href="#tab-3">
                                <i class="fa fa-pizza-slice f text-danger"></i>
                                <div class="ps-3">
                                    <small class="text-danger">Yummy</small>
                                    <h6 class="mt-n1 mb-0">Pizzas</h6>
                                </div>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="d-flex align-items-center text-start mx-3 me-0 pb-3" data-bs-toggle="pill" href="#tab-4">
                                <i class="fa fa-cheese f  text-danger"></i>
                                <div class="ps-3">
                                    <small class="text-danger">Meaty</small>
                                    <h6 class="mt-n1 mb-0">Wraps</h6>
                                </div>
                            </a>
                        </li>
                          <li class="nav-item">
                            <a class="d-flex align-items-center text-start mx-3 me-0 pb-3" data-bs-toggle="pill" href="#tab-5">
                                <i class="fa fa-drumstick-bite f text-danger"></i>
                                <div class="ps-3">
                                    <small class="text-danger">Chicken</small>
                                    <h6 class="mt-n1 mb-0">Wraps</h6>
                                </div>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="d-flex align-items-center text-start mx-3 me-0 pb-3" data-bs-toggle="pill" href="#tab-6">
                                <i class="fa fa-carrot f text-danger"></i>
                                <div class="ps-3">
                                    <small class="text-danger">Vegetables</small>
                                    <h6 class="mt-n1 mb-0"> Veges</h6>
                                </div>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="d-flex align-items-center text-start mx-3 me-0 pb-3" data-bs-toggle="pill" href="#tab-7">
                                <i class="fa fa-fish f text-danger"></i>
                                <div class="ps-3">
                                    <small class="text-danger">White Meat</small>
                                    <h6 class="mt-n1 mb-0"> Fish</h6>
                                </div>
                            </a>
                        </li>
                           <li class="nav-item">
                            <a class="d-flex align-items-center text-start mx-3 me-0 pb-3" data-bs-toggle="pill" href="#tab-8">
                                <i class="fa-solid fa-wine-bottle f text-primary"></i>
                                <div class="ps-3">
                                    <small class="text-danger">Non & Alcoholics</small>
                                    <h6 class="mt-n1 mb-0">Drinks</h6>
                                </div>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="d-flex align-items-center text-start mx-3 me-0 pb-3" data-bs-toggle="pill" href="#tab-10">
                                <i class="fa fa-cocktail f text-danger"></i>
                                <div class="ps-3">
                                    <small class="text-danger">Beverages</small>
                                    <h6 class="mt-n1 mb-0">Cocktails & Tots</h6>
                                </div>
                            </a>
                        </li>
                    </ul>
                 
    <div class="container py-2">
                <input type="text" id="searchInput"   style="background-color: rgba(255, 255, 255, 0.5);" class="form-control input-rounded" placeholder="Search">
        <div id="searchResults"></div>

    </div>
                    <div class="tab-content">
                       <div id="tab-1" class="tab-pane fade show p-0 active">
                        <div class="row g-4" id="breakfastItemsContainer">
                            <!-- Displayed breakfast items will be inserted here -->
                        </div>
                        <nav aria-label="Page navigation">
                            <ul class="pagination justify-content-center" id="paginationContainer">
                                <!-- Pagination buttons will be inserted here -->
                            </ul>
                        </nav>
                       </div>
                        <div id="tab-2" class="tab-pane fade show p-0">
                           <div class="row g-4" id="lunchItemsContainer">
                                <!-- Displayed lunch items will be inserted here -->
                           </div>
                          <!-- Pagination -->
                          <nav aria-label="Page navigation">
                              <ul class="pagination justify-content-center">
                                  <!-- Pagination buttons will be inserted here -->
                              </ul>
                          </nav>
                      </div>
                        <div id="tab-3" class="tab-pane fade show p-0">
                           <div class="row g-4" id="pizzaItemsContainer">
                                
                                <!-- Displayed pizza items will be inserted here -->
                            </div>
                            <nav aria-label="Page navigation">
                                    <ul class="pagination justify-content-center">
                                        <!-- Pagination buttons will be inserted here -->
                                    </ul>
                                </nav>
                        </div>
                           
                       <div id="tab-4" class="tab-pane fade show p-0">
    <div class="row g-4" id="meatItemsContainer">
        <!-- Meat items will be inserted here -->
    </div>
    <nav aria-label="Page navigation" id="meatItemsContainer_pagination">
        <ul class="pagination justify-content-center">
            <!-- Pagination buttons will be inserted here -->
        </ul>
    </nav>
</div>

<div id="tab-5" class="tab-pane fade show p-0">
    <div class="row g-4" id="chickenItemsContainer">
        <!-- Chicken items will be inserted here -->
    </div>
    <nav aria-label="Page navigation" id="chickenItemsContainer_pagination">
        <ul class="pagination justify-content-center">
            <!-- Pagination buttons will be inserted here -->
        </ul>
    </nav>
</div>

<div id="tab-6" class="tab-pane fade show p-0">
    <div class="row g-4" id="vegetableItemsContainer">
        <!-- Vegetable items will be inserted here -->
    </div>
    <nav aria-label="Page navigation" id="vegetableItemsContainer_pagination">
        <ul class="pagination justify-content-center">
            <!-- Pagination buttons will be inserted here -->
        </ul>
    </nav>
</div>

<div id="tab-7" class="tab-pane fade show p-0">
    <div class="row g-4" id="fishItemsContainer">
        <!-- Fish items will be inserted here -->
    </div>
    <nav aria-label="Page navigation" id="fishItemsContainer_pagination">
        <ul class="pagination justify-content-center">
            <!-- Pagination buttons will be inserted here -->
        </ul>
    </nav>
</div>

<div id="tab-8" class="tab-pane fade show p-0">
    <div class="row g-4" id="drinkItemsContainer">
        <!-- Drink items will be inserted here -->
    </div>
    <nav aria-label="Page navigation" id="drinkItemsContainer_pagination">
        <ul class="pagination justify-content-center">
            <!-- Pagination buttons will be inserted here -->
        </ul>
    </nav>
</div>
 <div id="tab-10" class="tab-pane fade show p-0">
    <div class="row g-4" id="totsItemsContainer">
        <!-- Drink items will be inserted here -->
    </div>
    <nav aria-label="Page navigation" id="totsItemsContainer_pagination">
        <ul class="pagination justify-content-center">
            <!-- Pagination buttons will be inserted here -->
        </ul>
    </nav>
</div>

                        
                    </div>
                </div>
            </div>
        </div>
        <!-- Menu End -->


       
            
          

        <!-- Footer End -->
  <div id="cart-modal" class="modal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Food Cart</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <!-- Cart items will be displayed here -->
        <ul id="cart-items" class="list-group mb-3"></ul>

        <!-- Subtotal and total -->
        <div class="d-flex justify-content-between">
          <span>Subtotal:</span>
          <span id="subtotal"></span>
        </div>
        <div class="d-flex justify-content-between">
          <span>Total:</span>
          <span id="total"></span>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-warning"  id="clear-cart-button">Clear</button>
        <button type="button" class="btn btn-success"  id="submit-order">Submit Order</button>
      </div>
    </div>
  </div>
</div>

        <!-- Back to Top -->
        <a href="#" class="btn btn-lg btn-primary btn-lg-square back-to-top"><i class="bi bi-arrow-up"></i></a>
  

    <!-- JavaScript Libraries -->
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="lib/wow/wow.min.js"></script>
    <script src="lib/easing/easing.min.js"></script>
    <script src="lib/waypoints/waypoints.min.js"></script>
    <script src="lib/counterup/counterup.min.js"></script>
    <script src="lib/owlcarousel/owl.carousel.min.js"></script>
    <script src="lib/tempusdominus/js/moment.min.js"></script>
    <script src="lib/tempusdominus/js/moment-timezone.min.js"></script>
    <script src="lib/tempusdominus/js/tempusdominus-bootstrap-4.min.js"></script>

    <!-- Template Javascript -->
    <script src="js/main.js"></script>
    
     
    <script>
  document.addEventListener('DOMContentLoaded', () => {
    const addToCartBtns = document.querySelectorAll('.add-to-cart-btn');

    addToCartBtns.forEach(btn => {
      btn.addEventListener('click', (event) => {
        event.preventDefault();
        const foodId = btn.getAttribute('data-food-id');
        const foodName = btn.getAttribute('data-food-name');
        const foodPrice = btn.getAttribute('data-food-price');

        // Set the values of the hidden input fields in the form
        document.getElementById('food-id').value = foodId;
        document.getElementById('food-name').value = foodName;
        document.getElementById('food-price').value = foodPrice;

        // Submit the form to add the item to the cart
        document.getElementById('add-to-cart-btn').click();
      });
    });
  });
  </script>
  
 
<script>

 document.addEventListener('DOMContentLoaded', () => {
  const cartItemsContainer = document.getElementById('cart-items');
  const subtotalElement = document.getElementById('subtotal');
  const totalElement = document.getElementById('total');
  const cartItemsCountElement = document.getElementById('cart-items-count');
  const clearCartButton = document.getElementById('clear-cart-btn');

  // Function to update the cart items count in the round icon
  function updateCartItemsCount(count) {
    cartItemsCountElement.textContent = count;
  }

 // Function to display the cart items, subtotal, and total
// Function to display the cart items, subtotal, and total
function displayCartItems() {
  // Clear the cart items container
  cartItemsContainer.innerHTML = '';

  // Retrieve the cart items from the PHP session
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'gearbox/get_cart_items.kts.php', true);
  xhr.onreadystatechange = function () {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      if (xhr.status === 200) {
        const cartItemsJSON = xhr.responseText;
        const items = JSON.parse(cartItemsJSON) || [];

        let subtotal = 0;

        // Loop through the cart items and create HTML elements for each item
        items.forEach((item) => {
          const cartItemElement = document.createElement('li');
          cartItemElement.className = 'list-group-item d-flex justify-content-between align-items-center';
          cartItemElement.innerHTML = `
            <span>${item.food_name}</span>
            <div>
              <button class="btn btn-sm btn-secondary decrease-quantity" data-food-id="${item.food_id}">-</button>
              <span class="mx-2">${item.quantity}</span>
              <button class="btn btn-sm btn-secondary increase-quantity" data-food-id="${item.food_id}">+</button>
              <button class="btn btn-sm btn-danger remove-item" data-food-id="${item.food_id}">Remove</button>
            </div>
            <span>Ksh ${item.food_price}</span>
          `;
          cartItemsContainer.appendChild(cartItemElement);

          subtotal += parseFloat(item.food_price) * item.quantity;
        });

        // Update the subtotal and total elements
        subtotalElement.textContent = `Ksh ${subtotal.toFixed(2)}`;
        totalElement.textContent = `Ksh ${subtotal.toFixed(2)}`; // Assuming total is the same as subtotal in this example

        // Update the cart items count
        updateCartItemsCount(items.length);

        // Add event listeners to the quantity buttons
        const increaseButtons = document.querySelectorAll('.increase-quantity');
        const decreaseButtons = document.querySelectorAll('.decrease-quantity');
        const removeButtons = document.querySelectorAll('.remove-item');
        

       increaseButtons.forEach((button) => {
         button.addEventListener('click', () => {
            console.log('Increase button clicked');
            const foodId = button.getAttribute('data-food-id');
            changeCartItemQuantity(foodId, +1);
          });
        });

        decreaseButtons.forEach((button) => {
          button.addEventListener('click', () => {
            console.log('Decrease button clicked');
            const foodId = button.getAttribute('data-food-id');
            changeCartItemQuantity(foodId, -1);
          });
        });

        removeButtons.forEach((button) => {
          button.addEventListener('click', () => {
            const foodId = button.getAttribute('data-food-id');
            removeCartItem(foodId);
          });
        });

       // Add event listener to clear cart button
const clearCartButton = document.getElementById('clear-cart-button');

clearCartButton.addEventListener('click', clearCart);
      } else {
        console.error('Error retrieving cart items:', xhr.status);
      }
    }
  };
  xhr.send();
}


function changeCartItemQuantity(foodId, quantityChange) {
  console.log('Change cart item quantity:', foodId, quantityChange);

  fetch('gearbox/update_cart_items.kts.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ foodId: parseInt(foodId), quantityChange: parseInt(quantityChange) }),
  })
    .then((response) => {
      if (response.ok) {
        // Update the cart items and display them
        displayCartItems();
      } else {
        console.error('Error updating cart item:', response.status);
      }
    })
    .catch((error) => {
      console.error('Error updating cart item:', error);
    });
}


  // Function to remove a cart item
  function removeCartItem(foodId) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'gearbox/remove_cart_item.kts.php', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
          // Update the cart items in the PHP session
          displayCartItems();
        } else {
          console.error('Error removing cart item:', xhr.status);
        }
      }
    };
    xhr.send(JSON.stringify({ foodId }));
  }

  // Function to clear the cart
  function clearCart() {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'gearbox/clear_cart.kts.php', true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        if (xhr.status === 200) {
          // Display an empty cart
          displayCartItems();
        } else {
          console.error('Error clearing cart:', xhr.status);
        }
      }
    };
    xhr.send();
  }

  // Call the displayCartItems function to initially display the cart items
  displayCartItems();

  // Update the cart items count whenever the cart items change
  window.addEventListener('storage', (event) => {
    if (event.key === 'cart') {
      displayCartItems();
    }
  });
});


</script>
<script>
$(document).ready(function() {
    // Event handler for price option change (for beverages)
    $(document).on('change', 'select[name="price_option"]', function() {
        const selectedPrice = $(this).val(); // Get the selected price from the dropdown
        const productId = $(this).closest('tr').find('.add-to-cart-btn').data('product-id'); // Get the product ID

        console.log('Selected price:', selectedPrice, 'for product ID:', productId);

        // Call updatePrice function passing selectedPrice and productId
        updatePrice(selectedPrice, productId);
    });

    // Function to update UI elements based on selected price
    function updatePrice(selectedPrice, productId) {
        console.log('Updating price for product ID:', productId, 'to:', selectedPrice);
        // Optionally, update UI elements to reflect the selected price
    }

    // Event handler for add-to-cart button (for both food and beverages)
    $(document).on('click', '.add-to-cart-btn', function(e) {
        e.preventDefault(); // Prevent the default action of the anchor tag

        const productId = $(this).data('product-id'); // Get the product ID from data attribute
        const productName = $(this).data('product-name'); // Get the product name from data attribute
        let sellingPrice = $(this).data('selling-price'); // Get the default selling price from data attribute
        const cat = $(this).data('cat'); // Get the category (cat) from data attribute

        // For beverages, check if there's a selected price from the dropdown
        if ($(this).closest('tr').find('select[name="price_option"]').length > 0) {
            sellingPrice = $(this).closest('tr').find('select[name="price_option"]').val();
        }

        console.log('Add to cart clicked for product k ID:', productId, 'with price:', sellingPrice);

        // Validate that sellingPrice is defined
        if (typeof sellingPrice === 'undefined') {
            console.error('Selected price is undefined.');
            return;
        }

        // Create an object with the required data
        const requestData = {
            productId: productId,
            productName: productName,
            sellingPrice: sellingPrice,
            cat: cat,
            quantityChange: 1 // Assuming you want to add 1 quantity to the cart
        };

        // Send the AJAX request to add the item to the cart
        fetch('gearbox/add_to_cart.kts.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        })
        .then(response => response.json())
        .then(data => {
            location.reload(); // Reload the page after adding to cart (you can replace this with handling the response)
            // Perform any additional actions if needed
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });
});

</script>

<script>
$(document).ready(function() {
  $("#submit-order").click(function() {
     
    // Perform AJAX request to insert session data into the database
    $.ajax({
      url: "gearbox/proccess_order.kts.php", // Replace with the appropriate file handling the data insertion
      method: "POST",
      success: function(response) {
    // Redirect to the print page
     console.log('clicked');
},

      error: function(xhr, status, error) {
        console.log(error); // Log any errors for debugging
      }
    });
  });
});
</script>

<script>
    $(document).ready(function() {
        var currentPage = 1;

        // Function to fetch and display Tots items based on the current page
        function fetchTotsItems(page) {
            $.ajax({
                type: 'GET',
                url: 'gearbox/fetch_tot_items.kts.php',
                data: { page: page },
                dataType: 'json',
                success: function(response) {
                    // Clear previous content
                    $('#totsItemsContainer').empty();

                    if (response && response.items && response.items.length > 0) {
                        // Display fetched Tots items
                        $.each(response.items, function(index, item) {
                            var itemHtml = '<div class="col-lg-6">' +
                                '<div class="d-flex align-items-center">' +
                                '<img class="flex-shrink-0 img-fluid rounded" src="./uploaded/' + item.image + '" alt="" style="width: 80px;">' +
                                '<div class="w-100 d-flex flex-column text-start ps-4">' +
                                '<h5 class="d-flex justify-content-between border-bottom pb-2">' +
                                '<span>' + item.name + '</span>' +
                                '<span class="text-dark">Ksh' + item.price + '</span>' +
                                '</h5>' +
                                '<p class="d-flex justify-content-between border-bottom pb-2">' +
                                '<small class="fst-italic  text-dark">' + item.description + '</small>' +
                                '<span>' +
                                '<a href="#" class="f py-2 px-3 me-3 animated slideInLeft add-to-cart-btn1" ' + 
                                'data-food-id="' + item.food_id + '" ' +
                                'data-food-name="' + item.name + '" ' +
                                'data-food-price="' + item.price + '" ' +
                                'data-cat="' + item.cat + '">' +
                                '<i class="f"></i>' +
                                '</a>' +
                                '</span>' +
                                '</p>' +
                                '</div>' +
                                '</div>' +
                                '</div>';
                            $('#totsItemsContainer').append(itemHtml);
                        });

                        // Update pagination buttons
                        updatePagination(response.pagination);
                    } else {
                        console.log('No Tots items found.');
                    }
                },
                error: function(xhr, status, error) {
                    console.log('Error fetching Tots items:', error);
                }
            });
        }

        // Function to update pagination buttons
        function updatePagination(pagination) {
            var paginationContainer = $('#totsItemsContainer_pagination ul');
            paginationContainer.empty(); // Clear previous pagination buttons

            // Previous button
            var prevButton = '<li class="page-item ' + (pagination.currentPage === 1 ? 'disabled' : '') + '">' +
                '<a class="page-link" href="#" data-page="' + (pagination.currentPage - 1) + '">Previous</a>' +
                '</li>';
            paginationContainer.append(prevButton);

            // Page numbers
            for (var i = 1; i <= pagination.totalPages; i++) {
                var pageButton = '<li class="page-item ' + (pagination.currentPage === i ? 'active' : '') + '">' +
                    '<a class="page-link" href="#" data-page="' + i + '">' + i + '</a>' +
                    '</li>';
                paginationContainer.append(pageButton);
            }

            // Next button
            var nextButton = '<li class="page-item ' + (pagination.currentPage === pagination.totalPages ? 'disabled' : '') + '">' +
                '<a class="page-link" href="#" data-page="' + (pagination.currentPage + 1) + '">Next</a>' +
                '</li>';
            paginationContainer.append(nextButton);

            // Log pagination data for debugging
            console.log('Pagination:', pagination);
        }

        // Initial fetch of Tots items on page load
        fetchTotsItems(currentPage);

        // Event handler for pagination buttons
        $(document).on('click', '.pagination .page-link', function(e) {
            e.preventDefault();
            var page = parseInt($(this).data('page'));
            if (page !== currentPage) {
                currentPage = page;
                fetchTotsItems(currentPage);
            }
        });

        // Event handler for add-to-cart buttons
        $(document).on('click', '.add-to-cart-btn1', function(e) {
            e.preventDefault();
            var productId = $(this).data('food-id');
            var productName = $(this).data('food-name');
            var productPrice = $(this).data('food-price');
            var cat = $(this).data('cat'); // Get the category from data attribute

            console.log('Add to cart clicked for product ID:', productId, 'with price:', productPrice, 'and category:', cat);
            if (productId === undefined || productPrice === undefined || cat === undefined) {
                console.log('Product ID, Price, or Category is undefined');
            } else {
                const requestData = {
                    productId: productId,
                    productName: productName,
                    sellingPrice: productPrice,
                    cat: cat, // Use the category fetched from data attribute
                    quantityChange: 1 // Assuming you want to add 1 quantity to the cart
                };

                // Send the AJAX request to add the item to the cart
                fetch('gearbox/add_to_cart.kts.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                .then(response => response.json())
                .then(data => {
                   location.reload(); // Reload the page after adding to cart (you can replace this with handling the response)
                    // Perform any additional actions if needed
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            }
        });
    });
</script>
    <script>
$(document).ready(function() {
    var currentPage = 1;

    // Function to fetch and display breakfast items based on the current page
    function fetchBreakfastItems(page) {
        $.ajax({
            type: 'GET',
            url: 'gearbox/fetch_breakfast_items.kts.php',
            data: { page: page },
            dataType: 'json',
            success: function(response) {
                // Clear previous content
                $('#breakfastItemsContainer').empty();

                if (response && response.items && response.items.length > 0) {
                    // Display fetched breakfast items
                    $.each(response.items, function(index, item) {
                        var itemHtml = '<div class="col-lg-6">' +
                            '<div class="d-flex align-items-center">' +
                            '<img class="flex-shrink-0 img-fluid rounded" src="./uploaded/' + item.image + '" alt="" style="width: 80px;">' +
                            '<div class="w-100 d-flex flex-column text-start ps-4">' +
                            '<h5 class="d-flex justify-content-between border-bottom pb-2">' +
                            '<span>' + item.name + '</span>' +
                            '<span class="text-dark">Ksh' + item.price + '</span>' +
                            '</h5>' +
                            '<p class="d-flex justify-content-between border-bottom pb-2">' +
                            '<small class="fst-italic  text-dark">' + item.description + '</small>' +
                            '<span>' +
                            '<a href="#" class="f py-2 px-3 me-3 animated slideInLeft add-to-cart-btn-breakfast" ' + 
                            'data-food-id="' + item.food_id + '" ' +
                            'data-food-name="' + item.name + '" ' +
                            'data-food-price="' + item.price + '" ' +
                            'data-cat="' + item.cat + '">' +
                            '<i class="f"></i>' +
                            '</a>' +
                            '</span>' +
                            '</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        $('#breakfastItemsContainer').append(itemHtml);
                    });

                    // Update pagination buttons
                    updatePagination(response.pagination);
                } else {
                    console.log('No breakfast items found.');
                }
            },
            error: function(xhr, status, error) {
                console.log('Error fetching breakfast items:', error);
            }
        });
    }

    // Function to update pagination buttons
    function updatePagination(pagination) {
        var paginationContainer = $('#breakfastItemsContainer_pagination ul');
        paginationContainer.empty(); // Clear previous pagination buttons

        // Previous button
        var prevButton = '<li class="page-item ' + (pagination.currentPage === 1 ? 'disabled' : '') + '">' +
            '<a class="page-link" href="#" data-page="' + (pagination.currentPage - 1) + '">Previous</a>' +
            '</li>';
        paginationContainer.append(prevButton);

        // Page numbers
        for (var i = 1; i <= pagination.totalPages; i++) {
            var pageButton = '<li class="page-item ' + (pagination.currentPage === i ? 'active' : '') + '">' +
                '<a class="page-link" href="#" data-page="' + i + '">' + i + '</a>' +
                '</li>';
            paginationContainer.append(pageButton);
        }

        // Next button
        var nextButton = '<li class="page-item ' + (pagination.currentPage === pagination.totalPages ? 'disabled' : '') + '">' +
            '<a class="page-link" href="#" data-page="' + (pagination.currentPage + 1) + '">Next</a>' +
            '</li>';
        paginationContainer.append(nextButton);

        // Log pagination data for debugging
        console.log('Pagination:', pagination);
    }

    // Initial fetch of breakfast items on page load
    fetchBreakfastItems(currentPage);

    // Event handler for pagination buttons
    $(document).on('click', '.pagination .page-link', function(e) {
        e.preventDefault();
        var page = parseInt($(this).data('page'));
        if (page !== currentPage) {
            currentPage = page;
            fetchBreakfastItems(currentPage);
        }
    });

    // Event handler for add-to-cart buttons
    $(document).on('click', '.add-to-cart-btn-breakfast', function(e) {
        e.preventDefault();
        var productId = $(this).data('food-id');
        var productName = $(this).data('food-name');
        var productPrice = $(this).data('food-price');
        var cat = $(this).data('cat'); // Get the category from data attribute

        console.log('Add to cart clicked for product ID:', productId, 'with price:', productPrice, 'and category:', cat);
        if (productId === undefined || productPrice === undefined || cat === undefined) {
            console.log('Product ID, Price, or Category is undefined');
        } else {
            const requestData = {
                productId: productId,
                productName: productName,
                sellingPrice: productPrice,
                cat: cat, // Use the category fetched from data attribute
                quantityChange: 1 // Assuming you want to add 1 quantity to the cart
            };

            // Send the AJAX request to add the item to the cart
            fetch('gearbox/add_to_cart.kts.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                location.reload(); // Reload the page after adding to cart (you can replace this with handling the response)
                // Perform any additional actions if needed
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    });
});

    </script>
  <script>
 $(document).ready(function() {
    var currentPage = 1;

    // Function to fetch and display lunch items based on the current page
    function fetchLunchItems(page) {
        $.ajax({
            type: 'GET',
            url: 'gearbox/fetch_lunch_items.kts.php',
            data: { page: page },
            dataType: 'json',
            success: function(response) {
                // Clear previous content
                $('#lunchItemsContainer').empty();

                if (response && response.items && response.items.length > 0) {
                    // Display fetched lunch items
                    $.each(response.items, function(index, item) {
                        var itemHtml = '<div class="col-lg-6">' +
                            '<div class="d-flex align-items-center">' +
                            '<img class="flex-shrink-0 img-fluid rounded" src="./uploaded/' + item.image + '" alt="" style="width: 80px;">' +
                            '<div class="w-100 d-flex flex-column text-start ps-4">' +
                            '<h5 class="d-flex justify-content-between border-bottom pb-2">' +
                            '<span>' + item.name + '</span>' +
                            '<span class="text-dark">Ksh' + item.price + '</span>' +
                            '</h5>' +
                            '<p class="d-flex justify-content-between border-bottom pb-2">' +
                            '<small class="fst-italic  text-dark">' + item.description + '</small>' +
                            '<span>' +
                            '<a href="#" class="f py-2 px-3 me-3 animated slideInLeft add-to-cart-btn-lunch" ' + 
                            'data-food-id="' + item.food_id + '" ' +
                            'data-food-name="' + item.name + '" ' +
                            'data-food-price="' + item.price + '" ' +
                            'data-cat="' + item.cat + '">' +
                            '<i class="f"></i>' +
                            '</a>' +
                            '</span>' +
                            '</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        $('#lunchItemsContainer').append(itemHtml);
                    });

                    // Update pagination buttons
                    updatePagination(response.pagination);
                } else {
                    console.log('No lunch items found.');
                }
            },
            error: function(xhr, status, error) {
                console.log('Error fetching lunch items:', error);
            }
        });
    }

    // Function to update pagination buttons
    function updatePagination(pagination) {
        var paginationContainer = $('#lunchItemsContainer_pagination ul');
        paginationContainer.empty(); // Clear previous pagination buttons

        // Previous button
        var prevButton = '<li class="page-item ' + (pagination.currentPage === 1 ? 'disabled' : '') + '">' +
            '<a class="page-link" href="#" data-page="' + (pagination.currentPage - 1) + '">Previous</a>' +
            '</li>';
        paginationContainer.append(prevButton);

        // Page numbers
        for (var i = 1; i <= pagination.totalPages; i++) {
            var pageButton = '<li class="page-item ' + (pagination.currentPage === i ? 'active' : '') + '">' +
                '<a class="page-link" href="#" data-page="' + i + '">' + i + '</a>' +
                '</li>';
            paginationContainer.append(pageButton);
        }

        // Next button
        var nextButton = '<li class="page-item ' + (pagination.currentPage === pagination.totalPages ? 'disabled' : '') + '">' +
            '<a class="page-link" href="#" data-page="' + (pagination.currentPage + 1) + '">Next</a>' +
            '</li>';
        paginationContainer.append(nextButton);

        // Log pagination data for debugging
        console.log('Pagination:', pagination);
    }

    // Initial fetch of lunch items on page load
    fetchLunchItems(currentPage);

    // Event handler for pagination buttons
    $(document).on('click', '.pagination .page-link', function(e) {
        e.preventDefault();
        var page = parseInt($(this).data('page'));
        if (page !== currentPage) {
            currentPage = page;
            fetchLunchItems(currentPage);
        }
    });

    // Event handler for add-to-cart buttons
    $(document).on('click', '.add-to-cart-btn-lunch', function(e) {
        e.preventDefault();
        var productId = $(this).data('food-id');
        var productName = $(this).data('food-name');
        var productPrice = $(this).data('food-price');
        var cat = $(this).data('cat'); // Get the category from data attribute

        console.log('Add to cart clicked for product ID:', productId, 'with price:', productPrice, 'and category:', cat);
        if (productId === undefined || productPrice === undefined || cat === undefined) {
            console.log('Product ID, Price, or Category is undefined');
        } else {
            const requestData = {
                productId: productId,
                productName: productName,
                sellingPrice: productPrice,
                cat: cat, // Use the category fetched from data attribute
                quantityChange: 1 // Assuming you want to add 1 quantity to the cart
            };

            // Send the AJAX request to add the item to the cart
            fetch('gearbox/add_to_cart.kts.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
               location.reload(); // Reload the page after adding to cart (you can replace this with handling the response)
                // Perform any additional actions if needed
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    });
});

    </script>
    
  <script>
    $(document).ready(function() {
        var currentPage = 1;

        // Function to fetch and display pizza items based on the current page
        function fetchPizzaItems(page) {
            $.ajax({
                type: 'GET',
                url: 'gearbox/fetch_pizza_items.kts.php',
                data: { page: page },
                dataType: 'json',
                success: function(response) {
                    // Clear previous content
                    $('#pizzaItemsContainer .row').empty();

                    if (response && response.items && response.items.length > 0) {
                        // Display fetched pizza items
                        $.each(response.items, function(index, item) {
                            var itemHtml = '<div class="col-lg-6">' +
                                '<div class="d-flex align-items-center">' +
                                '<img class="flex-shrink-0 img-fluid rounded" src="' + item.image + '" alt="" style="width: 80px;">' +
                                '<div class="w-100 d-flex flex-column text-start ps-4">' +
                                '<h5 class="d-flex justify-content-between border-bottom pb-2">' +
                                '<span>' + item.name + '</span>' +
                                '<span class="text-dark">Ksh' + item.price + '</span>' +
                                '</h5>' +
                                '<p class="d-flex justify-content-between border-bottom pb-2">' +
                                '<small class="fst-italic  text-dark">' + item.description + '</small>' +
                                '<span>' +
                                '<a href="#" class="f py-2 px-3 me-3 animated slideInLeft add-to-cart-btn" ' +
                                'data-food-id="' + item.food_id + '" ' +
                                'data-food-name="' + item.name + '" ' +
                                'data-food-price="' + item.price + '" ' +
                                'data-cat="pizza">' +
                                '<i class="f"></i>' +
                                '</a>' +
                                '</span>' +
                                '</p>' +
                                '</div>' +
                                '</div>' +
                                '</div>';
                            $('#pizzaItemsContainer .row').append(itemHtml);
                        });
                        // Update pagination buttons
                        updatePagination(response.pagination);
                    } else {
                        console.log('No pizza items found.');
                    }
                },
                error: function(xhr, status, error) {
                    console.log('Error fetching pizza items:', error);
                }
            });
        }

        // Function to update pagination buttons
        function updatePagination(pagination) {
            var paginationContainer = $('#pizzaItemsContainer').find('.pagination');
            paginationContainer.empty(); // Clear previous pagination buttons

            // Previous button
            var prevButton = '<li class="page-item ' + (pagination.currentPage === 1 ? 'disabled' : '') + '">' +
                '<a class="page-link" href="#" data-page="' + (pagination.currentPage - 1) + '">Previous</a>' +
                '</li>';
            paginationContainer.append(prevButton);

            // Page numbers
            for (var i = 1; i <= pagination.totalPages; i++) {
                var pageButton = '<li class="page-item ' + (pagination.currentPage === i ? 'active' : '') + '">' +
                    '<a class="page-link" href="#" data-page="' + i + '">' + i + '</a>' +
                    '</li>';
                paginationContainer.append(pageButton);
            }

            // Next button
            var nextButton = '<li class="page-item ' + (pagination.currentPage === pagination.totalPages ? 'disabled' : '') + '">' +
                '<a class="page-link" href="#" data-page="' + (pagination.currentPage + 1) + '">Next</a>' +
                '</li>';
            paginationContainer.append(nextButton);

            // Log pagination data for debugging
            console.log('Pagination:', pagination);
        }

        // Initial fetch of pizza items on page load
        fetchPizzaItems(currentPage);

        // Event handler for pagination buttons
        $(document).on('click', '.pagination .page-link', function(e) {
            e.preventDefault();
            var page = parseInt($(this).data('page'));
            if (page !== currentPage) {
                currentPage = page;
                fetchPizzaItems(currentPage);
            }
        });

        // Event handler for add-to-cart buttons
        $(document).on('click', '.add-to-cart-btn', function(e) {
            e.preventDefault();
            var productId = $(this).data('food-id');
            var productName = $(this).data('food-name');
            var productPrice = $(this).data('food-price');
            var productCat = $(this).data('cat');

            console.log('Add to cart clicked for product ID:', productId, 'with price:', productPrice, 'and category:', productCat);
            if (productId === undefined || productPrice === undefined || productCat === undefined) {
                console.log('Product ID, Price, or Category is undefined');
            } else {
                const requestData = {
                    productId: productId,
                    productName: productName,
                    sellingPrice: productPrice,
                    cat: productCat,
                    quantityChange: 1 // Assuming you want to add 1 quantity to the cart
                };

                // Send the AJAX request to add the item to the cart
                fetch('gearbox/add_to_cart.kts.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                })
                .then(response => response.json())
                .then(data => {
                    location.reload(); // Reload the page after adding to cart (you can replace this with handling the response)
                    // Perform any additional actions if needed
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            }
        });
    });
    </script>
<script>
$(document).ready(function() {
    // Function to fetch and display items based on the current page and category
  $(document).ready(function() {
    // Function to fetch and display items based on the current page and category
   $(document).ready(function() {
    // Function to fetch and display items based on the current page and category
    function fetchItems(page, category, containerId) {
        $.ajax({
            type: 'GET',
            url: 'gearbox/fetch_items.kts.php',
            data: { page: page, category: category },
            dataType: 'json',
            success: function(response) {
                console.log('Response:', response); // Log the response data
                $('#' + containerId).empty(); // Clear previous content
                if (response && response[category] && response[category].items.length > 0) {
                    $.each(response[category].items, function(index, item) {
                        console.log('Item:', item); // Log each item data
                        var itemHtml = '<div class="col-lg-6">' +
                            '<div class="d-flex align-items-center">' +
                            '<img class="flex-shrink-0 img-fluid rounded" src="uploaded/' + item.image + '" alt="" style="width: 80px;">' +
                            '<div class="w-100 d-flex flex-column text-start ps-4">' +
                            '<h5 class="d-flex justify-content-between border-bottom pb-2">' +
                            '<span>' + item.product_name + '</span>' +
                            '<span class="text-dark">Ksh' + item.selling_price + '</span>' +
                            '</h5>' +
                            '<p class="d-flex justify-content-between border-bottom pb-2">' +
                            '<small class="fst-italic  text-dark">' + item.description + '</small>' +
                            '<span>' +
                            '<a href="#" class="f py-2 px-3 me-3 animated slideInLeft add-to-cart-btn" ' +
                            'data-food-id="' + item.product_id + '" ' +
                            'data-food-name="' + item.product_name + '" ' +
                            'data-food-price="' + item.selling_price + '" ' +
                            'data-cat="' + item.cat + '">' +
                            '<i class="f"></i>' +
                            '</a>' +
                            '</span>' +
                            '</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        $('#' + containerId).append(itemHtml);
                    });

                    // Update pagination buttons
                    updatePagination(response[category], page, category, containerId);
                } else {
                    console.log('No items found for category: ' + category);
                }
            },
            error: function(xhr, status, error) {
                console.log('Error fetching items for category ' + category + ':', error);
            }
        });
    }

    // Function to update pagination buttons
    function updatePagination(categoryData, currentPage, category, containerId) {
        var paginationHtml = '<nav aria-label="Page navigation"><ul class="pagination">';

        // Add previous button
        if (currentPage > 1) {
            paginationHtml += '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage - 1) + '" data-category="' + category + '" data-container="' + containerId + '">Previous</a></li>';
        }

        // Add page buttons
        for (var i = 1; i <= categoryData.total_pages; i++) {
            paginationHtml += '<li class="page-item ' + (i === currentPage ? 'active' : '') + '"><a class="page-link" href="#" data-page="' + i + '" data-category="' + category + '" data-container="' + containerId + '">' + i + '</a></li>';
        }

        // Add next button
        if (currentPage < categoryData.total_pages) {
            paginationHtml += '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage + 1) + '" data-category="' + category + '" data-container="' + containerId + '">Next</a></li>';
        }

        paginationHtml += '</ul></nav>';

        // Update pagination container
        $('#' + containerId + '_pagination').html(paginationHtml);
    }

    // Initial fetch of items for each category on page load
    fetchItems(1, 'Meat', 'meatItemsContainer');
    fetchItems(1, 'Chicken', 'chickenItemsContainer');
    fetchItems(1, 'Vegetables', 'vegetableItemsContainer');
    fetchItems(1, 'Fish', 'fishItemsContainer');
    fetchItems(1, 'Beverages', 'drinkItemsContainer');

    // Event handler for pagination buttons
    $(document).on('click', '.pagination .page-link', function(e) {
        e.preventDefault();
        var page = parseInt($(this).data('page'));
        var category = $(this).data('category');
        var containerId = $(this).data('container');
        fetchItems(page, category, containerId);
    });

    // Event handler for add-to-cart buttons
    $(document).on('click', '.add-to-cart-btn', function(e) {
        e.preventDefault();
        var productId = $(this).data('food-id');
        var productName = $(this).data('food-name');
        var productPrice = $(this).data('food-price');
        var productCat = $(this).data('cat');

        console.log('Add to cart clicked for product ID:', productId, 'with price:', productPrice, 'and category:', productCat);
        if (productId === undefined || productPrice === undefined || productCat === undefined) {
            console.log('Product ID, Price, or Category is undefined');
        } else {
            const requestData = {
                productId: productId,
                productName: productName,
                sellingPrice: productPrice,
                cat: productCat,
                quantityChange: 1 // Assuming you want to add 1 quantity to the cart
            };

            // Send the AJAX request to add the item to the cart
            fetch('gearbox/add_to_cart.kts.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                location.reload(); // Reload the page after adding to cart (you can replace this with handling the response)
                // Perform any additional actions if needed
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
    });
});

    // Function to update pagination buttons
    function updatePagination(categoryData, currentPage, category, containerId) {
        var paginationHtml = '<nav aria-label="Page navigation"><ul class="pagination">';

        // Add previous button
        if (currentPage > 1) {
            paginationHtml += '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage - 1) + '" data-category="' + category + '" data-container="' + containerId + '">Previous</a></li>';
        }

        // Add page buttons
        for (var i = 1; i <= categoryData.total_pages; i++) {
            paginationHtml += '<li class="page-item ' + (i === currentPage ? 'active' : '') + '"><a class="page-link" href="#" data-page="' + i + '" data-category="' + category + '" data-container="' + containerId + '">' + i + '</a></li>';
        }

        // Add next button
        if (currentPage < categoryData.total_pages) {
            paginationHtml += '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage + 1) + '" data-category="' + category + '" data-container="' + containerId + '">Next</a></li>';
        }

        paginationHtml += '</ul></nav>';

        // Update pagination container
        $('#' + containerId + '_pagination').html(paginationHtml);
    }

    // Initial fetch of items for each category on page load
    fetchItems(1, 'Meat', 'meatItemsContainer');
    fetchItems(1, 'Chicken', 'chickenItemsContainer');
    fetchItems(1, 'Vegetables', 'vegetableItemsContainer');
    fetchItems(1, 'Fish', 'fishItemsContainer');
    fetchItems(1, 'Beverages', 'drinkItemsContainer');

    // Event handler for pagination buttons
    $(document).on('click', '.pagination .page-link', function(e) {
        e.preventDefault();
        var page = parseInt($(this).data('page'));
        var category = $(this).data('category');
        var containerId = $(this).data('container');
        fetchItems(page, category, containerId);
    });

    // Event handler for add-to-cart buttons
    $(document).on('click', '.add-to-cart-btn', function(e) {
        e.preventDefault();
        var productId = $(this).data('food-id');
        var productName = $(this).data('food-name');
        var productPrice = $(this).data('food-price');
        var productCat = $(this).data('cat');

        console.log('Add to cart clicked for product ID:', productId, 'with price:', productPrice, 'and category:', productCat);
        if (productId === undefined || productPrice === undefined || productCat === undefined) {
            console.log('Product ID, Price, or Category is undefined');
        } else {
            // Add your add-to-cart functionality here
        }
    });
});

    // Function to update pagination buttons
    function updatePagination(categoryData, currentPage, category, containerId) {
        var paginationHtml = '<nav aria-label="Page navigation"><ul class="pagination">';

        // Add previous button
        if (currentPage > 1) {
            paginationHtml += '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage - 1) + '" data-category="' + category + '" data-container="' + containerId + '">Previous</a></li>';
        }

        // Add page buttons
        for (var i = 1; i <= categoryData.total_pages; i++) {
            paginationHtml += '<li class="page-item ' + (i === currentPage ? 'active' : '') + '"><a class="page-link" href="#" data-page="' + i + '" data-category="' + category + '" data-container="' + containerId + '">' + i + '</a></li>';
        }

        // Add next button
        if (currentPage < categoryData.total_pages) {
            paginationHtml += '<li class="page-item"><a class="page-link" href="#" data-page="' + (currentPage + 1) + '" data-category="' + category + '" data-container="' + containerId + '">Next</a></li>';
        }

        paginationHtml += '</ul></nav>';

        // Update pagination container
        $('#' + containerId + '_pagination').html(paginationHtml);
    }

    // Initial fetch of items for each category on page load
    fetchItems(1, 'Meat', 'meatItemsContainer');
    fetchItems(1, 'Chicken', 'chickenItemsContainer');
    fetchItems(1, 'Vegetables', 'vegetableItemsContainer');
    fetchItems(1, 'Fish', 'fishItemsContainer');
    fetchItems(1, 'Beverages', 'drinkItemsContainer');

    // Event handler for pagination buttons
    $(document).on('click', '.pagination .page-link', function(e) {
        e.preventDefault();
        var page = parseInt($(this).data('page'));
        var category = $(this).data('category');
        var containerId = $(this).data('container');
        fetchItems(page, category, containerId);
    });

    // Event handler for add-to-cart buttons
    $(document).on('click', '.add-to-cart-btn', function(e) {
        e.preventDefault();
        var productId = $(this).data('food-id');
        var productName = $(this).data('food-name');
        var productPrice = $(this).data('food-price');
        var productCat = $(this).data('cat');

        console.log('Add to cart clicked for product m ID:', productId, 'with price:', productPrice);
        if (productId === undefined || productPrice === undefined) {
            console.log('Product ID or Price is undefined');
        } else {
            // Add your add-to-cart functionality here
        }
    });
});

</script>

<script>
$(document).ready(function() {
    $('#searchInput').on('input', function() {
        var searchQuery = $(this).val().trim();

        // Check if search query is empty
        if (searchQuery === '') {
            // If empty, clear the search results
            $('#searchResults').empty();
            return; // Exit the function early
        }

        // Send AJAX request to fetch search results
        $.ajax({
            url: './gearbox/search.kts.php',
            method: 'POST',
            data: { query: searchQuery },
            success: function(response) {
                $('#searchResults').html(response);
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
            }
        });
    });
});
</script>

<script>
    // JavaScript code to fetch data and display it
    function fetchBusinessDetails() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', './database/fetch_business.kts.php', true);
        xhr.onload = function() {
            if (this.status === 200) {
                var data = JSON.parse(this.responseText);
                
                console.log(data);  // Check if contact2 is present in the response
                
                // Check if no error
                if (!data.error) {
                    // Update the span elements with the fetched data
                    document.getElementById('shopname').innerText = data.shop_name || '';
                    document.getElementById('shopname1').innerText = data.shop_name || '';
                    document.getElementById('location').innerText = data.location || '';
                    document.getElementById('quote').innerText = data.quote || '';
                    document.getElementById('street').innerText = data.street || '';
                    document.getElementById('address').innerText = data.address || '';
                    document.getElementById('pin').innerText = data.pin || '';
                    document.getElementById('contact1').innerText = data.contact1 || '';
                    document.getElementById('contact2').innerText = data.contact2 || ''; // This should populate contact2
                } else {
                    console.error("Error: " + data.error);
                }
            } else {
                console.error("Failed to fetch data");
            }
        };
        xhr.send();
    }

    // Call the function as soon as the DOM is fully loaded
    document.addEventListener('DOMContentLoaded', fetchBusinessDetails);
</script>






</body>

</html>