<?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>JacyJoka Apartments</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" />

    <!-- 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 py-0">
    <div class="container-xxl position-relative p-0">
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark px-4 px-lg-5 py-3 py-lg-0 fixed-top">
            <a href="" class="navbar-brand p-0">
                <h1 class="text-primary m-0"><i class="fa fa-utensils me-3"></i>JacyJoka Apartments</h1>
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
                <span class="fa fa-bars"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarCollapse">
                <div class="navbar-nav ms-auto py-0 pe-lg-4">
                    <a href="menu.php" class="nav-item nav-link active">Menu</a>
                    <a href="index.php" class="nav-item nav-link">Home</a>
                </div>
                <a href="#" class="btn btn-primary py-2 px-4" data-bs-toggle="modal" data-bs-target="#cart-modal">
                    <i class="fas fa-shopping-cart fa-2x"> 
                        <sup>
                            <span class="badge rounded-circle bg-secondary position-absolute top-0 start-100 translate-middle" id="cart-items-count">0</span>
                        </sup>
                    </i>
                </a>
            </div>
        </nav>

        <div class=" py-5 bg-dark  mb-5" style="height: 35px;">
            <div class="container text-center my-5 pt-5 pb-4">
                <!-- Content Here -->
            </div>
        </div>
    </div>
</div>

    <div class="container-xxl bg-white p-0">
        <!-- Spinner Start -->
        <div id="spinner" class="show bg-white position-fixed translate-middle w-100 vh-100 top-50 start-50 d-flex align-items-center justify-content-center">
            <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
                <span class="sr-only">Loading...</span>
            </div>
        </div>
        <!-- Spinner End -->


        <!-- Navbar & Hero Start -->
      
        <!-- Navbar & Hero End -->
   <!-- Menu Start -->
       

        <div class="container-xxl py-5 tabz">
            <div class="container tabz  ">
                <div class="text-center tabz wow fadeInUp" data-wow-delay="0.1s">
                    <h2 class=" text-center text-primary fw-normal">JacyJoka Apartments</h2>
                    <p></p>
                    <h5 class="section-title ff-secondary text-center text-primary fw-normal">Food Menu</h5>
                   
                </div>
                <div class="tab-class text-center wow fadeInUp" data-wow-delay="0.1s">
                    <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 fa-2x text-primary"></i>
                                <div class="ps-3">
                                    <small class="text-body">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 fa-2x text-primary"></i>
                                <div class="ps-3">
                                    <small class="text-body">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 fa-2x text-primary"></i>
                                <div class="ps-3">
                                    <small class="text-body">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 fa-2x  text-primary"></i>
                                <div class="ps-3">
                                    <small class="text-body">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 fa-2x text-primary"></i>
                                <div class="ps-3">
                                    <small class="text-body">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 fa-2x text-primary"></i>
                                <div class="ps-3">
                                    <small class="text-body">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 fa-2x text-primary"></i>
                                <div class="ps-3">
                                    <small class="text-body">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 fa-cocktail fa-2x text-primary"></i>
                                <div class="ps-3">
                                    <small class="text-body">Non & Alcoholics</small>
                                    <h6 class="mt-n1 mb-0">Drinks</h6>
                                </div>
                            </a>
                        </li>
                    </ul>
                 
    <div class="container py-2">
                <input type="text" id="searchInput" 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>
                </div>
            </div>
        </div>
        <!-- Menu End -->

  </div>

       
            
          

        <!-- 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>
    </div>

    <!-- 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>

<!-- add to cart -->

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

    const foodId = $(this).data('food-id'); // Get the food ID from data attribute using jQuery
    const foodName = $(this).data('food-name'); // Get the food name from data attribute using jQuery
    const foodPrice = $(this).data('food-price'); // Get the food price from data attribute using jQuery

    console.log('Add to cart clicked for food ID:', foodId);

    // Create an object with the required data
    const requestData = {
        foodId: foodId,
        foodName: foodName,
        foodPrice: foodPrice,
        quantityChange: 1
    };

    // 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(); // Log the response message
        // 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
        window.location.href = "print.php";
      },
      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 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-primary">Ksh' + item.price + '</span>' +
                                '</h5>' +
                                '<p class="d-flex justify-content-between border-bottom pb-2">' +
                                '<small class="fst-italic">' + item.description + '</small>' +
                                '<span>' +
                                '<a href="#" class="btn2 btn-primary 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 + '">' +
                                '<i class="fas fa-shopping-cart"></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 = $('#paginationContainer');
            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);
            }
        });
    });
</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-primary">Ksh' + item.price + '</span>' +
                                    '</h5>' +
                                    '<p class="d-flex justify-content-between border-bottom pb-2">' +
                                    '<small class="fst-italic">' + item.description + '</small>' +
                                    '<span>' +
                                    '<a href="#" class="btn2 btn-primary 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 + '">' +
                                    '<i class="fas fa-shopping-cart"></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 = $('.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 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);
                }
            });
        });
    </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').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="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-primary">Ksh' + item.price + '</span>' +
                            '</h5>' +
                            '<p class="d-flex justify-content-between border-bottom pb-2">' +
                            '<small class="fst-italic">' + item.description + '</small>' +
                            '<span>' +
                            '<a href="#" class="btn2 btn-primary 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 + '">' +
                            '<i class="fas fa-shopping-cart"></i>' +
                            '</a>' +
                            '</span>' +
                            '</p>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        $('#pizzaItemsContainer').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);
        }
    });
});
</script>

<script>
$(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) {
                $('#' + containerId).empty(); // Clear previous content
                if (response && response[category] && response[category].items.length > 0) {
                    $.each(response[category].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.product_name + '</span>' +
                            '<span class="text-primary">Ksh' + item.selling_price + '</span>' +
                            '</h5>' +
                            '<p class="d-flex justify-content-between border-bottom pb-2">' +
                            '<small class="fst-italic">' + item.description + '</small>' +
                            '<span>' +
                            '<a href="#" class="btn2 btn-primary 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 + '">' +
                            '<i class="fas fa-shopping-cart"></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, 'Drinks', '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);
    });
});

</script>


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

        // Check if search query is empty
        if (searchQuery.trim() === '') {
            // 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: { searchQuery: searchQuery },
            success: function(response) {
                $('#searchResults').html(response);
            }
        });
    });
});
</script>




</body>

</html>