<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Order Management</title>
  <!-- Socket.IO Client Library -->
  <script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
  <style>
    /* CSS Variables for Theming */
    :root {
      --primary-color: #007bff;
      --success-color: #28a745;
      --danger-color: #dc3545;
      --background-color: #f9f9f9;
      --card-background: white;
      --text-color: #333;
      --border-color: #ddd;
      --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }

    /* Reset and Base Styles */
    body {
      font-family: Arial, sans-serif;
      background-color: var(--background-color);
      margin: 0;
      padding: 20px;
      color: var(--text-color);
    }

    h1 {
      text-align: center;
      color: var(--primary-color);
      margin-bottom: 30px;
    }

    .order {
  background-color: #f8f9fa; /* Light background for better readability */
  border: 1px solid #ddd; /* Subtle border for separation */
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1.5rem; /* Spacing between orders */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.06); /* Depth effect */
}

.order-actions {
  display: flex;
  justify-content: space-between; /* Align buttons to the left, center, and right */
  margin-top: 1rem;
}

.order-action-button {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s, transform 0.2s; /* Smooth effects */
}

.order-action-button.add {
  background-color: #f97705; /* Teal for Add Item */
  color: white;
}

.order-action-button.update {
  background-color: #28a745; /* Green for Update Order */
  color: white;
}

.order-action-button.transfer {
  background-color: #007bff; /* Professional blue for Transfer Order */
  color: white;
}

.order-action-button:hover {
  transform: scale(1.05); /* Slight zoom for interaction */
}

.order-action-button:active {
  transform: scale(0.95); /* Click feedback */
}



    .order h2 {
      margin-top: 0;
      color: var(--primary-color);
      font-size: 1.5rem;
    }

    .order p {
      margin: 5px 0;
      color: #666;
    }

    /* Items List */
    .items-list {
      margin-top: 15px;
    }

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      border-bottom: 1px solid var(--border-color);
    }

    .item:last-child {
      border-bottom: none;
    }

    .item span {
      font-weight: bold;
    }

    /* Quantity Controls */
    .quantity-control {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .quantity-control button {
      background-color: var(--primary-color);
      color: white;
      border: none;
      padding: 5px 10px;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .quantity-control button:hover {
      background-color: darken(var(--primary-color), 10%);
    }

    .quantity-control button:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }

    .quantity-control button.remove {
      background-color: var(--danger-color);
    }

    .quantity-control button.remove:hover {
      background-color: darken(var(--danger-color), 10%);
    }

    /* Add Item Section */
    .add-item {
      display: flex;
      gap: 10px;
      margin-top: 15px;
    }

    .add-item input {
      padding: 8px;
      border: 1px solid var(--border-color);
      border-radius: 4px;
      flex: 1;
    }

    .add-item button {
      background-color: var(--success-color);
      color: white;
      border: none;
      padding: 8px 15px;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .add-item button:hover {
      background-color: darken(var(--success-color), 10%);
    }

    /* Update Button */
    .update-button {
      background-color: var(--success-color);
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      cursor: pointer;
      margin-top: 20px;
      width: 100%;
      transition: background-color 0.3s ease;
    }

    .update-button:hover {
      background-color: darken(var(--success-color), 10%);
    }

    /* Modal Styles */
    .modal {
      display: none;
      position: fixed;
      z-index: 1;
      left: 150px;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
     
    }

    .modal-content {
      background-color: var(--card-background);
   
      padding: 20px;
   
    
      border: 1px solid var(--border-color);
      width: 75%;
    
      max-height: 80vh; /* Critical: Constrains height for inner scroll */
      border-radius: 8px;
      box-shadow: var(--shadow);
    
    }

 .modal-items-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  padding: 1rem;
  overflow-y: auto;
  max-height: 400px;
  height: 400px; /* Fallback */
  scrollbar-width: thin;
  flex-shrink: 0; /* Critical if inside another flex container */
}



    .close {
      color: #555252;
      float: right;
      
      font-size: 32px;
      font-weight: bold;
      cursor: pointer;
    }

    .close:hover {
      color: var(--text-color);
    }

    .modal-item {
      display: flex;
      justify-content: space-between;
      padding: 10px;
      border-bottom: 1px solid var(--border-color);
     
    }

    .modal-item:last-child {
      border-bottom: none;
    }

    .modal-item button {
      background-color: var(--primary-color);
      color: white;
      border: none;
      padding: 5px 10px;
      border-radius: 4px;
      cursor: pointer;
    }

    .modal-item button:hover {
      background-color: darken(var(--primary-color), 10%);
    }

    /* Error Message Styles */
    #error-message-container {
      background-color: #f8d7da;
      color: #721c24;
      padding: 10px;
      margin-top: 10px;
      border: 1px solid #f5c6cb;
      border-radius: 4px;
      text-align: center;
      display: none;
    }

    #passcodeModal {
      display: none;
      position: fixed;
      z-index: 2;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0, 0, 0, 0.5);
    }

    #passcodeModal .modal-content {
      background-color: white;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 500px;
      border-radius: 8px;
    }

    #passcodeModal .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    #passcodeModal .close:hover {
      color: black;
    }

    #passcodeModal input[type="password"] {
      width: 100%;
      padding: 10px;
      margin: 10px 0;
      box-sizing: border-box;
    }

    #passcodeModal button {
      background-color: #007bff;
      color: white;
      padding: 10px 15px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    #passcode-container {
      position: absolute;
      top: 60px;
      right: 20px;
      width: 200px;
      text-align: right;
    }

    #passCodeInput {
      width: 100%; /* Ensure input fills the container */
      padding: 8px;
      margin-top: 5px;
      box-sizing: border-box;
    }

    /* Waiter Selection Modal */
    #waiterModal {
      display: none;
      position: fixed;
      z-index: 3;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0, 0, 0, 0.5);
    }

    #waiterModal .modal-content {
      background-color: white;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 500px;
      border-radius: 8px;
    }

    #waiterModal .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }

    #waiterModal .close:hover {
      color: black;
    }

    #waiterModal select {
      width: 100%;
      padding: 10px;
      margin: 10px 0;
      box-sizing: border-box;
    }

    #waiterModal button {
      background-color: #007bff;
      color: white;
      padding: 10px 15px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }


  
.row {
  display: flex;
  justify-content: center; /* Center-align the cards */
  gap: 1.5rem; /* Space between cards in a row */
  flex-wrap: wrap; /* Wraps cards to fit */
}

.modal-item {
  flex: 1 1 calc(25% - 1.5rem); /* Allows up to 4 cards per row */
  max-width: calc(25% - 1.5rem); /* Prevents cards from being too wide */
  min-width: 200px; /* Minimum size for each card */
}

.card {
  /* Retains the card styles from earlier */
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 10px;
  padding: 1rem;
  text-align: center;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.06);
  transition: transform 0.2s, box-shadow 0.2s;
}





