<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sales Summary with Graph</title>
  <style>
    /* General styles */
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f9;
      margin: 0;
      padding: 0;
    }
    .container {
      max-width: 900px;
      margin: 20px auto;
      background-color: #fff;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    }
    h1 {
      text-align: center;
      color: #333;
      margin-bottom: 20px;
    }

    /* Table styles */
    table {
      width: 100%;
      border-collapse: collapse;
      margin: 20px 0;
    }
    th, td {
      padding: 12px;
      text-align: left;
    }
    th {
      font-weight: bold;
      background-color: #f4f4f4;
      border-bottom: 2px solid #ddd;
    }
    td {
      border-bottom: 1px solid #ddd; /* Only bottom borders */
    }
    td:last-child {
      font-weight: bold;
      color: #555;
    }

    /* Grand total section */
    .summary {
      font-size: 20px;
      font-weight: bold;
      text-align: right;
      margin-top: 20px;
      color: #444;
    }

    /* Chart styling */
    canvas {
      margin-top: 30px;
    }

    /* Date filter section */
    .filter-section {
      margin-bottom: 25px;
      padding: 15px;
      background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      border: 1px solid #e9ecef;
    }

    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      flex-wrap: wrap;
      gap: 10px;
    }

    .filter-title {
      font-size: 13px;
      font-weight: 600;
      color: #495057;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .date-inputs-row {
      display: flex;
      gap: 10px;
      align-items: center;
      flex-wrap: wrap;
      margin-bottom: 12px;
    }

    .date-input-wrapper {
      display: flex;
      align-items: center;
      gap: 6px;
      background: white;
      padding: 6px 10px;
      border-radius: 8px;
      border: 1px solid #dee2e6;
      transition: all 0.2s;
    }

    .date-input-wrapper:hover {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .date-input-wrapper label {
      font-size: 11px;
      font-weight: 600;
      color: #6c757d;
      white-space: nowrap;
    }

    .date-input-wrapper input[type="date"] {
      padding: 4px 6px;
      border: none;
      border-radius: 4px;
      font-size: 12px;
      cursor: pointer;
      background: transparent;
      color: #495057;
      font-weight: 500;
    }

    .date-input-wrapper input[type="date"]:focus {
      outline: none;
    }

    .quick-filters-row {
      display: flex;
      align-items: center;
      gap: 6px;
      flex-wrap: wrap;
    }

    .quick-filters-label {
      font-size: 11px;
      font-weight: 600;
      color: #6c757d;
      margin-right: 4px;
    }

    .quick-filters {
      display: flex;
      gap: 6px;
      flex-wrap: wrap;
    }

    .quick-filter-btn {
      padding: 4px 10px;
      background: #e9ecef;
      color: #495057;
      border: 1px solid #dee2e6;
      border-radius: 6px;
      cursor: pointer;
      font-size: 11px;
      font-weight: 600;
      transition: all 0.2s ease;
      white-space: nowrap;
      min-width: auto;
    }

    .quick-filter-btn:hover {
      background: #667eea;
      color: white;
      border-color: #667eea;
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3);
    }

    .quick-filter-btn.active {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border-color: #667eea;
      box-shadow: 0 2px 6px rgba(102, 126, 234, 0.4);
      transform: translateY(-1px);
    }

    .apply-filter-btn {
      padding: 6px 14px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      border-radius: 8px;
      cursor: pointer;
      font-size: 12px;
      font-weight: 600;
      transition: all 0.2s ease;
      box-shadow: 0 2px 4px rgba(102, 126, 234, 0.3);
      white-space: nowrap;
    }

    .apply-filter-btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 8px rgba(102, 126, 234, 0.4);
    }

    .apply-filter-btn:active {
      transform: translateY(0);
    }
  </style>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <div class="container">
    <h1>Bono Sales Summary</h1>

    <!-- Date Filter Section -->
    <div class="filter-section">
      <div class="filter-header">
        <div class="filter-title">📅 Date Range Filter</div>
      </div>
      <div class="date-inputs-row">
        <div class="date-input-wrapper">
          <label for="startDate">From:</label>
          <input type="date" id="startDate" />
        </div>
        <div class="date-input-wrapper">
          <label for="endDate">To:</label>
          <input type="date" id="endDate" />
        </div>
        <button class="apply-filter-btn" onclick="applyDateFilter()">Apply</button>
      </div>
      <div class="quick-filters-row">
        <span class="quick-filters-label">Quick:</span>
        <div class="quick-filters">
          <button class="quick-filter-btn" onclick="setQuickFilter('today')">Today</button>
          <button class="quick-filter-btn" onclick="setQuickFilter('yesterday')">Yesterday</button>
          <button class="quick-filter-btn" onclick="setQuickFilter('dayBeforeYesterday')">2 Days</button>
        </div>
      </div>
    </div>

    <!-- Chart -->
    <canvas id="salesChart" width="400" height="200"></canvas>

    <!-- Table -->
    <table>
      <thead>
        <tr>
          <th>Item Name</th>
          <th>Bono Served</th>
          <th>Selling Price</th>
          <th>Total Sales</th>
        </tr>
      </thead>
      <tbody id="sales-table-body">
        <!-- Rows will be dynamically added -->
      </tbody>
    </table>

    <!-- Grand Total -->
    <div class="summary">Grand Total: $<span id="grand-total">0.00</span></div>
  </div>

  <script>
    let salesChart = null; // Store chart instance for re-rendering

    // Initialize date inputs with current date
    document.addEventListener('DOMContentLoaded', function() {
      const today = new Date().toISOString().split('T')[0];
      document.getElementById('startDate').value = today;
      document.getElementById('endDate').value = today;
      fetchSalesData();
    });

    // Fetch Data from the API
    async function fetchSalesData(startDate = null, endDate = null) {
      try {
        let url = '/api/cafeorder/get-bono';
        const params = new URLSearchParams();
        
        if (startDate && endDate) {
          params.append('startDate', startDate);
          params.append('endDate', endDate);
          url += '?' + params.toString();
        }

        const response = await fetch(url);
        const result = await response.json();

        if (result.success) {
          renderSalesSummary(result.data); // Render the table
          renderSalesChart(result.data); // Render the graph
        } else {
          console.error('Failed to fetch sales data:', result.message);
        }
      } catch (error) {
        console.error('Error fetching sales data:', error);
      }
    }

    // Apply date filter
    function applyDateFilter() {
      const startDate = document.getElementById('startDate').value;
      const endDate = document.getElementById('endDate').value;
      
      if (!startDate || !endDate) {
        alert('Please select both start and end dates');
        return;
      }

      if (new Date(startDate) > new Date(endDate)) {
        alert('Start date cannot be after end date');
        return;
      }

      // Remove active class from all quick filter buttons
      document.querySelectorAll('.quick-filter-btn').forEach(btn => {
        btn.classList.remove('active');
      });

      fetchSalesData(startDate, endDate);
    }

    // Set quick filter dates
    function setQuickFilter(filterType) {
      const today = new Date();
      let startDate, endDate;

      switch(filterType) {
        case 'today':
          startDate = new Date(today);
          endDate = new Date(today);
          break;
        case 'yesterday':
          startDate = new Date(today);
          startDate.setDate(today.getDate() - 1);
          endDate = new Date(startDate);
          break;
        case 'dayBeforeYesterday':
          startDate = new Date(today);
          startDate.setDate(today.getDate() - 2);
          endDate = new Date(startDate);
          break;
        default:
          return;
      }

      // Format dates as YYYY-MM-DD
      const startDateStr = startDate.toISOString().split('T')[0];
      const endDateStr = endDate.toISOString().split('T')[0];

      // Set date inputs
      document.getElementById('startDate').value = startDateStr;
      document.getElementById('endDate').value = endDateStr;

      // Update active button
      document.querySelectorAll('.quick-filter-btn').forEach(btn => {
        btn.classList.remove('active');
      });
      event.target.classList.add('active');

      // Fetch data with the selected dates
      fetchSalesData(startDateStr, endDateStr);
    }

    // Render the Sales Table
    function renderSalesSummary(data) {
      const tableBody = document.getElementById('sales-table-body');
      const grandTotalElem = document.getElementById('grand-total');
      
      // Clear existing table rows
      tableBody.innerHTML = '';
      
      let grandTotal = 0;

      data.forEach((item) => {
        // Skip invalid selling prices
        if (!item.selling_price || isNaN(item.selling_price)) {
          console.warn(`Skipping item due to invalid selling_price:`, item);
          return;
        }

        const totalSales = item.totalSales;
        grandTotal += totalSales;

        const row = document.createElement('tr');
        row.innerHTML = `
          <td>${item.itemName}</td>
          <td>${item.totalKitchenServedQty}</td>
          <td>$${item.selling_price.toFixed(2)}</td>
          <td>$${totalSales.toFixed(2)}</td>
        `;
        tableBody.appendChild(row);
      });

      grandTotalElem.textContent = grandTotal.toFixed(2);
    }

    // Render the Sales Chart
    function renderSalesChart(data) {
      const ctx = document.getElementById('salesChart').getContext('2d');
      
      // Destroy existing chart if it exists
      if (salesChart) {
        salesChart.destroy();
      }

      const labels = data.map(item => item.itemName); // Item names
      const salesData = data.map(item => item.totalSales); // Total sales per item

      // Dynamic colors
      const colors = salesData.map(() => `hsl(${Math.random() * 360}, 70%, 70%)`);

      salesChart = new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: 'Total Sales ($)',
            data: salesData,
            backgroundColor: colors,
            borderColor: colors.map(color => color.replace('70%', '50%')),
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          plugins: {
            legend: { display: true, position: 'top' }
          },
          scales: { y: { beginAtZero: true } }
        }
      });
    }
  </script>
</body>
</html>
