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

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
$u = current_user();
$userId = (int)$u['id'];

$primary = get_primary_account($conn,$userId);

/* ===============================
   LOAD DAILY STATS (30 DAYS)
================================ */
$data = [];
$st = $conn->prepare("
  SELECT
    DATE(e.created_at) d,
    SUM(CASE WHEN e.direction='credit' THEN e.amount ELSE 0 END) inflow,
    SUM(CASE WHEN e.direction='debit' THEN e.amount ELSE 0 END) outflow
  FROM ledger_entries e
  WHERE e.account_id=?
    AND e.created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
  GROUP BY DATE(e.created_at)
  ORDER BY d ASC
");
$st->bind_param("i", $primary['id']);
$st->execute();
$res = $st->get_result();
while($r=$res->fetch_assoc()) $data[]=$r;

$title = 'Account Analytics';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/customer_sidebar.php';
?>

<main style="margin-left:240px;min-height:100vh">
<div class="container-fluid py-4">

<h3 class="fw-bold mb-3">Account Analytics</h3>

<div class="card ab-card p-4">
  <canvas id="flowChart" height="100"></canvas>
</div>

</div>
</main>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const labels = <?= json_encode(array_column($data,'d')) ?>;
const inflow = <?= json_encode(array_column($data,'inflow')) ?>;
const outflow = <?= json_encode(array_column($data,'outflow')) ?>;

new Chart(document.getElementById('flowChart'), {
  type: 'line',
  data: {
    labels,
    datasets: [
      {
        label: 'Inflow',
        data: inflow,
        borderColor: 'green',
        tension: .3
      },
      {
        label: 'Outflow',
        data: outflow,
        borderColor: 'red',
        tension: .3
      }
    ]
  }
});
</script>

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