.category-row {
  display: flex;
  gap: 1.5rem; /* Space between items */
  padding: 1.5rem;
  overflow-x: scroll; /* Prevent visible scroll bar */
  scroll-behavior: smooth; /* Smooth scrolling */

  position: relative; /* For pseudo-elements or controls, if needed */
}

.category-item {
  padding: 0.75rem 1.5rem; /* Balanced padding */
  background: linear-gradient(135deg, #1e90ff, #0073e6); /* Professional blue gradient */
  border-radius: 8px; /* Rounded corners */
  text-align: center;
  font-family: 'Arial', sans-serif; /* Modern font */
  font-size: 1rem;
  font-weight: bold;
  color: #fff; /* White text for contrast */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.06); /* Softer shadows */
  flex-shrink: 0; /* Ensure items don't shrink */
  width: 150px; /* Fixed width for uniformity */
  transition: transform 0.2s, box-shadow 0.2s; /* Hover effects */
}

.category-item:hover {
  transform: scale(1.05); /* Slight zoom on hover */
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.15), 0 3px 6px rgba(0, 0, 0, 0.1); /* Enhanced shadow */
}

.category-item:active {
  transform: scale(0.98); /* Click feedback */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2), 0 1px 2px rgba(0, 0, 0, 0.1); /* Subtle depth adjustment */
}




  /* Modal Styling */
  .special-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            overflow: auto;
        }

        .special-modal-content {
            background-color: #fff;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            max-width: 800px;
            width: 90%;
            position: relative;
        }

        .special-close {
            position: absolute;
            top: 1rem;
            right: 1.5rem;
            font-size: 1.5rem;
            color: #888;
            cursor: pointer;
            transition: color 0.3s ease;
        }

        .special-close:hover {
            color: #333;
        }

        h2 {
            font-size: 1.8rem;
            color: #333;
            margin-bottom: 1.5rem;
        }

        /* Category Buttons */
        .special-category-container {
            display: flex;

            flex-wrap: wrap;
            gap: 0.8rem;
            margin-bottom: 1.5rem;
        }

        .special-category-button {
            padding: 0.8rem 1.2rem;
            width: 120px;
            background-color: #007BFF;
            color: #fff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: background-color 0.3s ease;
        }

        .special-category-button:hover {
            background-color: #0056b3;
        }

        /* Selected Special Needs */
        #selected-specialNeeds {
            font-size: 1rem;
            color: #555;
            margin-bottom: 1.5rem;
            font-weight: 500;
        }

        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 0.8rem;
            margin-bottom: 1.5rem;
        }

        .action-buttons button {
            padding: 0.8rem 1.2rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: background-color 0.3s ease;
        }

        #remove-all-btn {
          width: 80px;
            background-color: #dc3545;
            color: #fff;
        }

        #remove-all-btn:hover {
            background-color: #a71d2a;
        }

        #save-btn {
          width: 80px;
            background-color: #28a745;
            color: #fff;
        }

        #save-btn:hover {
            background-color: #1e7e34;
        }

        /* Special Needs Cards */
        .special-specialNeeds-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 1rem;
        }

        .special-card {
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .special-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .special-card button {
            padding: 0.5rem 1rem;
            background-color: #28a745;
            color: #fff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: background-color 0.3s ease;
        }

        .special-card button:hover {
            background-color: #1e7e34;
        }

        /* Trigger Button */
        #special-openModal {
            padding: 1rem 2rem;
            background-color: #007BFF;
            color: #fff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s ease;
        }

        #special-openModal:hover {
            background-color: #0056b3;
        }



    
    .special-needs-row {
        display: grid;
        grid-template-columns: 1fr auto auto; /* Text takes up most of the row, buttons auto-size */
        align-items: center; /* Vertically align text and buttons */
        gap: 5px; /* Space between elements */
        margin-bottom: 5px; /* Spacing below the row */
    }

    .special-needs-text {
        font-size: 14px; /* Adjusted font size for readability */
    }

    .special-needs-btn {
        font-size: 12px;
        padding: 5px 15px;
        cursor: pointer;
        border: none;
        border-radius: 3px;
        color: white;
    }

    .special-needs-btn.add-btn {
        background-color: #28a745; /* Green for Add */
    }

    .special-needs-btn.add-btn:hover {
        background-color: #218838; /* Darker green for hover */
    }

    .special-needs-btn.remove-btn {
        background-color: #dc3545; /* Red for Remove */
    }

    .special-needs-btn.remove-btn:hover {
        background-color: #c82333; /* Darker red for hover */
    }


    .table-calendar {
      display: grid;
      grid-template-columns: repeat(6, 1fr); /* Adjust columns as needed */
      gap: 10px;
      padding: 20px;
    }
    .table-item {
      padding: 20px;
      border: 1px solid #ccc;
      border-radius: 5px;
      text-align: center;
      background-color: #f9f9f9;
    }
    .table-item button {
      margin-top: 10px;
      padding: 5px 10px;
      cursor: pointer;
    }
    .table-modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
      z-index: 9999;
      justify-content: center;
      align-items: center;
    }
    .table-modal-content {
  background: white;
  padding: 20px;
  border-radius: 10px;
  max-width: 800px;
  width: 90%;
  max-height: 400px; /* Adjust to suit your design */
  overflow-y: auto; /* Enables scrolling for overflowing content */
}

    .table-close {
      float: right;
      font-size: 20px;
      font-weight: bold;
      cursor: pointer;
    }
    .table-close:hover {
      color: red;
    }


    #openTableModal {
      font-size: 20px;
      padding: 10px;
      border: none;
      background: none;
      cursor: pointer;
    }
    #openTableModal i {
      color: #555;
    }
    #openTableModal:hover i {
      color: #007BFF; /* Change color on hover */
    }

    /* Toast Notification Styles */
    .toast-container {
      position: fixed;
      top: 20px;
      right: 20px;
      z-index: 10000;
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .toast {
      background-color: #28a745;
      color: white;
      padding: 16px 24px;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      min-width: 300px;
      max-width: 400px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      animation: slideInRight 0.3s ease-out;
      font-size: 14px;
    }

    .toast.error {
      background-color: #dc3545;
    }

    .toast.warning {
      background-color: #ffc107;
      color: #333;
    }

    .toast.info {
      background-color: #17a2b8;
    }

    .toast-close {
      background: none;
      border: none;
      color: white;
      font-size: 20px;
      cursor: pointer;
      padding: 0;
      margin-left: 15px;
      opacity: 0.8;
      line-height: 1;
    }

    .toast-close:hover {
      opacity: 1;
    }

    .toast.warning .toast-close {
      color: #333;
    }

    @keyframes slideInRight {
      from {
        transform: translateX(100%);
        opacity: 0;
      }
      to {
        transform: translateX(0);
        opacity: 1;
      }
    }

    @keyframes slideOutRight {
      from {
        transform: translateX(0);
        opacity: 1;
      }
      to {
        transform: translateX(100%);
        opacity: 0;
      }
    }

    .toast.hiding {
      animation: slideOutRight 0.3s ease-out forwards;
    }

</style>



</head>
<body>
  <!-- Toast Container -->
  <div id="toastContainer" class="toast-container"></div>

  <h1 id="companyTitle">Cafe Order Management System</h1>


  <span id="selectedTable"> </span>


  <!-- Modal -->
  <div class="table-modal" id="tableModal">
    <div class="table-modal-content">
      <span class="table-close" id="closeTableModal">&times;</span>
      <div class="table-calendar" id="calendar"></div>
    </div>
  </div>

  <div id="passcode-container">
    Enter PassCode:
    <input type="password" id="passCodeInput" required>
  </div>

  <div id="passcodeModal" class="modal">
    <div class="modal-content">
      <span class="close" onclick="closePasscodeModal()">&times;</span>
      <h2>Enter Passcode</h2>
      <input type="password" id="passcodeInputModal" placeholder="Passcode">
      <div id="passcodeError" style="color: red; display: none;"></div>
    </div>
  </div>






<!-- Modal -->
<div id="special-specialNeedsModal" class="special-modal">
    <div class="special-modal-content">
        <span class="special-close">&times;</span>
        <h2>Special Needs</h2>
        <div id="special-categories" class="special-category-container">
            <!-- Category buttons will be added here -->
        </div>

        <div class="row">
          <div id="selected-specialNeeds">
            Selected Special Needs: None
        </div>
        <div class="action-buttons">
          <button id="remove-all-btn">Remove</button>
          <button id="save-btn">Save</button>
      </div>
        </div>
      

     

        <div id="special-specialNeeds" class="special-specialNeeds-container">
            <!-- Special needs list will be displayed here -->
        </div>
    </div>
</div>




  <!-- Waiter Selection Modal -->
  <div id="waiterModal" class="modal">
    <div class="modal-content">
      <span class="close" onclick="closeWaiterModal()">&times;</span>
      <h2>Select Waiter</h2>
      <select id="waiterSelect">
        <option value="">Select Waiter</option>
      </select>
      <button onclick="transferOrder()">Transfer Order</button>
    </div>
  </div>

  <div id="orders-container"></div>

  <!-- Modal for Adding Items -->
  <div id="itemModal" class="modal">
    <div class="modal-content" style="overflow-y: scroll;">
      <span class="close" onclick="closeModal()">&times;</span>
   

      <div id="categoryContainer" class="category-row">

      </div>


      <script >





let currenOrderDetailId = null;//current
let selectedSpecialNeeds = [];
let  currentOrderId=null;
let tableNo=null;
const SelectedSpecialNeedsForItem = [];


        // const categoryRow = document.querySelector('.category-row');
        
        // let startX = 0;
        // let scrollLeft = 0;
        
        // categoryRow.addEventListener('touchstart', (e) => {
        //   startX = e.touches[0].pageX; // Record starting point
        //   scrollLeft = categoryRow.scrollLeft; // Store current scroll position
        // });
        
        // categoryRow.addEventListener('touchmove', (e) => {
        //   const x = e.touches[0].pageX;
        //   const walk = startX - x; // Calculate swipe distance
        //   categoryRow.scrollLeft = scrollLeft + walk; // Adjust scroll position
        // });
        
        
        const renderCategories = async () => {
  try {
    const res = await fetch('/api/category');
    const categories = await res.json(); // Assuming the API returns an array of category objects

    const container = document.getElementById('categoryContainer');
    container.innerHTML = ''; // Clear any existing content

    categories.forEach(category => {
      const item = document.createElement('div');
      item.classList.add('category-item');
      item.textContent = category.name; // Customize to match your API response structure

      // Add click event listener to alert the category ID
      item.addEventListener('click', () => {
        onlySomeCategory(category._id)   
         });

      container.appendChild(item);
    });
  } catch (error) {
    console.error('Error fetching categories:', error);
  }
};

renderCategories();





                </script>
      <div id="error-message-container"></div>
      <div id="modal-items-list"></div>
    </div>
  </div>

  <script>
    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');
    const userId = sessionStorage.getItem('userId');
    let currentUserId = null;
    window.currentUserId = null; // Make accessible globally for KitchenPrinter
    let currentOrderIdForUpdate = null;
    let selectedWaiterId = null;
    let currentOrderNo = null;
let currentOrderIdForTransfer=null
let items=[];

    // Sample data (replace with your actual data from the backend)
    let fullOrders = [];
    window.fullOrders = fullOrders; // Make accessible globally for KitchenPrinter
    let originalOrdersState = {}; // Store original state for comparison




    if (!companyId || !branchId) {
  console.log('Company ID and Branch ID are required. please Login again');
  window.location.href = "/"; // Redirect to the login page
}





    // Render orders
    const ordersContainer = document.getElementById("orders-container");

    function renderOrders(orders) {
  ordersContainer.innerHTML = ""; // Clear existing content
  //console.log("orders are", orders);
  const filteredOrders = orders.filter(order => order.status === "pending");
  
  // Store original state for comparison when updating
  originalOrdersState = {};
  filteredOrders.forEach((order) => {
    originalOrdersState[order._id] = {
      items: order.items.map(item => ({
        itemId: item.itemId.toString(),
        itemName: item.itemName,
        quantity: item.quantity,
        orderDetailId: item._id.toString(),
        specialNeeds: item.specialNeeds || []
      }))
    };
  });
  
  filteredOrders.forEach((order) => {
    const orderDiv = document.createElement("div");
    orderDiv.className = "order";

    // Convert server's UTC time to local time
    const createdAtUTC = new Date(order.createdAt); // Assuming createdAt is in UTC
    const localCreatedAt = createdAtUTC.toLocaleString(); // Convert to local time zone
    const now = new Date();
    const timePassed = calculateTimePassed(createdAtUTC, now);

    orderDiv.innerHTML = `
      <h2>Order No: ${order.orderNo}</h2>
  <p style="display: flex; align-items: center; gap: 5px; margin: 0; font-size: 14px;">
 <span id="table_${order._id}"> Table No: ${order.tableNo} </span>
  <button  onclick="openTableModal('${order._id}')"  style="padding: 5px 5px; font-size: 12px; width:40px; display: flex; align-items: left; justify-content: center;">
    <i class="fas fa-table"></i>
  </button>
</p>


      <p>Created At: ${localCreatedAt}</p>
      <p>Time Passed: ${timePassed}</p>
      <h3>Items:</h3>
      <div class="items-list" id="items-${order._id}"></div>

    <div class="order-actions">
  <button class="order-action-button add" onclick="openModal('${order._id}')">
    Add Item
  </button>
  <button class="order-action-button update" onclick="updateOrder('${order._id}')">
    Update Order
  </button>
  <button class="order-action-button transfer" onclick="loadWaiters('${order._id}')">
    Transfer Order
  </button>
 
</div>

    `;

    const itemsContainer = orderDiv.querySelector(`#items-${order._id}`);
    console.log(order.items);
    order.items.forEach((item) => {
      renderItem(order._id, item.itemId, item.quantity, itemsContainer, item._id, item.itemName,item.selling_price,item.specialNeeds);
    });

    ordersContainer.appendChild(orderDiv);
  });
}
function openTableModal(orderId)
{
  currentOrderId=orderId;
  document.getElementById('tableModal').style.display = 'flex';

}

// Helper function to calculate time passed
function calculateTimePassed(startDate, endDate) {
  const diffMs = endDate - startDate; // Difference in milliseconds
  const diffMinutes = Math.floor(diffMs / (1000 * 60));
  const diffHours = Math.floor(diffMinutes / 60);
  const diffDays = Math.floor(diffHours / 24);

  if (diffDays > 0) {
    return `${diffDays} day(s) ago`;
  } else if (diffHours > 0) {
    return `${diffHours} hour(s) ago`;
  } else if (diffMinutes > 0) {
    return `${diffMinutes} minute(s) ago`;
  } else {
    return `Just now`;
  }
}


    function loadWaiters(orderId) {
      currentOrderIdForTransfer=orderId;
      fetch(`/api/users?companyId=${companyId}`)
        .then(response => response.json())
        .then(data => {
          displayWaiters(data, orderId);
        })
        .catch(error => console.error('Error loading waiters:', error));
    }

    function displayWaiters(waiters, orderId) {
      const waiterSelect = document.getElementById('waiterSelect');
      waiterSelect.innerHTML = ""; // Clear existing options
     console.log(waiters);
      waiters.forEach((waiter) => {
        waiterSelect.innerHTML += `<option value="${waiter._id}">${waiter.username}</option>`;
      });

     // selectedWaiterId = orderId;
      openWaiterModal();
    }

    function openWaiterModal() {
      document.getElementById('waiterModal').style.display = 'block';
    }

    function closeWaiterModal() {
      document.getElementById('waiterModal').style.display = 'none';
    }

    function transferOrder() {
      const waiterSelect = document.getElementById('waiterSelect');
      const selectedWaiterId = waiterSelect.value;

      if (!selectedWaiterId) {
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('Please select a waiter.', 'warning', 3000);
        } else {
          alert('Please select a waiter.');
        }
        return;
      }

      fetch(`/api/cafeTransfer/create?orderId=${currentOrderIdForTransfer}&waiterId=${selectedWaiterId}&userId=${currentUserId}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
      if (response.ok) {
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('Order transferred successfully.', 'success', 3000);
        } else {
          alert('Order transferred successfully.');
        }
        closeWaiterModal();
        getAllOrders(currentUserId); // Refresh orders
      } else {
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('Failed to transfer order.', 'error', 3000);
        } else {
          alert('Failed to transfer order.');
        }
      }
    })
      .catch(error => {
        console.error('Error transferring order:', error);
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('An error occurred while transferring the order.', 'error', 3000);
        } else {
          alert('An error occurred while transferring the order.');
        }
      });
    }

    // Render a single item
    function renderItem(orderId, itemId, quantity, container, orderDetailId, itemName, selling_price, specialNeeds) {
    const itemDiv = document.createElement("div");
    itemDiv.className = "item";
    
    // Convert the `specialNeeds` array into a user-friendly format
    const specialNeedsDisplay = Array.isArray(specialNeeds) && specialNeeds.length > 0 
    ? specialNeeds.join(", ") // Join elements with a comma and space
    : "None"; // Display "None" if the array is empty or invalid

    itemDiv.innerHTML = `
    <span style="display:none">ItemId: ${itemId}</span>
    <span>Food Name: ${itemName}</span>
    <span>Price: ${selling_price}</span><div class="special-needs-row">
    <span id="special_${orderDetailId}" class="special-needs-text">SP: ${specialNeedsDisplay}</span>
    <button onclick="addSpecialNeed('${orderDetailId}')" class="special-needs-btn add-btn">+</button>
    <button onclick="removeSpecialNeed('${orderDetailId}')" class="special-needs-btn remove-btn">-</button>
</div>

    <h2 style="display:none">OrderDetail Id: ${orderDetailId}</h2>
    <div class="quantity-control">
        <button onclick="updateQuantity('${orderId}', '${itemId}', -1)">-</button>
        <span id="quantity-${orderId}-${itemId}">${quantity}</span>
        <button onclick="updateQuantity('${orderId}', '${itemId}', 1)">+</button>
        <button class="remove" onclick="removeItem('${orderId}', '${itemId}')">Remove</button>
    </div>
    <strong>Total: ${selling_price * quantity}</strong>
`;

    container.appendChild(itemDiv);
}

// Update quantity and total
function updateQuantity(orderId, itemId, change) {
  const quantityElement = document.getElementById(`quantity-${orderId}-${itemId}`);
  let quantity = parseInt(quantityElement.textContent);
  quantity += change;
  if (quantity < 0) quantity = 0; // Prevent negative quantities
  quantityElement.textContent = quantity;

  // Recalculate total
  const itemDiv = quantityElement.closest('.item');
  const sellingPrice = parseFloat(itemDiv.querySelector('span:nth-child(3)').textContent.split(": ")[1]);
  const totalElement = itemDiv.querySelector('strong');
  const total = sellingPrice * quantity;
  totalElement.textContent = `Total: ${total}`;
}






    // Remove item
    function removeItem(orderId, itemId) {
      const itemsContainer = document.getElementById(`items-${orderId}`);
      const itemDiv = document.getElementById(`quantity-${orderId}-${itemId}`).parentElement.parentElement;
      itemsContainer.removeChild(itemDiv);
    }

    // Open modal to add items
    function openModal(orderId) {
      currentOrderNo = orderId;
      document.getElementById('itemModal').style.display = 'block';
      loadItems();
    }

    // Close modal
    function closeModal() {
      document.getElementById('itemModal').style.display = 'none';
      document.getElementById('error-message-container').style.display = 'none'; // Hide error message
    }

    // Load items from backend
    function loadItems() {
      fetch(`/api/items?companyId=${companyId}`)
        .then(response => response.json())
        .then(data => {
          items = data;
          displayItems(data);
        })
        .catch(error => console.error('Error loading items:', error));
    }
   

    function displayItems(items) {
  const modalItemsList = document.getElementById('modal-items-list');
  modalItemsList.innerHTML = ''; // Clear previous items

  const rowDiv = document.createElement('div'); // Create a row container
  rowDiv.className = 'row'; // Add a class for styling

  items.forEach((item, index) => {
    // Create a card container for each item
    const itemDiv = document.createElement('div');
    itemDiv.className = 'modal-item'; // The class for individual cards
    itemDiv.innerHTML = `
      <div class="card">
        <h3>${item.name}</h3>
        <p>Price: $${item.selling_price}</p>
        <button onclick="addItemToOrder('${item._id}', '${item.name}','${item.selling_price}')">Add</button>
      </div>
    `;
    rowDiv.appendChild(itemDiv); // Add the item to the row

    // After every 3rd or 4th item, create a new row
    if ((index + 1) % 4 === 0 || index === items.length - 1) {
      modalItemsList.appendChild(rowDiv.cloneNode(true)); // Append the current row to the list
      rowDiv.innerHTML = ''; // Clear the row for the next set of items
    }
  });
}



    // Add item to order
    function addItemToOrder(itemId,name,price) {
      const itemsContainer = document.getElementById(`items-${currentOrderNo}`);
      const existingItems = itemsContainer.querySelectorAll('.item span');
      let itemExists = false;

      // Check if the item already exists in the order
      existingItems.forEach(item => {
      
        if (item.textContent.split(': ')[1] === itemId) {
          itemExists = true;
        }
      });

      if (itemExists) {
        displayErrorMessage("Item is already in the order.");
        return;
      }

      renderItem(currentOrderNo, itemId, 1, itemsContainer, "newOrder",name,price);
    
    }

    // Display error message in modal
    function displayErrorMessage(message) {
      const errorMessageContainer = document.getElementById('error-message-container');
      errorMessageContainer.textContent = message;
      errorMessageContainer.style.display = 'block';

      // Hide the error message after 3 seconds
      setTimeout(() => {
        errorMessageContainer.style.display = 'none';
      }, 3000);
    }

    // Update a specific order
    function performOrderUpdate(orderId) {
    const itemsContainer = document.getElementById(`items-${orderId}`);
    const itemDivs = itemsContainer.querySelectorAll(".item");
    const items = [];
    const currentItemsMap = {};

    itemDivs.forEach((itemDiv) => {
        const itemId = itemDiv.querySelector("span").textContent.split(": ")[1];
        const orderDetailId = itemDiv.querySelector("h2").textContent.split(": ")[1];
        const quantity = parseInt(itemDiv.querySelector(".quantity-control span").textContent);
        
        // Retrieve item name from the span
        const itemNameSpan = itemDiv.querySelector("span:nth-child(2)");
        const itemName = itemNameSpan ? itemNameSpan.textContent.split(": ")[1] : '';
        
        // Retrieve special needs data
        const specialNeedsElement = itemDiv.querySelector("#special_" + orderDetailId);
        const specialNeedsText = specialNeedsElement ? specialNeedsElement.textContent.split(":")[1]?.trim() : "None";
        const specialNeeds = specialNeedsText === "None" || !specialNeedsText ? [] : specialNeedsText.split(", ").map(s => s.trim());

        items.push({ itemId, quantity, orderDetailId, specialNeeds });
        currentItemsMap[itemId] = { itemId, quantity, itemName, specialNeeds };
    });

    // Calculate changes
    const originalItems = originalOrdersState[orderId]?.items || [];
    const originalItemsMap = {};
    originalItems.forEach(item => {
        originalItemsMap[item.itemId] = item;
    });

    const changes = {
        added: [],
        removed: [],
        quantityChanged: []
    };

    // Find added items and quantity changes
    Object.keys(currentItemsMap).forEach(itemId => {
        const current = currentItemsMap[itemId];
        const original = originalItemsMap[itemId];
        
        if (!original) {
            // New item added
            changes.added.push({
                itemId: current.itemId,
                itemName: current.itemName,
                quantity: current.quantity,
                specialNeeds: current.specialNeeds
            });
        } else if (original.quantity !== current.quantity) {
            // Quantity changed
            changes.quantityChanged.push({
                itemId: current.itemId,
                itemName: current.itemName,
                previousQuantity: original.quantity,
                currentQuantity: current.quantity,
                specialNeeds: current.specialNeeds
            });
        }
    });

    // Find removed items
    Object.keys(originalItemsMap).forEach(itemId => {
        if (!currentItemsMap[itemId]) {
            const original = originalItemsMap[itemId];
            changes.removed.push({
                itemId: original.itemId,
                itemName: original.itemName,
                quantity: original.quantity,
                specialNeeds: original.specialNeeds
            });
        }
    });

    const updatedOrder = {
        orderId,
        items,
    };

    updateCafeOrder(updatedOrder, orderId, changes);
}


    async function updateCafeOrder(updatedOrder, orderId, changes) {
      try {
        const response = await fetch("/api/cafeorder/update-order", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(updatedOrder),
        });

        if (response.ok) {
      
          // Save print data to database immediately after successful update (don't wait for print)
          if (changes && (changes.added.length > 0 || changes.removed.length > 0 || changes.quantityChanged.length > 0)) {
            // Find order details for saving print data
            const order = fullOrders.find(o => o._id === orderId);
            if (order && window.kitchenPrinter) {
              const printData = {
                id: order.orderNo || 'N/A',
                table: order.tableNo || null,
                waiter: order.userName || 'N/A',
                changes: changes,
                orderId: orderId
              };
              // Save print data immediately (async, don't wait)
              window.kitchenPrinter.savePrintDataToDatabase(printData);
              
              // Print changes (async, don't wait)
           //   window.kitchenPrinter.printOrderChanges(printData);


                  // Show toast notification instead of alert
          if (window.showToast) {
            window.showToast('Order updated successfully!', 'success', 3000);
          } else {
            alert("Order updated successfully!");
          }
          


            }
          }
          
          // Update original state after successful update
          getAllOrders(currentUserId);
        } else {
          const errorResponse = await response.json();
          // Show toast notification instead of alert
          if (window.showToast) {
            window.showToast(`Failed to update order: ${errorResponse.message || 'Unknown error occurred'}`, 'error', 3000);
          } else {
            alert(`Failed to update order: ${errorResponse.message || 'Unknown error occurred'}`);
          }
        }
      } catch (error) {
        console.error("Error updating order:", error);
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('An error occurred while updating the order. Please try again.', 'error', 3000);
        } else {
          alert("An error occurred while updating the order. Please try again.");
        }
      }
    }

    // Fetch all orders from the backend
    function getAllOrders(currentUserId) {
      
      fetch(`/api/cafeorder?companyId=${companyId}&&userId=${currentUserId}`)
        .then(response => response.json())
        .then(result => {
          fullOrders = result.data;
          window.fullOrders = fullOrders; // Update global reference
       //   console.log(fullOrders);
          renderOrders(fullOrders);
        })
        .catch(error => console.error('Error fetching orders:', error));
    }

    // Initial render
    // getAllOrders();

    // Add event listener to check input length and verify passcode
    const passCodeInput = document.getElementById("passCodeInput");

    passCodeInput.addEventListener("input", function () {
      if (this.value.length === 4) {
        verifyPassCode(this.value);
      }
    });

    // Function to verify the passcode with the backend
    async function verifyPassCode(passcode) {
      try {
        const response = await fetch(`api/users/getByPasscode?passcode=${passcode}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (response.ok) {
          const data = await response.json();
          currentUserId = data.userId;
          window.currentUserId = currentUserId; // Update global reference
          getAllOrders(currentUserId);
          passCodeInput.value = "";
        } else {
          // Show toast notification instead of alert
          if (window.showToast) {
            window.showToast('Invalid passcode. Please try again.', 'error', 3000);
          } else {
            alert('Invalid passcode. Please try again.');
          }
        }
      } catch (error) {
        console.error('Error verifying passcode:', error);
        // Show toast notification instead of alert
        if (window.showToast) {
          window.showToast('An error occurred while verifying the passcode.', 'error', 3000);
        } else {
          alert('An error occurred while verifying the passcode.');
        }
      }
    }

    function updateOrder(orderId) {
      currentOrderIdForUpdate = orderId;
      document.getElementById('passcodeModal').style.display = 'block';
    }

    function verifyPasscodeFromModal() {
      const passcode = document.getElementById('passcodeInputModal').value;
      verifyPasscodeForUpdate(passcode, currentOrderIdForUpdate);
    }

    async function verifyPasscodeForUpdate(passcode, orderId) {
      try {
        const response = await fetch(`api/users/getByPasscode?passcode=${passcode}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        });

        if (response.ok) {
          const data = await response.json();
          const userId = data.userId;
          if (currentUserId === userId) {
            closePasscodeModal();
            performOrderUpdate(orderId);
          } else {
            document.getElementById('passcodeError').textContent = 'Passcode valid, but user does not match.';
            document.getElementById('passcodeError').style.display = 'block';
          }
        } else {
          document.getElementById('passcodeError').textContent = 'Invalid passcode. Please try again.';
          document.getElementById('passcodeError').style.display = 'block';
        }
      } catch (error) {
        console.error('Error verifying passcode:', error);
        document.getElementById('passcodeError').textContent = 'An error occurred while verifying the passcode.';
        document.getElementById('passcodeError').style.display = 'block';
      }
    }

    function closePasscodeModal() {
      document.getElementById('passcodeModal').style.display = 'none';
      document.getElementById('passcodeError').style.display = 'none';
      document.getElementById('passcodeInputModal').value = '';
    }

    const passcodeInputModal = document.getElementById("passcodeInputModal");

    passcodeInputModal.addEventListener("input", function () {
      if (this.value.length === 4) {
        verifyPasscodeFromModal();
      }
    });



    function onlySomeCategory(categoryId) {
      console.log('items:',items);
  const someItems = items.filter((item) => {
    // Check if categoryId exists before calling toString
    if (!item.categoryId) {
      return false;
    }
    return item.categoryId.toString() === categoryId.toString();
  });

  if (someItems.length === 0) {
    console.warn(`No items found for category ID: ${categoryId}`);
  }

  displayItems(someItems);
}







    // Function to fetch data from API
    async function fetchData(url) {
      try {
          const response = await fetch(url);
          return await response.json();
      } catch (error) {
          console.error('Error fetching data:', error);
          return [];
      }
  }


  function removeSpecialNeed(orderDetailId) {
     
     updateSelectedSpecialNeeds(orderDetailId,[]);
   }
   

   function addSpecialNeed(orderDetailId) {
    currenOrderDetailId =orderDetailId;
    // Target the element by its ID
    const specialNeedsElement = document.getElementById(`special_${orderDetailId}`);

    // Ensure the element exists and handle null/undefined
    if (specialNeedsElement) {
        // Extract and split the current special needs into an array
        const specialNeedsText = specialNeedsElement.textContent.split(":")[1] || "None";
        selectedSpecialNeeds = specialNeedsText.trim() === "None" ? [] : specialNeedsText.split(", ").map(need => need.trim());

        // Call the modal update function
        updateSelectedSpecialNeedsInModal(orderDetailId, selectedSpecialNeeds);

        // Display the modal
        document.getElementById("special-specialNeedsModal").style.display = 'block';
    } else {
        console.error(`Element with ID special_${orderDetailId} not found.`);
    }
}



function updateSelectedSpecialNeedsInModal(specialNeeds) {
    const selectedDiv = document.getElementById('selected-specialNeeds');
    
    // Ensure no empty values in the array
    const validSpecialNeeds = selectedSpecialNeeds.filter(need => need && need.trim() !== '');

    if (validSpecialNeeds.length > 0) {
        selectedDiv.innerText = `Selected Special Needs: ${validSpecialNeeds.join(', ')}`;
    } else {
        selectedDiv.innerText = 'Selected Special Needs: None';
    }
}


  
function updateSelectedSpecialNeeds(orderDetailId, specialNeeds) {
    // Target the <small> element using the id
    const specialNeedsElement = document.getElementById(`special_${orderDetailId}`);
    
    if (specialNeedsElement) {
        // Ensure specialNeeds is a valid array before processing
        if (!specialNeeds || !Array.isArray(specialNeeds)) {
            specialNeeds = []; // Default to an empty array if it's invalid
        }

        // Update the content of the <small> element
        specialNeedsElement.textContent = `Sp: ${specialNeeds.length > 0 
            ? specialNeeds.join(", ")  // Join the array if it has items
            : "None" // Display "None" if no special needs
        }`;

        console.log(`Updated special needs for OrderDetailId ${orderDetailId}:`, specialNeeds);
    } else {
        console.error(`Element with id "special_${orderDetailId}" not found.`);
    }
}



  function handleAddButtonClick(specialNeedName) {
      if (!selectedSpecialNeeds.includes(specialNeedName)) {
          selectedSpecialNeeds.push(specialNeedName);

          console.log(`Added: ${specialNeedName}`);
          console.log('Current list:', selectedSpecialNeeds);
      } else {
          console.log(`${specialNeedName} is already in the list.`);
      }
      updateSelectedSpecialNeeds(currenOrderDetailId, selectedSpecialNeeds);
      updateSelectedSpecialNeedsInModal( selectedSpecialNeeds);
  }

  document.getElementById('remove-all-btn').onclick = () => {
      selectedSpecialNeeds.length = 0; // Clear the array
      updateSelectedSpecialNeeds(); // Update the UI
      console.log('All selected special needs have been removed.');
  };




  document.getElementById('save-btn').onclick = () => {
     
     
  };

  const modal = document.getElementById("special-specialNeedsModal");
//  const openModalBtn = document.getElementById("special-openModal");
  const closeModalBtn = document.getElementsByClassName("special-close")[0];

  //openModalBtn.onclick = () => modal.style.display = "block";
  closeModalBtn.onclick = () => modal.style.display = "none";
  window.onclick = (event) => {
      if (event.target === modal) modal.style.display = "none";
  };

  // Load categories and special needs
  async function loadModalData() {
      const categories = await fetchData('api/category');
      const specialNeeds = await fetchData('api/special-need');

      const categoriesDiv = document.getElementById('special-categories');
      const specialNeedsDiv = document.getElementById('special-specialNeeds');

      categoriesDiv.innerHTML = ''; // Clear previous categories
      specialNeedsDiv.innerHTML = ''; // Clear previous special needs

      // Display all special needs in card view by default
      specialNeeds.forEach(item => {
          const card = document.createElement('div');
          card.className = 'special-card';
          card.innerHTML = `
              <div>${item.name}</div>
              <button>Add</button>
          `;
          const addButton = card.querySelector('button');
          addButton.onclick = () => handleAddButtonClick(item.name);

          specialNeedsDiv.appendChild(card);
      });

      // Add category buttons in a row
      categories.forEach(category => {
          const button = document.createElement('button');
          button.className = 'special-category-button';
          button.innerText = category.name;
          button.onclick = () => {
              // Filter and display special needs for the selected category
              const filteredSpecialNeeds = specialNeeds.filter(item => item.categoryId._id === category._id);
              specialNeedsDiv.innerHTML = ''; // Clear previous special needs

              if (filteredSpecialNeeds.length > 0) {
                  filteredSpecialNeeds.forEach(item => {
                      const card = document.createElement('div');
                      card.className = 'special-card';
                      card.innerHTML = `
                          <div>${item.name}</div>
                          <button>Add</button>
                      `;
                      specialNeedsDiv.appendChild(card);
                  });
              } else {
                  const noResults = document.createElement('div');
                  noResults.innerText = 'No special needs found for this category.';
                  specialNeedsDiv.appendChild(noResults);
              }
          };
          categoriesDiv.appendChild(button);
      });
  }










  window.updateSelectedTable = function(tableNumber) {

  document.getElementById('tableModal').style.display = 'none';

 
    const tableSpan = document.getElementById(`table_${currentOrderId}`);
    if (tableSpan) {
      // Update the span's content
      tableSpan.textContent = `Table No: ${tableNumber}`;
    } 

 updateOrderTable(tableNumber)
 };

 async function updateOrderTable( tableNo) {
  try {
    const res = await fetch(`/api/cafeorder/updateOrderTable?orderId=${currentOrderId}&tableNo=${tableNo}`, {
      method: 'POST', // You can switch to POST if necessary
    });

    if (!res.ok) {
      throw new Error(`Error: ${res.status} - ${res.statusText}`);
    }

    const data = await res.json();
    console.log('Table number updated successfully:', data);
  } catch (error) {
    console.error('Failed to update table number:', error);
  }
}




  async function fetchTables() {
  try {
    const res = await fetch('/api/table');
    const tables = await res.json();
    const calendar = document.getElementById('calendar');

    tables.forEach(table => {
      const tableDiv = document.createElement('div');
      tableDiv.className = 'table-item';
      tableDiv.innerHTML = `
        <div> No: ${table.No}</div>
        <button onclick="updateSelectedTable(${table.No})">Select</button>
      `;
      calendar.appendChild(tableDiv);
    });
  } catch (error) {
    console.error('Error fetching tables:', error);
  }
}




// Close Modal
document.getElementById('closeTableModal').addEventListener('click', () => {
  document.getElementById('tableModal').style.display = 'none'
  
  
  ;
});



fetchTables();


  loadModalData();

  // Kitchen Printer Class
  class KitchenPrinter {
    constructor() {
      // Get printer IP from localStorage, default to 192.168.20.100
      this.printerIP = localStorage.getItem('kitchenPrinterIP') || '192.168.20.100';
    }

    async printOrderChanges(orderData) {
      try {
        const escposData = this.generateESC_POS_Changes(orderData);

        // Get printer bridge protocol, IP and port from localStorage and construct full URL
        const bridgeProtocol = localStorage.getItem('kitchenPrinterBridgeProtocol') || (window.location.protocol === 'https:' ? 'https' : 'http');
        const bridgeIP = localStorage.getItem('kitchenPrinterBridgeIP') || 'localhost';
        const bridgePort = localStorage.getItem('kitchenPrinterBridgePort') || '3000';
        const bridgeUrl = `${bridgeProtocol}://${bridgeIP}:${bridgePort}/print`;

        const response = await fetch(bridgeUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            printerIP: this.printerIP,
            port: 9100,
            data: Array.from(escposData) // Convert to array for JSON
          })
        });

        const result = await response.json();

        if (result.success) {
          console.log('✓ Print job sent successfully!');
        } else {
          throw new Error(result.error);
        }

      } catch (error) {
        console.error('Print failed:', error);
        // Silent failure - don't interrupt user experience
      }
    }

    async savePrintDataToDatabase(orderData) {
      try {
        // Use window scope to access fullOrders
        const orders = window.fullOrders || [];
        
        // Extract orderId from the order data or find it from fullOrders
        const order = orders.find(o => 
          o.orderNo === orderData.id || 
          o._id === orderData.orderId
        );

        if (!order) {
          console.warn('Order not found for saving print data');
          return;
        }

        const response = await fetch('/api/printed-data/save-print-data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            orderId: order._id,
            orderNo: orderData.id || order.orderNo,
            tableNo: orderData.table || order.tableNo,
            waiterName: orderData.waiter || 'N/A',
            changes: orderData.changes || {},
            printType: 'order_update'
          })
        });

        const result = await response.json();
        
        if (result.success) {
          console.log('✓ Print data saved to database');
          // Note: Socket broadcast is now handled by the server after successful save
        } else {
          console.warn('Failed to save print data:', result.message);
        }
      } catch (error) {
        console.error('Error saving print data to database:', error);
        // Silent failure - don't interrupt user experience
      }
    }

    generateESC_POS_Changes(order) {
      const encoder = new TextEncoder();
      const commands = [
        '\x1B\x40',           // Initialize printer
        '\x1B\x61\x01',       // Center align
        '\x1B\x21\x10',       // Double height
        'ORDER UPDATE\n',      // Title
        '\x1B\x21\x00',       // Normal text
        '\x1B\x61\x00',       // Left align
        `${'='.repeat(32)}\n`,
      ];

      // Helper function to create two-column layout
      const twoColumn = (left, right, maxWidth = 32) => {
        const leftText = left || '';
        const rightText = right || '';
        const padding = maxWidth - leftText.length - rightText.length;
        return padding > 0 
          ? leftText + ' '.repeat(padding) + rightText + '\n'
          : leftText + ' ' + rightText + '\n';
      };

      // Order Number (left) and Table (right)
      const orderText = `Order: #${order.id || order.orderNo || 'N/A'}`;
      const tableText = order.table ? `Table: ${order.table}` : '';
      commands.push(twoColumn(orderText, tableText));

      // Waiter Name (left) and Time (right)
      const waiterText = order.waiter ? `Waiter: ${order.waiter}` : '';
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const timeText = `Time: ${hours}:${minutes}`;
      commands.push(twoColumn(waiterText, timeText));

      commands.push(`${'='.repeat(32)}\n\n`);

      const changes = order.changes || {};

      // ADDED ITEMS SECTION
      if (changes.added && changes.added.length > 0) {
        commands.push('\x1B\x61\x01'); // Center align
        commands.push('\x1B\x21\x08'); // Bold
        commands.push('ADDED ITEMS\n');
        commands.push('\x1B\x21\x00'); // Normal text
        commands.push('\x1B\x61\x00'); // Left align
        commands.push(`${'-'.repeat(32)}\n`);
        
        changes.added.forEach(item => {
          commands.push(`${item.quantity}x ${item.itemName}\n`);
          if (item.specialNeeds && item.specialNeeds.length > 0) {
            commands.push(`  Special: ${item.specialNeeds.join(', ')}\n`);
          }
          commands.push('\n');
        });
      }

      // QUANTITY CHANGED ITEMS SECTION
      if (changes.quantityChanged && changes.quantityChanged.length > 0) {
        if (changes.added && changes.added.length > 0) {
          commands.push('\n');
        }
        commands.push('\x1B\x61\x01'); // Center align
        commands.push('\x1B\x21\x08'); // Bold
        commands.push('QUANTITY CHANGED\n');
        commands.push('\x1B\x21\x00'); // Normal text
        commands.push('\x1B\x61\x00'); // Left align
        commands.push(`${'-'.repeat(32)}\n`);
        
        changes.quantityChanged.forEach(item => {
          const change = item.currentQuantity > item.previousQuantity ? '+' : '';
          const qtyChange = item.currentQuantity - item.previousQuantity;
          commands.push(`${item.itemName}\n`);
          commands.push(`  ${item.previousQuantity} -> ${item.currentQuantity} (${change}${qtyChange})\n`);
          if (item.specialNeeds && item.specialNeeds.length > 0) {
            commands.push(`  Special: ${item.specialNeeds.join(', ')}\n`);
          }
          commands.push('\n');
        });
      }

      // REMOVED ITEMS SECTION
      if (changes.removed && changes.removed.length > 0) {
        if ((changes.added && changes.added.length > 0) || (changes.quantityChanged && changes.quantityChanged.length > 0)) {
          commands.push('\n');
        }
        commands.push('\x1B\x61\x01'); // Center align
        commands.push('\x1B\x21\x08'); // Bold
        commands.push('REMOVED ITEMS\n');
        commands.push('\x1B\x21\x00'); // Normal text
        commands.push('\x1B\x61\x00'); // Left align
        commands.push(`${'-'.repeat(32)}\n`);
        
        changes.removed.forEach(item => {
          commands.push(`${item.quantity}x ${item.itemName}\n`);
          if (item.specialNeeds && item.specialNeeds.length > 0) {
            commands.push(`  Special: ${item.specialNeeds.join(', ')}\n`);
          }
          commands.push('\n');
        });
      }

      commands.push(
        `${'='.repeat(32)}\n\n\n\n`,
        '\x1B\x69' // Partial cut
      );

      return encoder.encode(commands.join(''));
    }
  }

  // Create global printer instance
  window.kitchenPrinter = new KitchenPrinter();

  // Toast Notification Function
  function showToast(message, type = 'success', duration = 3000) {
    const toastContainer = document.getElementById('toastContainer');
    if (!toastContainer) {
      // Create container if it doesn't exist
      const container = document.createElement('div');
      container.id = 'toastContainer';
      container.className = 'toast-container';
      document.body.appendChild(container);
    }

    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    
    const messageSpan = document.createElement('span');
    messageSpan.textContent = message;
    
    const closeButton = document.createElement('button');
    closeButton.className = 'toast-close';
    closeButton.innerHTML = '&times;';
    closeButton.onclick = () => removeToast(toast);
    
    toast.appendChild(messageSpan);
    toast.appendChild(closeButton);
    
    toastContainer.appendChild(toast);
    
    // Auto remove after duration
    if (duration > 0) {
      setTimeout(() => {
        removeToast(toast);
      }, duration);
    }
    
    return toast;
  }

  function removeToast(toast) {
    toast.classList.add('hiding');
    setTimeout(() => {
      if (toast.parentNode) {
        toast.parentNode.removeChild(toast);
      }
    }, 300); // Match animation duration
  }

  // Make toast function globally available
  window.showToast = showToast;

  // Initialize Socket.IO connection (uses same origin as current page)
  window.socket = io({
    transports: ['websocket', 'polling']
  });

  window.socket.on('connect', () => {
    console.log('✓ Socket.IO connected');
  });

  window.socket.on('disconnect', () => {
    console.log('Socket.IO disconnected');
  });

  // Listen for print data broadcasts from other clients
  // window.socket.on('new-print-data', (printData) => {
  //   console.log('📢 New print data received from another client:', printData);
  //   // You can add a notification or UI update here
  //   // For example: show a toast notification, update a list, etc.
  //   if (printData.printType === 'order_update') {
  //     console.log(`Order #${printData.orderNo} updated by ${printData.waiterName}`);
  //   } else if (printData.printType === 'new_order') {
  //     console.log(`New order #${printData.orderNo} created by ${printData.waiterName}`);
  //   }
  // });

  window.socket.on('connect_error', (error) => {
    console.warn('Socket.IO connection error:', error);
  });

  // Load and display company name
  (async function() {
    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');
    
    if (companyId && branchId) {
      try {
        const response = await fetch(`/api/settings?companyId=${companyId}&branchId=${branchId}`);
        if (response.ok) {
          const data = await response.json();
          if (data.companyName) {
            localStorage.setItem('companyName', data.companyName);
            const titleElement = document.getElementById('companyTitle');
            if (titleElement) {
              titleElement.textContent = data.companyName + ' Cafe Order Management System';
            }
          }
        }
      } catch (error) {
        console.error('Error loading company name:', error);
      }
    }
    
    // Fallback to localStorage or default
    const companyName = localStorage.getItem('companyName') || 'Zad';
    const titleElement = document.getElementById('companyTitle');
    if (titleElement && !titleElement.textContent.includes(companyName)) {
      titleElement.textContent = companyName + ' Cafe Order Management System';
    }
  })();
    
  </script>
</body>
</html>