<!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;
      background-color: #f4f4f9;
      margin: 0;
      padding: 0;
      color: #333;
    }

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

    #orders-container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); /* Flexible grid */
      gap: 20px;
      padding: 20px;
      max-width: 1200px;
      margin: 0 auto;
    }

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

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

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

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

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

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

    .serve-btn {
      background: #0078d7;
      color: white;
      border: none;
      padding: 8px 12px;
      font-size: 14px;
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    .serve-btn:hover {
      background: #0056a8;
    }

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

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

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

    .loading-text {
      text-align: center;
      font-size: 16px;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <h1>Attachment Orders  </h1>
  <div id="loading-spinner" class="spinner"></div>
  <p id="loading-text" class="loading-text"></p>
  <div id="orders-container">
    <!-- Orders will be dynamically loaded here -->
  </div>

  <script>
    const loadingSpinner = document.getElementById('loading-spinner');
    const loadingText = document.getElementById('loading-text');

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

        const response = await fetch(`/api/cafeorder/get-attachment`);
        const data = await response.json();

        if (data.success) {
          renderOrders(data.data);
        } else {
          console.error('Failed to fetch orders:', data.error);
        }
      } catch (error) {
        console.error('Error fetching orders:', error);
      } finally {
        // Hide the loading spinner
        loadingSpinner.style.display = 'none';
        loadingText.innerText = '';
      }
    }

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


      console.log(orders); //
      orders.forEach((order) => {
        const filteredItems = order.items.filter(
          (item) => item.quantity > (item.attachmentServedQty || 0) // Exclude fully served items
        );

        if (filteredItems.length === 0) {
          return; // Skip orders with no unserved items
        }

        const elapsedTime = calculateElapsedTime(order.createdAt);

        const itemsList = filteredItems
          .map((item) => {
            const remaining = item.quantity - (item.attachmentServedQty || 0);

            
const specialNeeds = item.specialNeeds;
  // 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
            return `
              <li>
                <strong>${item.itemName}</strong><br>
                Quantity: ${item.quantity}<br>
                Remaining: ${remaining}
               - ${specialNeedsDisplay}
              </li>
            `;
          })
          .join('');

        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(
          filteredItems.map((item) => ({
            itemId: item.itemId,
            remaining: item.quantity - (item.attachmentServedQty || 0),
          }))
        )})' 
           }>
            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 = Math.abs(now - createdTime); // Difference in milliseconds

      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-attachment', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ orderId, items }),
        });

        const data = await response.json();

        if (data.success) {
      //    alert('Order served successfully!');
          fetchOrders(); // Refresh the orders list
        } else {
          alert('Failed to serve order: ' + data.message);
        }
      } catch (error) {
        console.error('Error serving order:', error);
        alert('Error serving the order.');
      } finally {
        loadingSpinner.style.display = 'none';
        loadingText.innerText = '';
      }
    }

    // Fetch orders when the page loads and refresh every 30 seconds
    document.addEventListener('DOMContentLoaded', () => {
      fetchOrders();
      setInterval(fetchOrders, 30000);
    });
  </script>
</body>
</html>
