<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Orders</title>
  <style>
    /* Base Styles */
    body {
      font-family: Arial, sans-serif;
      line-height: 1.6;
      background-color: #f4f4f9;
      margin: 0;
      padding: 0;
      color: #333;
    }

    h1 {
      text-align: center;
      padding: 20px;
      background-color: #04b12a;
      color: white;
      margin: 0;
    }

    .orders-container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
      padding: 20px;
      max-width: 1200px;
      margin: 20px auto;
    }

    .order {
      background: #fff;
      border: 1px solid #ddd;
      border-radius: 8px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      padding: 15px;
      transition: transform 0.2s ease, box-shadow 0.2s ease;
    }

    .order:hover {
      transform: translateY(-5px);
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
    }

    .order h2 {
      font-size: 18px;
      margin: 0 0 10px;
      color: #3498db;
    }

    .order p {
      font-size: 14px;
      margin: 5px 0;
      color: #555;
    }

    .order-details {
      list-style: none;
      padding: 0;
      margin: 15px 0;
    }

    .order-details li {
      margin-bottom: 8px;
    }

    .warning {
      color: #e74c3c;
      font-weight: bold;
    }

    .serve-btn {
      background-color: #11a809;
      color: white;
      border: none;
      padding: 10px;
      font-size: 14px;
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s ease;
      width: 100%;
    }

    .serve-btn:hover:not(:disabled) {
      background-color: #2980b9;
    }

    .serve-btn:disabled {
      background-color: gray;
      cursor: not-allowed;
    }

    .elapsed-time {
      font-size: 12px;
      color: #888;
      text-align: right;
      margin-top: 10px;
    }

    .spinner {
      display: none;
      border: 4px solid #f3f3f3;
      border-top: 4px solid #3498db;
      border-radius: 50%;
      width: 40px;
      height: 40px;
      animation: spin 1s linear infinite;
      margin: 20px auto;
    }

    .loading-text {
      text-align: center;
      font-size: 16px;
      font-weight: bold;
      color: #555;
    }
    .item-quantity{
      font-size: 11px;
    }
    .special-needs {
      font-style: italic;
      color: #666;
      font-size: 12px;
      display: block;
      margin-top: 3px;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .kitchen-row {
  display: flex; /* Align buttons in a row */
  gap: 1rem; /* Add space between buttons */
  padding: 1rem; /* Add padding around the container */
  overflow-x: auto; /* Allow scrolling if buttons overflow */
}

.kitchen-btn {
  padding: 0.5rem 1rem; /* Button padding */
  border: none; /* Remove border */
  border-radius: 8px; /* Rounded edges for a modern look */
  font-size: 1rem; /* Readable font size */
  font-weight: bold; /* Emphasized text */
  color: #ffffff; /* White text for contrast */
  background-color: #0078d4; /* Professional blue color */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* Subtle shadow for depth */
  cursor: pointer; /* Indicate interactivity */
  transition: all 0.3s ease; /* Smooth hover and focus effects */
}

.kitchen-btn:hover {
  background-color: #005a9e; /* Darker blue on hover */
  transform: scale(1.05); /* Slight zoom for interaction */
}

.kitchen-btn:active {
  background-color: #003b6f; /* Dark blue on click */
  transform: scale(0.95); /* Press effect */
}


  </style>
</head>
<body>
  <h1 id="companyTitle">Kitchen Order System</h1>

  <div id="kitchenContainer" class="kitchen-row"></div>

  <div id="loading-spinner" class="spinner"></div>
  <p id="loading-text" class="loading-text"></p>
  <div id="orders-container" class="orders-container">
    <!-- Orders will be dynamically loaded here -->
  </div>
  <script>
    const loadingSpinner = document.getElementById('loading-spinner');
    const loadingText = document.getElementById('loading-text');

    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');
    const userId = sessionStorage.getItem('userId');
    let  userKitchenId = sessionStorage.getItem('kitchenId');
    let allOrder=null;
   
    if (!companyId || !branchId || !userId || !userKitchenId) {
      alert('Company ID, Branch ID, User ID, and Kitchen ID are required. Please log in again.');
      window.location.href = '/'; // Redirect to login page
    }

    async function fetchOrders() {
      try {
        // Show spinner and loading message
        loadingSpinner.style.display = 'block';
        loadingText.innerText = 'Loading orders...';

        const response = await fetch(`/api/cafeorder?companyId=${companyId}`);
        const data = await response.json();

        if (data.success) {
          allOrder=data.data;
          renderOrders(data.data);
        } else {
          console.error('Failed to fetch orders:', data.error);
          alert('Failed to load orders. Please try again.');
        }
      } catch (error) {
        console.error('Error fetching orders:', error);
        alert('Error loading orders. Please check your connection.');
      } finally {
        // Hide spinner and loading message
        loadingSpinner.style.display = 'none';
        loadingText.innerText = '';
      }
    }

    function renderOrders(orders) {
      const container = document.getElementById('orders-container');
      container.innerHTML = ''; // Clear previous orders

      if (orders.length === 0) {
        container.innerHTML = '<p style="grid-column: 1 / -1; text-align: center;">No orders found</p>';
        return;
      }

      orders.forEach((order) => {
        // First filter items where quantity > kitchenServedQty
        const filteredItems = order.items.filter(
          (item) => item.quantity > (item.kitchenServedQty || 0)
        );

        // Then filter items where userKitchenId matches item.kitchenId
        const kitchenItems = filteredItems.filter(
          (item) => item.kitchenId && item.kitchenId.toString() === userKitchenId
        );

        // Skip orders that have no items for this kitchen
        if (kitchenItems.length === 0) return;

        const elapsedTime = calculateElapsedTime(order.createdAt);

        const itemsList = kitchenItems
          .map((item) => {
            const remaining = item.quantity - (item.kitchenServedQty || 0);
            const waitingForAttachment = item.attachmentReq &&
              remaining > ((item.attachmentServedQty - item.kitchenServedQty) || 0);
            
            const specialNeeds = item.specialNeeds;
            const specialNeedsDisplay = Array.isArray(specialNeeds) && specialNeeds.length > 0 
              ? specialNeeds.join(", ")
              : "";

            return `
              <li> 
                <strong>${item.itemName}</strong> <span class="item-quantity">Qty: ${item.quantity}</span> - Remain: ${remaining}
                ${waitingForAttachment ? '<span class="warning"> (waiting)</span>' : ''}
                ${specialNeedsDisplay ? `<span class="special-needs">Special: ${specialNeedsDisplay}</span>` : ''}
              </li>
            `;
          })
          .join('');

        const disabledButton = kitchenItems.some(
          (item) => item.attachmentReq &&
            item.quantity - (item.kitchenServedQty || 0) >
            ((item.attachmentServedQty - item.kitchenServedQty) || 0)
        );

        const orderDiv = document.createElement('div');
        orderDiv.className = 'order';
        orderDiv.innerHTML = `
          <h2>Order #${order.orderNo}</h2>
            <small>Table: ${order.tableNo}</small><br>
             ${order.transferFrom ? `<small>From: ${order.transferFrom}</small><br>` : ""}
                            <small>Waiter: ${order.userName}</small><br>
          <p><strong>Created At:</strong> ${new Date(order.createdAt).toLocaleString()}</p>
          <ul class="order-details">${itemsList}</ul>
          <button class="serve-btn"
            onclick='serveOrder("${order._id}", ${JSON.stringify(
              kitchenItems.map((item) => ({
                itemId: item.itemId,
                remaining: item.quantity - (item.kitchenServedQty || 0),
              }))
            )})' 
            ${disabledButton ? 'disabled' : ''}>
            Serve
          </button>
          <div class="elapsed-time">Elapsed: ${elapsedTime}</div>
        `;

        container.appendChild(orderDiv);
      });
    }

    function calculateElapsedTime(createdAt) {
      const now = new Date();
      const createdTime = new Date(createdAt);
      const diff = now - createdTime;

      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      return `${hours}h ${minutes}m ago`;
    }

    async function serveOrder(orderId, items) {
      try {
        loadingSpinner.style.display = 'block';
        loadingText.innerText = 'Submitting order...';

        const response = await fetch('/api/cafeorder/serve-order', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ orderId, items }),
        });

        const data = await response.json();

        if (data.success) {
          fetchOrders(); // Refresh orders
        } else {
          alert('Failed to serve order: ' + (data.message || 'Unknown error'));
        }
      } catch (error) {
        console.error('Error serving order:', error);
        alert('Error serving the order. Please try again.');
      } finally {
        loadingSpinner.style.display = 'none';
        loadingText.innerText = '';
      }
    }



  

    async function fetchKitchen() {
  const response = await fetch('/api/kitchen');
  const data = await response.json();
 
 
    const kitchenContainer = document.getElementById('kitchenContainer'); // Target container for buttons
    kitchenContainer.innerHTML = ''; // Clear existing content

    // Create a row of buttons for the kitchens
    data.forEach((kitchen) => {
      console.log(kitchen); //
      const button = document.createElement('button'); // Create button element
      button.textContent = kitchen.name; // Set button text to the kitchen name
      button.setAttribute('data-id', kitchen._id); // Add a data attribute for the kitchen ID
      button.classList.add('kitchen-btn'); // Add a class for consistent styling

      // Add event listener for button click
      button.addEventListener('click', () => {
        userKitchenId=kitchen._id;
        renderOrders(allOrder); // filter based on new kitchen id
      //  console.log(`Kitchen ID: ${kitchen._id}`); // Log the kitchen ID
      //  alert(`Kitchen ID: ${kitchen._id}`); // Display ID in an alert box (optional)
      });

      kitchenContainer.appendChild(button); // Append the button to the container
    });
  
}

fetchKitchen();

    // Refresh orders every 30 seconds
    document.addEventListener('DOMContentLoaded', () => {
      // 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 + ' Kitchen Order 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 + ' Kitchen Order System';
        }
      })();
      
      fetchOrders();
      setInterval(fetchOrders, 30000);
    });
  </script>
</body>
</html>