
<div class="row">
  <div class="col-md-12">
    <div class="card">
      <div class="card-body">
        <div class="d-flex align-items-center justify-content-between">
          <div class="d-inline-flex align-items-center">
            <i class="ph-duotone ph-arrow-down-left text-primary me-2 f-20"></i><p class="text-muted mb-0">Daily Tokens Shift-wise for Selected Month</p>
          </div>
          <h4 class="mb-0"><select id="dailyYearFilter" class="form-select d-inline w-auto ms-2"></select>
        <select id="dailyMonthFilter" class="form-select d-inline w-auto ms-2"></select></h4>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- Row for charts -->
<div class="row">
  <div class="col-md-8 d-flex">
    <div class="card flex-fill">
      <div class="card-body">
        <div id="dailyChart" style="height:100%;"></div>
      </div>
    </div>
  </div>
  <div class="col-md-4 d-flex">
    <div class="card flex-fill">
      <div class="card-body">
        <div id="pieChart" style="height:100%;"></div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
let dailyChart, pieChart;
const baseUrl = "<?= base_url() ?>";
const monthNames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

function fetchDailyStats() {
  const year  = document.getElementById('dailyYearFilter').value;
  const month = document.getElementById('dailyMonthFilter').value;

  fetch(baseUrl + "admin/tokens/get_token_stats?year=" + year + "&month=" + month)
    .then(res => res.json())
    .then(data => {
      renderDailyChart(data.daily, month, year);
      renderPieChart(data.daily, month, year);
    })
    .catch(err => console.error(err));
}

function renderDailyChart(data, month, year) {
  const daysInMonth = new Date(year, month, 0).getDate();
  const days = Array.from({length: daysInMonth}, (_, i) => i+1);

  const shifts = [...new Set(data.map(d => d.shift_name))];
  const series = shifts.map(shift => ({
    name: shift,
    data: days.map(day => {
      const found = data.find(d => d.day == day && d.shift_name == shift);
      return found ? found.token_count : 0;
    })
  }));

  const options = {
    chart: { type: 'bar', height: 350, stacked: true, toolbar: { show: false }},
    series,
    xaxis: { categories: days.map(d => `${d} ${monthNames[month-1]}`) },
    //yaxis: { title: { text: 'Tokens' }},
    legend: { position: 'top' },
    tooltip: { y: { formatter: val => val + " tokens" }},
    //title: { text: "Daily Tokens ("+monthNames[month-1]+" "+year+")", align: "center" }
  };

  if (dailyChart) dailyChart.destroy();
  dailyChart = new ApexCharts(document.querySelector("#dailyChart"), options);
  dailyChart.render();
}

function renderPieChart(data, month, year) {
  // shift-wise total counts
  const shiftTotals = {};
  data.forEach(d => {
    shiftTotals[d.shift_name] = (shiftTotals[d.shift_name] || 0) + parseInt(d.token_count);
  });

  const labels = Object.keys(shiftTotals);
  const series = Object.values(shiftTotals);

  const options = {
    chart: { type: 'pie', height: 350 },
    series,
    labels,
    legend: { position: 'top' },
    //title: { text: "Shift % ("+monthNames[month-1]+" "+year+")", align: "center" },
    tooltip: { y: { formatter: val => val + " tokens" }},
  };

  if (pieChart) pieChart.destroy();
  pieChart = new ApexCharts(document.querySelector("#pieChart"), options);
  pieChart.render();
}

function initDailyFilters() {
  const yearSel  = document.getElementById('dailyYearFilter');
  const monthSel = document.getElementById('dailyMonthFilter');
  const currentYear  = new Date().getFullYear();
  const currentMonth = new Date().getMonth()+1;

  for (let y=currentYear-3; y<=currentYear; y++) {
    yearSel.innerHTML += `<option value="${y}" ${y==currentYear?'selected':''}>${y}</option>`;
  }
  for (let m=1; m<=12; m++) {
    monthSel.innerHTML += `<option value="${m}" ${m==currentMonth?'selected':''}>${monthNames[m-1]}</option>`;
  }

  yearSel.onchange  = fetchDailyStats;
  monthSel.onchange = fetchDailyStats;
  fetchDailyStats();
}
document.addEventListener("DOMContentLoaded", initDailyFilters);
</script>







    <div class="row">
      <!-- Pie Chart -->
      <div class="col-md-4 d-flex">
        <div class="card flex-fill">
          <div class="card-body">
            <div id="monthlyPieChart" style="height:100%;"></div>
          </div>
        </div>
      </div>
      <!-- Bar Chart -->
      <div class="col-md-8 d-flex">
        <div class="card flex-fill">
          <div class="card-body">
            <div id="monthlyChart" style="height:100%;"></div>
          </div>
        </div>
      </div>

    </div>


<!-- monthlyYearFilter -->
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
let monthlyChart, monthlyPieChart;
const monthNamesMonthly = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];


function fetchMonthlyStats() {
  const year = document.getElementById('dailyYearFilter').value;

  fetch(baseUrl + "admin/tokens/get_token_stats?year=" + year)
    .then(res => res.json())
    .then(data => {
      renderMonthlyChart(data.monthly, year);
      renderMonthlyPie(data.monthly, year);
    })
    .catch(err => console.error("Monthly fetch error:", err));
}

function renderMonthlyChart(data, year) {
  const months = Array.from({length: 12}, (_, i) => i+1);
  const shifts = [...new Set(data.map(d => d.shift_name))];

  const filteredData = data.filter(d => d.year == year);

  const series = shifts.map(shift => ({
    name: shift,
    data: months.map(m => {
      const found = filteredData.find(d => d.month == m && d.shift_name == shift);
      return found ? parseInt(found.token_count) : 0;
    })
  }));

  const options = {
    chart: { type: 'bar', height: 350, stacked: true, toolbar: { show: false }},
    series,
    xaxis: { categories: monthNamesMonthly },
    yaxis: { title: { text: 'Tokens' }},
    legend: { position: 'bottom' },
    tooltip: { y: { formatter: val => val + " tokens" }},
  };

  if (monthlyChart) monthlyChart.destroy();
  monthlyChart = new ApexCharts(document.querySelector("#monthlyChart"), options);
  monthlyChart.render();
}

function renderMonthlyPie(data, year) {
  const shiftTotals = {};
  data.filter(d => d.year == year).forEach(d => {
    shiftTotals[d.shift_name] = (shiftTotals[d.shift_name] || 0) + parseInt(d.token_count);
  });

  const labels = Object.keys(shiftTotals);
  const series = Object.values(shiftTotals);

  const options = {
    chart: { type: 'pie', height: 350 },
    series,
    labels,
    legend: { position: 'top' },
    tooltip: { y: { formatter: val => val + " tokens" }},
  };

  if (monthlyPieChart) monthlyPieChart.destroy();
  monthlyPieChart = new ApexCharts(document.querySelector("#monthlyPieChart"), options);
  monthlyPieChart.render();
}

function initMonthlyFilters() {
  const yearSel = document.getElementById('dailyYearFilter');
  const currentYear = new Date().getFullYear();

  for (let y=currentYear-3; y<=currentYear; y++) {
    yearSel.innerHTML += `<option value="${y}" ${y==currentYear?'selected':''}>${y}</option>`;
  }

  yearSel.onchange = fetchMonthlyStats;
  fetchMonthlyStats();
}
document.addEventListener("DOMContentLoaded", initMonthlyFilters);
</script>