<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Order Summary with Graph</title>
  <style>
    /* Existing Styles */
    body {
      font-family: Arial, sans-serif;
      background-color: #f9f9f9;
      margin: 0;
      padding: 0;
    }
    .container {
      max-width: 800px;
      margin: 20px auto;
      background-color: #fff;
      padding: 20px;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
      border-radius: 10px;
    }
    h1 {
      text-align: center;
      color: #333;
    }
    .summary {
      margin-top: 20px;
      font-size: 18px;
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #e0e0e0;
    }
    .summary div {
      margin-bottom: 10px;
    }
    .filter-container {
      display: flex;
      gap: 0.75rem;
      margin-bottom: 1.5rem;
      padding: 1rem;
      background: linear-gradient(135deg, #1e88e5, #0d47a1);
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      overflow-x: auto;
      white-space: nowrap;
      scrollbar-width: none;
    }
    .filter-container::-webkit-scrollbar {
      display: none;
    }
    .filter-btn {
      flex: 0 0 120px;
      padding: 0.6rem 0;
      border: 2px solid rgba(255, 255, 255, 0.3);
      border-radius: 24px;
      background: rgba(255, 255, 255, 0.1);
      color: white;
      cursor: pointer;
      transition: all 0.3s ease;
      font-weight: 500;
      text-align: center;
      backdrop-filter: blur(5px);
    }
    .filter-btn:hover {
      background: rgba(255, 255, 255, 0.2);
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    .filter-btn.active {
      background: #ffffff;
      color: #0d47a1;
      border-color: white;
      font-weight: 600;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 20px 0;
    }
    table, th, td {
      border: 1px solid #ddd;
    }
    th, td {
      padding: 10px;
      text-align: left;
    }
    th {
      background-color: #f4f4f9;
    }
    canvas {
      margin-top: 20px;
    }
    /* Item List Styles (from cashier) */
    .item-list {
      display: flex;
      flex-direction: column;
      gap: 1rem;
      max-width: 600px;
      margin: 0 auto;
      padding: 1rem;
      background: #f9f9f9;
      border-radius: 10px;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      font-family: 'Arial', sans-serif;
      color: #333;
    }
    .item {
      padding: 0.75rem 1rem;
      border-radius: 8px;
      border: 1px solid #ddd;
      font-weight: 500;
      transition: transform 0.2s ease, box-shadow 0.2s ease;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .item-content {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    .item-name {
      color: rgb(4, 59, 110);
      font-weight: bold;
      margin-right: 8px;
    }
    .item-quantity {
      font-size: 14px;
      color: gray;
      margin-left: 8px;
    }
    .item-served {
      font-size: 14px;
      color: gray;
      margin-left: 8px;
    }
    .item-serve-time {
      font-size: 12px;
      margin-left: auto;
      font-weight: 600;
      background-color: #efe7e7;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 2px;
      padding: 8px 12px;
      border-radius: 20px;
      min-width: 90px;
      justify-content: center;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      transition: all 0.3s ease;
      text-align: center;
      line-height: 1.2;
    }
    .item-serve-time.served {
      color: #ffffff;
      background: linear-gradient(135deg, #4CAF50, #45a049);
      border: 1px solid #4CAF50;
    }
    .item-serve-time.not-served {
      color: #9e9e9e;
      background: linear-gradient(135deg, #f5f5f5, #e0e0e0);
      border: 1px solid #bdbdbd;
    }
    .item-serve-time.served::before {
      content: "⚡";
      font-size: 14px;
    }
    .item-serve-time.not-served::before {
      content: "⏳";
      font-size: 14px;
    }
    .order-average-time {
      margin-top: 8px;
      padding: 6px 8px;
      background-color: #e3f2fd;
      border-radius: 4px;
      border-left: 3px solid #2196f3;
    }
    .order-average-time strong {
      color: #1976d2;
      font-size: 13px;
    }
    .item.equal {
      background-color: #4af972;
      border: 1px solid #c3e6cb;
    }
    .item.not-equal {
      background-color: #ffeeba;
      border: 1px solid #ffc107;
    }
    .item:hover {
      transform: translateY(-3px);
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
    }
    .order-number {
      color: #2A5C82;
      font-weight: 700;
      font-size: 1.1rem;
    }
    .order-meta {
      font-size: 0.9rem;
      color: #666;
      margin-top: 0.5rem;
    }
    .order-total {
      font-size: 1rem;
      font-weight: 600;
      color: #333;
      margin-top: 0.5rem;
    }
  </style>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <!-- Add Chart.js library -->
</head>
<body>
  <div class="container">
    <h1>Order Summary</h1>
    
    <!-- Filter buttons container -->
    <div class="filter-container" id="waiter-filters">
      <button class="filter-btn active" onclick="filterOrdersByWaiter('all')">All</button>
      <!-- Filter buttons will be added dynamically here -->
    </div>

    <!-- Summary at top -->
    <div class="summary">
      <div><strong>Total Quantity Ordered:</strong> <span id="total-ordered">0</span></div>
      <div><strong>Total Served Quantity:</strong> <span id="total-served">0</span></div>
      <div><strong>Total Remaining Quantity:</strong> <span id="total-remaining">0</span></div>
      <div><strong>Total Amount:</strong> $<span id="total-amount">0.00</span></div>
    </div>

    <canvas id="orderChart" width="400" height="200"></canvas>
    <div id="order-details" class="summary"></div>
    <table>
      <thead>
        <tr>
          <th>Order Details</th>
          <th>Items</th>
          <th>Total Amount</th>
          <th>Duration</th>
        </tr>
      </thead>
      <tbody id="order-table-body">
        <!-- Dynamic rows will be inserted here -->
      </tbody>
    </table>
 
  </div>
  <script>
    const companyId = sessionStorage.getItem('companyId');
    const branchId = sessionStorage.getItem('branchId');
    let allOrders = [];
    let currentFilter = 'all';
    let chartInstance = null;

    function getElapsedTime(createdAt) {
      const createdTime = new Date(createdAt);
      const currentTime = new Date();
      const elapsedMs = currentTime - createdTime;

      const seconds = Math.floor(elapsedMs / 1000) % 60;
      const minutes = Math.floor(elapsedMs / (1000 * 60)) % 60;
      const hours = Math.floor(elapsedMs / (1000 * 60 * 60)) % 24;
      const days = Math.floor(elapsedMs / (1000 * 60 * 60 * 24));

      if (days > 0) return `${days}d ${hours}h`;
      if (hours > 0) return `${hours}h ${minutes}m`;
      if (minutes > 0) return `${minutes}m ${seconds}s`;
      return `${seconds}s`;
    }

    function updateWaiterFilters(orders) {
      const filterContainer = document.getElementById('waiter-filters');
      const waiters = [...new Set(orders.map(order => order.userName).filter(Boolean))];
      
      filterContainer.innerHTML = '<button class="filter-btn active" onclick="filterOrdersByWaiter(\'all\')">All</button>';
      
      waiters.forEach(waiter => {
        const btn = document.createElement('button');
        btn.className = 'filter-btn';
        btn.textContent = waiter;
        btn.onclick = () => filterOrdersByWaiter(waiter);
        filterContainer.appendChild(btn);
      });
    }

    function filterOrdersByWaiter(waiterName) {
      currentFilter = waiterName;
      document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.classList.remove('active');
        if ((waiterName === 'all' && btn.textContent === 'All') || 
            (btn.textContent === waiterName)) {
          btn.classList.add('active');
        }
      });
      applyCurrentFilter();
    }

    function applyCurrentFilter() {
      const filteredOrders = currentFilter === 'all' 
        ? allOrders 
        : allOrders.filter(order => order.userName === currentFilter);
      
      renderOrderSummary(filteredOrders);
    }

    function calculateServeTime(createdAt, servedAt, attachmentServedAt, attachmentReq) {
      // Handle case when servedAt is null
      if (!servedAt) {
        // Special case: attachment served but main item not served yet
        if (attachmentReq && attachmentServedAt) {
          const orderTime = new Date(createdAt);
          const attachmentServedTime = new Date(attachmentServedAt);
          const attachmentTime = attachmentServedTime - orderTime;
          
          const attachmentMinutes = Math.floor(attachmentTime / (1000 * 60));
          const attachmentHours = Math.floor(attachmentMinutes / 60);
          
          let attachmentTimeText;
          if (attachmentHours > 0) attachmentTimeText = `${attachmentHours}h ${attachmentMinutes % 60}m`;
          else if (attachmentMinutes > 0) attachmentTimeText = `${attachmentMinutes}m`;
          else attachmentTimeText = `0m`;
          
          return { 
            text: '', 
            served: false,
            attachmentTime: attachmentTimeText,
            kitchenTime: 'Waiting',
            hasAttachment: true
          };
        }
        
        // Regular case: nothing served
        return { 
          text: '', 
          served: false,
          attachmentTime: '',
          kitchenTime: '',
          hasAttachment: attachmentReq
        };
      }
      
      const orderTime = new Date(createdAt);
      const servedTime = new Date(servedAt);
      
      // For items with attachmentReq: true
      if (attachmentReq) {
        let attachmentTime = 0;
        let attachmentTimeText = '';
        let kitchenTime = 0;
        let kitchenTimeText = '';
        
        // Calculate attachment time if attachmentServedAt exists
        if (attachmentServedAt) {
          const attachmentServedTime = new Date(attachmentServedAt);
          attachmentTime = attachmentServedTime - orderTime;
          const attachmentMinutes = Math.floor(attachmentTime / (1000 * 60));
          const attachmentHours = Math.floor(attachmentMinutes / 60);
          
          if (attachmentHours > 0) attachmentTimeText = `${attachmentHours}h ${attachmentMinutes % 60}m`;
          else if (attachmentMinutes > 0) attachmentTimeText = `${attachmentMinutes}m`;
          else attachmentTimeText = `0m`;
          
          // Calculate kitchen time: servedAt - attachmentServedAt
          kitchenTime = servedTime - attachmentServedTime;
        } else {
          // If no attachmentServedAt, kitchen time is servedAt - createdAt
          kitchenTime = servedTime - orderTime;
        }
        
        // Format kitchen time
        const kitchenMinutes = Math.floor(kitchenTime / (1000 * 60));
        const kitchenHours = Math.floor(kitchenMinutes / 60);
        
        if (kitchenHours > 0) kitchenTimeText = `${kitchenHours}h ${kitchenMinutes % 60}m`;
        else if (kitchenMinutes > 0) kitchenTimeText = `${kitchenMinutes}m`;
        else kitchenTimeText = `0m`;
        
        // Calculate total time
        const totalTime = attachmentTime + kitchenTime;
        const totalMinutes = Math.floor(totalTime / (1000 * 60));
        const totalHours = Math.floor(totalMinutes / 60);
        
        let totalTimeText;
        if (totalHours > 0) totalTimeText = `${totalHours}h ${totalMinutes % 60}m`;
        else if (totalMinutes > 0) totalTimeText = `${totalMinutes}m`;
        else totalTimeText = `0m`;

        return { 
          text: totalTimeText, 
          served: true,
          attachmentTime: attachmentTimeText,
          kitchenTime: kitchenTimeText,
          hasAttachment: true
        };
      } 
      // For items with attachmentReq: false
      else {
        // Calculate total time: servedAt - createdAt (no breakdown)
        const totalTime = servedTime - orderTime;
        const totalMinutes = Math.floor(totalTime / (1000 * 60));
        const totalHours = Math.floor(totalMinutes / 60);
        
        let totalTimeText;
        if (totalHours > 0) totalTimeText = `${totalHours}h ${totalMinutes % 60}m`;
        else if (totalMinutes > 0) totalTimeText = `${totalMinutes}m`;
        else totalTimeText = `0m`;

        return { 
          text: totalTimeText, 
          served: true,
          attachmentTime: '',
          kitchenTime: '',
          hasAttachment: false
        };
      }
    }

    function calculateAverageServeTime(order) {
      const servedItems = order.items.filter(item => item.servedAt);
      if (servedItems.length === 0) return 'No items served yet';
      
      const totalServeTime = servedItems.reduce((total, item) => {
        const orderTime = new Date(item.createdAt);
        const servedTime = new Date(item.servedAt);
        return total + (servedTime - orderTime);
      }, 0);
      
      const averageMs = totalServeTime / servedItems.length;
      const averageMinutes = Math.floor(averageMs / (1000 * 60));
      
      if (averageMinutes > 0) return `${averageMinutes}m`;
      return `0m`;
    }

    function renderOrderSummary(orders) {
      const tableBody = document.getElementById('order-table-body');
      const totalOrderedElem = document.getElementById('total-ordered');
      const totalServedElem = document.getElementById('total-served');
      const totalRemainingElem = document.getElementById('total-remaining');
      const totalAmountElem = document.getElementById('total-amount');

      // Clear table
      tableBody.innerHTML = '';

      let totalOrdered = 0;
      let totalServed = 0;
      let totalRemaining = 0;
      let totalAmount = 0;

      orders.forEach((order) => {
        // Calculate order totals
        const orderTotal = order.items.reduce((sum, item) => sum + ((item.selling_price || 0) * item.quantity), 0);
        let orderOrdered = 0;
        let orderServed = 0;
        let orderRemaining = 0;

        order.items.forEach((item) => {
          const remainingQty = item.quantity - item.kitchenServedQty;
          orderOrdered += item.quantity;
          orderServed += item.kitchenServedQty;
          orderRemaining += remainingQty;
        });

        totalOrdered += orderOrdered;
        totalServed += orderServed;
        totalRemaining += orderRemaining;
        totalAmount += orderTotal;

        // Create detailed items list
        const itemsList = order.items.map(item => {
          const className = item.quantity === item.kitchenServedQty ? "equal" : "not-equal";
          const serveTimeData = calculateServeTime(item.createdAt, item.servedAt, item.attachmentServedAt, item.attachmentReq);
          const serveTimeClass = serveTimeData.served ? 'served' : 'not-served';
          
          let timeDisplay = serveTimeData.text;
          if (serveTimeData.hasAttachment && item.attachmentReq) {
            timeDisplay = `<small><span style="color: #ff9800; font-size: 14px;">A:${serveTimeData.attachmentTime}</span>&nbsp;&nbsp;&nbsp;<span style="color: #2196f3; font-size: 14px;">K:${serveTimeData.kitchenTime}</span></small>`;
          }
          
          return `<div class="item ${className}">
            <div class="item-content">
              • <strong class="item-name">${item.itemName}</strong> $${(item.selling_price || 0).toFixed(2)}
              <span class="item-quantity">Qty: ${item.quantity}</span>
              <span class="item-served">Served: ${item.kitchenServedQty}</span>
            </div>
            <span class="item-serve-time ${serveTimeClass}">${timeDisplay}</span>
          </div>`;
        }).join('');

        const row = document.createElement('tr');
        row.innerHTML = `
          <td>
            <div class="order-number">#${order.orderNo}</div>
            <div class="order-meta">
              <small>Table: ${order.tableNo}</small><br>
              <small>Waiter: ${order.userName}</small>
            </div>
          </td>
          <td>
            <div class="item-list">
              ${itemsList}
              <div class="order-average-time">
                <strong>Average Serve Time: ${calculateAverageServeTime(order)}</strong>
              </div>
            </div>
          </td>
          <td>
            <div class="order-total">$${orderTotal.toFixed(2)}</div>
          </td>
          <td>${getElapsedTime(order.createdAt)}</td>
        `;

        tableBody.appendChild(row);
      });

      totalOrderedElem.textContent = totalOrdered;
      totalServedElem.textContent = totalServed;
      totalRemainingElem.textContent = totalRemaining;
      totalAmountElem.textContent = totalAmount.toFixed(2);

      // Render/Update the chart
      renderChart(totalOrdered, totalServed, totalRemaining);
    }

    function renderChart(totalOrdered, totalServed, totalRemaining) {
      const ctx = document.getElementById('orderChart').getContext('2d');
      
      // Destroy existing chart if it exists
      if (chartInstance) {
        chartInstance.destroy();
      }
      
      chartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: ['Ordered', 'Served', 'Remaining'],
          datasets: [{
            label: 'Order Summary',
            data: [totalOrdered, totalServed, totalRemaining],
            backgroundColor: ['#3498db', '#2ecc71', '#e74c3c']
          }]
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              display: true,
              position: 'top',
            }
          }
        }
      });
    }

    function getAllOrders(currentUserId) {
      fetch(`/api/cafeorder?companyId=${companyId}&userId=${currentUserId}`)
        .then(response => response.json())
        .then(result => {
          allOrders = result.data || [];
          updateWaiterFilters(allOrders);
          applyCurrentFilter();
        })
        .catch(error => console.error('Error fetching orders:', error));
    }

    // Call Function to Render Data
    getAllOrders();
  </script>
</body>
</html>
