<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Log Activities</title>
  <style>
  /* Full Updated CSS */
body {
  font-family: Arial, sans-serif;
  margin: 20px;
  padding: 0;
  background-color: #f4f6f9;
  color: #333;
}

h3 {
  text-align: center;
  margin-bottom: 20px;
  font-weight: bold;
  font-size: 24px;
  color: #1a9ef6;
}

#logTable {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

#logTable th, #logTable td {
  border: 1px solid #ddd;
  padding: 12px;
}

#logTable th {
  background-color: #1a9ef6;
  text-align: left;
  color: white;
}

#logTable tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

#logTable tbody tr:hover {
  background-color: #f1f1f1;
}

.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #e6f2ff;
  padding: 10px 20px;
  margin-bottom: 10px;
  border-radius: 5px;
}

.user-filter {
  display: flex;
  gap: 10px;
}

.reset-btn {
  padding: 8px 14px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-left: auto;
}

.reset-btn:hover {
  background-color: #d32f2f;
}

.user-btn {
  padding: 8px 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.user-btn:hover {
  background-color: #45a049;
}

.user-btn.active {
  background-color: #2E7D32;
}

.total-amount {
  font-size: 16px;
  margin-top: 10px;
  padding: 12px;
  background-color: #f8f8f8;
  border-radius: 4px;
  display: inline-block;
}

  </style>
</head>
<body>
  <h3>Log Activities</h3>
  
  <div class="filter-row">
    
 
    <div class="user-filter" id="userFilter">
      <!-- User buttons will be added here dynamically -->
    </div>
<div class="right-side">  <button class="reset-btn" id="resetFilter">Reset Filter</button>
</div>
   
  
  </div>
  <div class="total-amount" id="totalAmount">
    Total Amount: $0.00
  </div>
  
  <table id="logTable">
    <thead>
      <tr>
        <th>Date and Time</th>
        <th>Order No</th>
        <th>Amount</th>
        <th>Action</th>
        <th>Taken By</th>
        <th>Waiter</th>
      </tr>
    </thead>
    <tbody>
      <!-- Log activities will be dynamically inserted here -->
    </tbody>
  </table>

  <script>
    // JavaScript
    let allLogs = []; // Store all logs for filtering
    
    const fetchLogs = async () => {
      try {
        const response = await fetch('/api/cafeorder/log-activity'); // Adjust the URL to match your backend endpoint
        const data = await response.json();

        if (data.success) {
          allLogs = data.logs; // Store all logs
          renderLogs(allLogs);
          createUserFilters(allLogs);
          updateTotalAmount(allLogs);
        } else {
          console.error('Failed to fetch logs:', data.message);
        }
      } catch (error) {
        console.error('Error fetching logs:', error);
      }
    };

    const renderLogs = (logs) => {
      const logTableBody = document.querySelector('#logTable tbody');
      logTableBody.innerHTML = ''; // Clear existing rows

      logs.forEach(log => {
        const row = logTableBody.insertRow();
        const dateCell = row.insertCell();
        const orderNoCell = row.insertCell();
        const paidAmountCell = row.insertCell();
        const actionCell = row.insertCell();
        const usernameCell = row.insertCell();
        const waiternameCell = row.insertCell();

        // Populate cells with data
        dateCell.textContent = new Date(log.timestamp).toLocaleString();
        orderNoCell.textContent = log.orderId?.orderNo || 'N/A';
        paidAmountCell.textContent = log.paidAmount ? '$' + parseFloat(log.paidAmount).toFixed(2) : 'N/A';
        actionCell.textContent = log.action;
        usernameCell.textContent = log.userId?.username || 'N/A';
        waiternameCell.textContent = log.waiterName || 'N/A';
      });

      // Add summary row if there are logs
      if (logs.length > 0) {
        const total = calculateTotal(logs);
        const summaryRow = logTableBody.insertRow();
        summaryRow.className = 'summary-row';
        
        const emptyCell1 = summaryRow.insertCell();
        const emptyCell2 = summaryRow.insertCell();
        const totalCell = summaryRow.insertCell();
        const emptyCell4 = summaryRow.insertCell();
        const emptyCell5 = summaryRow.insertCell();
        const emptyCell6 = summaryRow.insertCell();
        
        emptyCell1.colSpan = 2;
        emptyCell1.textContent = 'Total:';
        totalCell.textContent = '$' + total.toFixed(2);
        emptyCell4.colSpan = 3;
      }
    };

    const calculateTotal = (logs) => {
      return logs.reduce((sum, log) => {
        const amount = parseFloat(log.paidAmount) || 0;
        return sum + amount;
      }, 0);
    };

    const updateTotalAmount = (logs) => {
      const total = calculateTotal(logs);
      document.getElementById('totalAmount').textContent = 
        `Total Amount: $${total.toFixed(2)}`;
    };

    const createUserFilters = (logs) => {
      const userFilterDiv = document.getElementById('userFilter');
      userFilterDiv.innerHTML = ''; // Clear existing buttons
      
      // Get unique usernames
      const usernames = [...new Set(logs.map(log => log.userId?.username || 'N/A'))];
      
      // Create a button for each username
      usernames.forEach(username => {
        const button = document.createElement('button');
        button.className = 'user-btn';
        button.textContent = username;
        button.dataset.username = username;
        button.addEventListener('click', () => filterByUser(username));
        userFilterDiv.appendChild(button);
      });
    };

    const filterByUser = (username) => {
      // Remove active class from all buttons
      document.querySelectorAll('.user-btn').forEach(btn => {
        btn.classList.remove('active');
      });
      
      // Add active class to clicked button
      const activeBtn = document.querySelector(`.user-btn[data-username="${username}"]`);
      if (activeBtn) {
        activeBtn.classList.add('active');
      }
      
      // Filter logs
      const filteredLogs = allLogs.filter(log => {
        const logUsername = log.userId?.username || 'N/A';
        return logUsername === username;
      });
      
      renderLogs(filteredLogs);
      updateTotalAmount(filteredLogs);
    };

    const resetFilter = () => {
      // Remove active class from all buttons
      document.querySelectorAll('.user-btn').forEach(btn => {
        btn.classList.remove('active');
      });
      
      // Show all logs
      renderLogs(allLogs);
      updateTotalAmount(allLogs);
    };

    // Event listeners
    document.getElementById('resetFilter').addEventListener('click', resetFilter);

    // Fetch logs when the page loads
    document.addEventListener('DOMContentLoaded', fetchLogs);
  </script>
</body>
</html>