<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);

/* Helper: scalar */
function scalar(mysqli $conn, string $sql, $default=0) {
  $res = $conn->query($sql);
  if (!$res) return $default;
  $row = $res->fetch_row();
  return $row && isset($row[0]) ? $row[0] : $default;
}

$totalCustomers = (int)scalar($conn, "SELECT COUNT(*) FROM users", 0);
$kycPending     = (int)scalar($conn, "SELECT COUNT(*) FROM kyc_submissions WHERE status='pending'", 0);
$loanPending    = (int)scalar($conn, "SELECT COUNT(*) FROM loans WHERE status='pending'", 0);
$loanExposure   = (float)scalar($conn, "SELECT COALESCE(SUM(amount),0) FROM loans WHERE status IN ('active','approved')", 0);
$todayDebits    = (float)scalar($conn, "SELECT COALESCE(SUM(amount),0) FROM ledger_entries WHERE direction='debit' AND created_at >= UTC_DATE()", 0);

/* Chart: last 7 days debit volume */
$labels = [];
$values = [];
$map = [];
$res = $conn->query("
  SELECT DATE(created_at) d, COALESCE(SUM(amount),0) amt
  FROM ledger_entries
  WHERE direction='debit'
    AND created_at >= (UTC_DATE() - INTERVAL 6 DAY)
  GROUP BY DATE(created_at)
  ORDER BY d ASC
");
while ($res && ($r=$res->fetch_assoc())) $map[$r['d']] = (float)$r['amt'];

for ($i=6; $i>=0; $i--) {
  $d = gmdate('Y-m-d', time()-($i*86400));
  $labels[] = $d;
  $values[] = $map[$d] ?? 0;
}

$title = 'Reports — Admin';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';
?>

<div class="container-fluid py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="fw-bold mb-0">Reports</h3>
    <a class="btn btn-sm btn-outline-secondary" href="dashboard.php">Back</a>
  </div>

  <div class="row g-3">
    <div class="col-md-3"><div class="card ab-card p-3"><div class="text-muted small">Customers</div><div class="fs-4 fw-bold"><?= number_format($totalCustomers) ?></div></div></div>
    <div class="col-md-3"><div class="card ab-card p-3"><div class="text-muted small">KYC Pending</div><div class="fs-4 fw-bold"><?= number_format($kycPending) ?></div></div></div>
    <div class="col-md-3"><div class="card ab-card p-3"><div class="text-muted small">Loans Pending</div><div class="fs-4 fw-bold"><?= number_format($loanPending) ?></div></div></div>
    <div class="col-md-3"><div class="card ab-card p-3"><div class="text-muted small">Loan Exposure</div><div class="fs-4 fw-bold">GHS <?= number_format($loanExposure,2) ?></div></div></div>
  </div>

  <div class="row g-3 mt-1">
    <div class="col-lg-8">
      <div class="card ab-card p-4">
        <div class="fw-bold mb-2">7-Day Debit Volume</div>
        <canvas id="volChart" height="90"></canvas>
      </div>
    </div>
    <div class="col-lg-4">
      <div class="card ab-card p-4">
        <div class="fw-bold mb-2">Today (Debits)</div>
        <div class="fs-3 fw-bold">GHS <?= number_format($todayDebits,2) ?></div>
        <div class="text-muted small mt-2">Use this for daily reconciliation reports.</div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
new Chart(document.getElementById('volChart'), {
  type: 'line',
  data: {
    labels: <?= json_encode($labels) ?>,
    datasets: [{ data: <?= json_encode($values) ?>, tension: 0.35 }]
  },
  options: { plugins:{legend:{display:false}}, scales:{y:{beginAtZero:true}} }
});
</script>

<?php include __DIR__ . '/../../views/partials/foot.php'; ?>
