<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Daily Sales Report</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <!-- Chart.js Library -->
  <style>
    /* Base Styles */
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f9;
      color: #333;
      margin: 0;
      padding: 0;
    }

    .container {
      max-width: 800px;
      margin: 50px auto;
      background: #fff;
      border-radius: 10px;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      overflow: hidden;
    }

    header {
      background-color: #0078d7;
      color: white;
      padding: 20px;
      text-align: center;
      font-size: 24px;
      font-weight: bold;
    }

    .filters {
      display: flex;
      justify-content: space-between;
      padding: 20px;
      background: #f9f9f9;
      border-bottom: 1px solid #ddd;
    }

    .filters input {
      padding: 10px;
      font-size: 16px;
      border: 1px solid #ddd;
      border-radius: 5px;
      outline: none;
    }

    .filters button {
      background-color: #0078d7;
      color: white;
      border: none;
      padding: 10px 20px;
      font-size: 16px;
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .filters button:hover {
      background-color: #0056a8;
    }

    .sales-table {
      width: 100%;
      border-collapse: collapse;
      margin: 20px 0;
    }

    .sales-table thead {
      background: #0078d7;
      color: white;
    }

    .sales-table th, .sales-table td {
      text-align: left;
      padding: 12px 15px;
      border-bottom: 1px solid #ddd;
    }

    .sales-table tr:hover {
      background: #f1f1f1;
    }

    .no-data {
      text-align: center;
      padding: 20px;
      font-size: 18px;
      color: #888;
    }

    canvas {
      margin: 20px auto;
      display: block;
    }

    footer {
      text-align: center;
      padding: 10px;
      font-size: 14px;
      color: #666;
      background-color: #f9f9f9;
    }
  </style>
</head>
<body>
  <div class="container">
    <header>Daily Sales Report</header>

    <div class="filters">
      <div>
        <label for="start-date">Start Date:</label>
        <input type="date" id="start-date">
      </div>
      <div>
        <label for="end-date">End Date:</label>
        <input type="date" id="end-date">
      </div>
      <button id="fetch-sales">Get Sales</button>
    </div>

    <canvas id="sales-chart" width="800" height="400"></canvas> <!-- Chart Placeholder -->

    <table class="sales-table" id="sales-table">
      <thead>
        <tr>
          <th>Date</th>
          <th>Total Sales</th>
        </tr>
      </thead>
      <tbody>
        <tr class="no-data">
          <td colspan="2">No data available. Please select a date range.</td>
        </tr>
      </tbody>
    </table>
  </div>

  <footer>Powered by CyberTech CafeOrder System</footer>

  <script>
    const fetchSalesButton = document.getElementById('fetch-sales');
    const salesTableBody = document.querySelector('#sales-table tbody');
    const startDateInput = document.getElementById('start-date');
    const endDateInput = document.getElementById('end-date');
    const salesChartCanvas = document.getElementById('sales-chart');

    let salesChart; // Chart.js instance

    // Function to set default dates: 7 days ago to today
    const setDefaultDates = () => {
      const today = new Date();
      const sevenDaysAgo = new Date();
      sevenDaysAgo.setDate(today.getDate() - 7);

      // Format dates to YYYY-MM-DD
      const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      };

      // Populate date inputs with defaults
      startDateInput.value = formatDate(sevenDaysAgo);
      endDateInput.value = formatDate(today);
    };

    // Function to fetch sales data
    const fetchSalesData = async () => {
      const startDate = startDateInput.value;
      const endDate = endDateInput.value;

      if (!startDate || !endDate) {
        alert('Please select both start and end dates.');
        return;
      }

      try {
        const response = await fetch(`api/cafeorder/get-sales?startDate=${startDate}&endDate=${endDate}`);
        const data = await response.json();

        // Clear existing rows
        salesTableBody.innerHTML = '';

        if (data.length === 0) {
          salesTableBody.innerHTML = '<tr class="no-data"><td colspan="2">No sales data found for this period.</td></tr>';
          updateChart([], []); // Clear chart data
        } else {
          const dates = [];
          const sales = [];
          data.forEach(sale => {
            dates.push(sale._id); // Collect dates
            sales.push(sale.dailyTotalSales); // Collect sales values

            const row = `
              <tr>
                <td>${sale._id}</td>
                <td>$${sale.dailyTotalSales.toFixed(2)}</td>
              </tr>
            `;
            salesTableBody.innerHTML += row;
          });

          updateChart(dates, sales); // Update chart with new data
        }
      } catch (error) {
        console.error('Error fetching sales data:', error);
        alert('An error occurred while fetching sales data. Please try again later.');
      }
    };

    // Function to initialize or update the chart
    const updateChart = (labels, data) => {
      if (salesChart) {
        salesChart.destroy(); // Destroy the existing chart to avoid duplication
      }

      salesChart = new Chart(salesChartCanvas, {
        type: 'line',
        data: {
          labels: labels, // Dates
          datasets: [{
            label: 'Total Sales ($)',
            data: data, // Sales values
            borderColor: '#0078d7',
            backgroundColor: 'rgba(0, 120, 215, 0.2)',
            fill: true,
            tension: 0.4
          }]
        },
        options: {
          responsive: true,
          plugins: {
            legend: { display: true, position: 'top' },
            tooltip: { enabled: true }
          },
          scales: {
            x: { title: { display: true, text: 'Date' } },
            y: { title: { display: true, text: 'Sales ($)' } }
          }
        }
      });
    };

    // Initialize default dates and fetch initial data
    document.addEventListener('DOMContentLoaded', () => {
      setDefaultDates();
      fetchSalesData(); // Fetch data with default dates after page load
    });

    // Add event listener to fetch sales on button click
    fetchSalesButton.addEventListener('click', fetchSalesData);
  </script>
</body>
</html>
