<?php
require 'db.php';
require 'functions.php';
requireRole(['admin']);

$pagetitle = 'Dashboard';
$activemenu = 'dashboard';
require 'header.php';
?>

<div class="dfp-stats-row" id="dfpStatsRow">
  <div class="dfp-stat-box"><div class="num" id="statTotal">-</div><div class="lbl">Total Villagers</div></div>
  <div class="dfp-stat-box"><div class="num" id="statPending">-</div><div class="lbl">Pending Approval</div></div>
  <div class="dfp-stat-box"><div class="num" id="statApproved">-</div><div class="lbl">Approved</div></div>
  <div class="dfp-stat-box"><div class="num" id="statRejected">-</div><div class="lbl">Rejected</div></div>
  <div class="dfp-stat-box"><div class="num" id="statActive">-</div><div class="lbl">Active Passes</div></div>
  <div class="dfp-stat-box"><div class="num" id="statExpiring">-</div><div class="lbl">Expiring in 30 days</div></div>
  <div class="dfp-stat-box"><div class="num" id="statRevenue">-</div><div class="lbl">Revenue Collected</div></div>
</div>

<div class="dfp-card">
  <h3>Registrations by Panchayat</h3>
  <canvas id="panchayatChart" height="90"></canvas>
</div>

<?php require 'footer.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
var panchayatChart = null;

function dfpRenderDashboard(data) {
  $('#statTotal').text(data.total);
  $('#statPending').text(data.pending);
  $('#statApproved').text(data.approved);
  $('#statRejected').text(data.rejected);
  $('#statActive').text(data.active);
  $('#statExpiring').text(data.expiring);
  $('#statRevenue').text(data.revenueformatted);

  var ctx = document.getElementById('panchayatChart').getContext('2d');
  var labels = data.panchayatlabels;
  var values = data.panchayatcounts;

  if (panchayatChart) {
    panchayatChart.data.labels = labels;
    panchayatChart.data.datasets[0].data = values;
    panchayatChart.update();
  } else {
    panchayatChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{ label: 'Villagers', data: values, backgroundColor: '#111111' }]
      },
      options: {
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
      }
    });
  }
}

$(function () {
  dfpStartAutoRefresh('ajax_admin_dashboardstats.php', dfpRenderDashboard, 60000);
});
</script>
<?php require 'footer2.php'; ?>
