<!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); }
    }



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

  <!-- Audio Status Display -->
  <div style="text-align: center; margin: 10px 0; padding: 10px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid #dee2e6;">
    <div style="display: flex; align-items: center; justify-content: center; gap: 10px;">
      <span style="font-weight: bold;">🔔 Kitchen Alerts:</span>
      <span id="audioStatus" style="font-size: 14px; color: #666;">Loading...</span>
      <button id="enableAudioBtn" style="background-color: #04b12a; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer;">
        Enable Audio
      </button>
    </div>
  </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 enableAudioBtn = document.getElementById('enableAudioBtn');
    const audioStatus = document.getElementById('audioStatus');

    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');
    const userId = sessionStorage.getItem('userId');
    let userKitchenId = sessionStorage.getItem('kitchenId');
    let allOrder = null;
    let previousOrderCount = 0;
    let audioEnabled = false;
   
    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

      // Count orders for this kitchen
      let currentOrderCount = 0;
      orders.forEach((order) => {
        const filteredItems = order.items.filter(
          (item) => item.quantity > (item.kitchenServedQty || 0)
        );
        const kitchenItems = filteredItems.filter(
          (item) => item.kitchenId && item.kitchenId.toString() === userKitchenId
        );
        if (kitchenItems.length > 0) {
          currentOrderCount++;
        }
      });

      // Play alert sound if there are new orders
      if (currentOrderCount > 0 && currentOrderCount > previousOrderCount) {
        playOrderAlert();
      }
      previousOrderCount = currentOrderCount;

      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`;
    }

    function playOrderAlert() {
      if (!audioEnabled) return;
      
      // Get the selected sound from localStorage, default to 'beep' if not set
      const selectedSound = localStorage.getItem('kitchenAlertSound') || 'beep';
      playSound(selectedSound);
    }

    function playSound(soundType) {
      try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const gainNode = audioContext.createGain();
        gainNode.connect(audioContext.destination);
        
        switch(soundType) {
          case 'beep':
            playBeep(audioContext, gainNode);
            break;
          case 'chime':
            playChime(audioContext, gainNode);
            break;
          case 'ding':
            playDing(audioContext, gainNode);
            break;
          case 'notification':
            playNotification(audioContext, gainNode);
            break;
          case 'bell':
            playBell(audioContext, gainNode);
            break;
          case 'alert':
            playAlert(audioContext, gainNode);
            break;
          default:
            playBeep(audioContext, gainNode);
        }
        
        console.log(`${soundType} sound played successfully`);
      } catch (error) {
        console.log('Error playing sound:', error);
      }
    }

    function playBeep(audioContext, gainNode) {
      const oscillator = audioContext.createOscillator();
      oscillator.connect(gainNode);
      
      oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
      oscillator.type = 'sine';
      
      gainNode.gain.setValueAtTime(0, audioContext.currentTime);
      gainNode.gain.linearRampToValueAtTime(0.8, audioContext.currentTime + 0.2);
      gainNode.gain.linearRampToValueAtTime(0.8, audioContext.currentTime + 1.0);
      gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.5);
      
      oscillator.start(audioContext.currentTime);
      oscillator.stop(audioContext.currentTime + 1.5);
    }

    function playChime(audioContext, gainNode) {
      // Play two tones in sequence
      const osc1 = audioContext.createOscillator();
      const osc2 = audioContext.createOscillator();
      osc1.connect(gainNode);
      osc2.connect(gainNode);
      
      osc1.frequency.setValueAtTime(523, audioContext.currentTime); // C5
      osc2.frequency.setValueAtTime(659, audioContext.currentTime + 0.3); // E5
      osc1.type = 'sine';
      osc2.type = 'sine';
      
      gainNode.gain.setValueAtTime(0, audioContext.currentTime);
      gainNode.gain.linearRampToValueAtTime(0.6, audioContext.currentTime + 0.1);
      gainNode.gain.linearRampToValueAtTime(0.6, audioContext.currentTime + 0.8);
      gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.2);
      
      osc1.start(audioContext.currentTime);
      osc1.stop(audioContext.currentTime + 0.6);
      osc2.start(audioContext.currentTime + 0.3);
      osc2.stop(audioContext.currentTime + 0.9);
    }

    function playDing(audioContext, gainNode) {
      const oscillator = audioContext.createOscillator();
      oscillator.connect(gainNode);
      
      oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);
      oscillator.type = 'triangle';
      
      gainNode.gain.setValueAtTime(0, audioContext.currentTime);
      gainNode.gain.linearRampToValueAtTime(0.7, audioContext.currentTime + 0.1);
      gainNode.gain.linearRampToValueAtTime(0.7, audioContext.currentTime + 0.4);
      gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 0.8);
      
      oscillator.start(audioContext.currentTime);
      oscillator.stop(audioContext.currentTime + 0.8);
    }

    function playNotification(audioContext, gainNode) {
      const oscillator = audioContext.createOscillator();
      oscillator.connect(gainNode);
      
      oscillator.frequency.setValueAtTime(400, audioContext.currentTime);
      oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.2);
      oscillator.type = 'square';
      
      gainNode.gain.setValueAtTime(0, audioContext.currentTime);
      gainNode.gain.linearRampToValueAtTime(0.5, audioContext.currentTime + 0.1);
      gainNode.gain.linearRampToValueAtTime(0.5, audioContext.currentTime + 0.6);
      gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.0);
      
      oscillator.start(audioContext.currentTime);
      oscillator.stop(audioContext.currentTime + 1.0);
    }

    function playBell(audioContext, gainNode) {
      const oscillator = audioContext.createOscillator();
      oscillator.connect(gainNode);
      
      oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
      oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.1);
      oscillator.frequency.setValueAtTime(800, audioContext.currentTime + 0.2);
      oscillator.type = 'sine';
      
      gainNode.gain.setValueAtTime(0, audioContext.currentTime);
      gainNode.gain.linearRampToValueAtTime(0.6, audioContext.currentTime + 0.1);
      gainNode.gain.linearRampToValueAtTime(0.6, audioContext.currentTime + 0.8);
      gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.2);
      
      oscillator.start(audioContext.currentTime);
      oscillator.stop(audioContext.currentTime + 1.2);
    }

    function playAlert(audioContext, gainNode) {
      const oscillator = audioContext.createOscillator();
      oscillator.connect(gainNode);
      
      oscillator.frequency.setValueAtTime(300, audioContext.currentTime);
      oscillator.frequency.setValueAtTime(800, audioContext.currentTime + 0.2);
      oscillator.frequency.setValueAtTime(300, audioContext.currentTime + 0.4);
      oscillator.type = 'sawtooth';
      
      gainNode.gain.setValueAtTime(0, audioContext.currentTime);
      gainNode.gain.linearRampToValueAtTime(0.8, audioContext.currentTime + 0.1);
      gainNode.gain.linearRampToValueAtTime(0.8, audioContext.currentTime + 1.0);
      gainNode.gain.linearRampToValueAtTime(0, audioContext.currentTime + 1.5);
      
      oscillator.start(audioContext.currentTime);
      oscillator.stop(audioContext.currentTime + 1.5);
    }

    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 = '';
      }
    }



  


    function enableAudio() {
      try {
        // Create audio context to enable audio permissions
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        
        // Resume audio context (required for some browsers)
        if (audioContext.state === 'suspended') {
          audioContext.resume();
        }
        
        // Test with a very short beep
        const oscillator = audioContext.createOscillator();
        const gainNode = audioContext.createGain();
        
        oscillator.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);
        oscillator.type = 'sine';
        gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
        
        oscillator.start(audioContext.currentTime);
        oscillator.stop(audioContext.currentTime + 0.1);
        
        audioEnabled = true;
        const selectedSound = localStorage.getItem('kitchenAlertSound') || 'beep';
        audioStatus.textContent = `✅ Alerts enabled (${selectedSound})`;
        audioStatus.style.color = '#04b12a';
        enableAudioBtn.style.display = 'none';
        console.log('Audio alerts enabled successfully');
        
      } catch (error) {
        console.log('Failed to enable audio:', error);
        audioStatus.textContent = '❌ Audio blocked by browser';
        audioStatus.style.color = '#e74c3c';
      }
    }

    // Add click event listener for enable audio button
    enableAudioBtn.addEventListener('click', enableAudio);

    // Refresh orders every 30 seconds
    document.addEventListener('DOMContentLoaded', () => {
      // Initialize audio status display
      const selectedSound = localStorage.getItem('kitchenAlertSound') || 'beep';
      audioStatus.textContent = `Sound: ${selectedSound} (click Enable Audio to activate)`;
      
      // 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>