<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Revenue Dashboard</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <div class="container mt-4">
    <ul class="nav nav-tabs" id="dashboardTabs" role="tablist">
      <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#monthly">Monthly Trends</button></li>
      <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#yearly">Yearly Comparison</button></li>
      <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#quarterly">Quarterly Summary</button></li>
      <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#top">Top Months</button></li>
      <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#percentage">% Contribution</button></li>
      <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#growth">Month-on-Month Growth</button></li>
      <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#weekly">Weekly Chart</button></li>
    </ul>
    <div class="tab-content pt-4">
      <div class="tab-pane fade show active" id="monthly"><canvas id="monthlyChart"></canvas></div>
      <div class="tab-pane fade" id="yearly"><canvas id="yearlyChart"></canvas></div>
      <div class="tab-pane fade" id="quarterly"><canvas id="quarterlyChart"></canvas></div>
      <div class="tab-pane fade" id="top"><canvas id="topMonthsChart"></canvas></div>
      <div class="tab-pane fade" id="percentage"><canvas id="percentageChart"></canvas></div>
      <div class="tab-pane fade" id="growth"><canvas id="growthChart"></canvas></div>
      <div class="tab-pane fade" id="weekly"><canvas id="weeklyChart"></canvas></div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    const colors = ['#36A2EB', '#FF6384', '#FFCE56', '#4BC0C0', '#9966FF'];

    fetch('analytics_data.php')
      .then(res => res.json())
      .then(data => {
        renderMonthlyChart(data);
        renderYearlyChart(data);
        renderQuarterlyChart(data);
        renderTopMonthsChart(data);
        renderPercentageChart(data);
        renderGrowthChart(data);
        renderWeeklyChart(data);
      });

    function renderMonthlyChart(data) {
      const ctx = document.getElementById('monthlyChart').getContext('2d');
      const datasets = Object.keys(data.monthly).map((year, idx) => ({
        label: year,
        data: data.months.map(m => data.monthly[year][m] || 0),
        borderColor: colors[idx % colors.length],
        fill: false
      }));
      new Chart(ctx, {
        type: 'line',
        data: { labels: data.months, datasets },
        options: { responsive: true, plugins: { title: { display: true, text: 'Monthly Trends' } } }
      });
    }

    function renderYearlyChart(data) {
      const ctx = document.getElementById('yearlyChart').getContext('2d');
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: Object.keys(data.yearly),
          datasets: [{
            label: 'Total Revenue',
            data: Object.values(data.yearly),
            backgroundColor: colors
          }]
        },
        options: { responsive: true, plugins: { title: { display: true, text: 'Yearly Comparison' } } }
      });
    }

    function renderQuarterlyChart(data) {
      const ctx = document.getElementById('quarterlyChart').getContext('2d');
      const labels = ['Q1', 'Q2', 'Q3', 'Q4'];
      const datasets = Object.keys(data.quarterly).map((year, idx) => ({
        label: year,
        data: labels.map(q => data.quarterly[year][q] || 0),
        backgroundColor: colors[idx % colors.length]
      }));
      new Chart(ctx, {
        type: 'bar',
        data: { labels, datasets },
        options: { responsive: true, plugins: { title: { display: true, text: 'Quarterly Summary' } } }
      });
    }

    function renderTopMonthsChart(data) {
      const allMonths = [];
      for (let year in data.monthly) {
        for (let month in data.monthly[year]) {
          allMonths.push({ label: `${month} ${year}`, value: data.monthly[year][month] });
        }
      }
      const top = allMonths.sort((a,b) => b.value - a.value).slice(0, 5);
      const ctx = document.getElementById('topMonthsChart').getContext('2d');
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: top.map(x => x.label),
          datasets: [{ label: 'Revenue', data: top.map(x => x.value), backgroundColor: colors }]
        },
        options: { responsive: true, plugins: { title: { display: true, text: 'Top 5 Months' } } }
      });
    }

    function renderPercentageChart(data) {
      const ctx = document.getElementById('percentageChart').getContext('2d');
      const year = Object.keys(data.monthly).pop();
      const total = Object.values(data.monthly[year]).reduce((a,b) => a + b, 0);
      const percentages = data.months.map(m => (data.monthly[year][m] || 0) / total * 100);
      new Chart(ctx, {
        type: 'pie',
        data: {
          labels: data.months,
          datasets: [{ label: `% Contribution - ${year}`, data: percentages, backgroundColor: colors.concat(colors) }]
        },
        options: { responsive: true, plugins: { title: { display: true, text: `% Monthly Contribution - ${year}` } } }
      });
    }

    function renderGrowthChart(data) {
      const ctx = document.getElementById('growthChart').getContext('2d');
      const year = Object.keys(data.monthly).pop();
      const values = data.months.map(m => data.monthly[year][m] || 0);
      const growth = values.map((v, i) => i === 0 ? 0 : ((v - values[i - 1]) / values[i - 1] * 100).toFixed(2));
      new Chart(ctx, {
        type: 'line',
        data: { labels: data.months, datasets: [{ label: `MoM Growth - ${year}`, data: growth, borderColor: '#198754' }] },
        options: { responsive: true, plugins: { title: { display: true, text: 'Month-on-Month Growth (%)' } } }
      });
    }

    function renderWeeklyChart(data) {
      const ctx = document.getElementById('weeklyChart').getContext('2d');
      const labels = data.weeks.map(w => `Week ${w.week}`);
      const values = data.weeks.map(w => w.total);
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels,
          datasets: [{
            label: 'Weekly Revenue',
            data: values,
            backgroundColor: '#6610f2'
          }]
        },
        options: {
          responsive: true,
          plugins: {
            title: {
              display: true,
              text: 'Weekly Revenue Overview'
            }
          },
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    }
  </script>
</body>
</html>
