<?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';

$user   = current_user();
$userId = (int)($user['id'] ?? 0);

/* ===============================
   LOAD ACCOUNTS
================================ */
$accounts = [];
$res = $conn->query("
  SELECT id, account_type, currency, balance
  FROM accounts
  WHERE user_id = $userId
");
while ($r = $res->fetch_assoc()) {
  $accounts[] = $r;
}

/* ===============================
   KPIs (LAST 30 DAYS)
================================ */
$credits30 = 0;
$debits30  = 0;
$txCount   = 0;
$idList    = '';

if (!empty($accounts)) {
  $ids    = array_column($accounts, 'id');
  $idList = implode(',', array_map('intval', $ids));

  $q = $conn->query("
    SELECT
      SUM(CASE WHEN direction='credit' THEN amount ELSE 0 END) AS credits,
      SUM(CASE WHEN direction='debit' THEN amount ELSE 0 END)  AS debits,
      COUNT(*) AS cnt
    FROM ledger_entries
    WHERE account_id IN ($idList)
      AND created_at >= (NOW() - INTERVAL 30 DAY)
  ");
  if ($q) {
    $row = $q->fetch_assoc();
    $credits30 = (float)($row['credits'] ?? 0);
    $debits30  = (float)($row['debits'] ?? 0);
    $txCount   = (int)($row['cnt'] ?? 0);
  }
}

/* ===============================
   RECENT TRANSACTIONS
================================ */
$recent = [];
if ($idList) {
  $r = $conn->query("
    SELECT
      e.amount,
      e.currency,
      e.direction,
      e.created_at,
      t.ref,
      t.type
    FROM ledger_entries e
    JOIN ledger_txn t ON t.id = e.txn_id
    WHERE e.account_id IN ($idList)
    ORDER BY e.id DESC
    LIMIT 6
  ");
  if ($r) {
    while ($x = $r->fetch_assoc()) {
      $recent[] = $x;
    }
  }
}

$title = 'Dashboard';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/customer_sidebar.php';

?>

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


  <!-- HEADER -->
  <div class="mb-4">
    <h3 class="fw-bold mb-0">
      Welcome<?= !empty($user['full_name']) ? ', '.e($user['full_name']) : '' ?>
    </h3>
    <small class="text-muted">Your banking overview</small>
  </div>

  <!-- KPIs -->
  <div class="row g-3 mb-4">

    <div class="col-md-3">
      <div class="card shadow-sm p-3">
        <div class="text-muted small">Inflow (30 days)</div>
        <div class="fs-4 fw-bold text-success">
          <?= e($accounts[0]['currency'] ?? 'GHS') ?> <?= money($credits30) ?>
        </div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card shadow-sm p-3">
        <div class="text-muted small">Outflow (30 days)</div>
        <div class="fs-4 fw-bold text-danger">
          <?= e($accounts[0]['currency'] ?? 'GHS') ?> <?= money($debits30) ?>
        </div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card shadow-sm p-3">
        <div class="text-muted small">Transactions</div>
        <div class="fs-4 fw-bold"><?= number_format($txCount) ?></div>
      </div>
    </div>

    <div class="col-md-3">
      <div class="card shadow-sm p-3">
        <div class="text-muted small">KYC Status</div>
        <div class="fs-5 fw-bold text-uppercase">
          <?= e($user['kyc_status'] ?? 'unverified') ?>
        </div>
      </div>
    </div>

  </div>

  <!-- CHARTS -->
  <div class="row g-3 mb-4">

    <div class="col-lg-8">
      <div class="card shadow-sm p-4">
        <h6 class="fw-bold mb-3">Cash Flow (30 Days)</h6>
        <canvas id="flowChart" height="120"></canvas>
      </div>
    </div>

    <div class="col-lg-4">
      <div class="card shadow-sm p-4">
        <h6 class="fw-bold mb-3">Account Balances</h6>
        <canvas id="balanceChart" height="220"></canvas>
      </div>
    </div>

  </div>

  <!-- RECENT TRANSACTIONS -->
  <div class="card shadow-sm p-4">
    <h6 class="fw-bold mb-3">Recent Transactions</h6>

    <div class="table-responsive">
      <table class="table align-middle">
        <thead>
          <tr>
            <th>Date</th>
            <th>Reference</th>
            <th>Type</th>
            <th>Direction</th>
            <th class="text-end">Amount</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$recent): ?>
            <tr>
              <td colspan="5" class="text-center text-muted py-3">
                No transactions yet
              </td>
            </tr>
          <?php endif; ?>

          <?php foreach ($recent as $r): ?>
            <tr>
              <td><?= date('d M Y', strtotime($r['created_at'])) ?></td>
              <td class="fw-semibold"><?= e($r['ref']) ?></td>
              <td><?= strtoupper(e($r['type'])) ?></td>
              <td>
                <span class="badge <?= $r['direction']==='credit'?'bg-success':'bg-danger' ?>">
                  <?= strtoupper($r['direction']) ?>
                </span>
              </td>
              <td class="text-end">
                <?= e($r['currency']) ?> <?= money($r['amount']) ?>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>
  </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
new Chart(document.getElementById('flowChart'), {
  type: 'bar',
  data: {
    labels: ['Credits', 'Debits'],
    datasets: [{
      data: [<?= $credits30 ?>, <?= $debits30 ?>],
      backgroundColor: ['#198754', '#dc3545']
    }]
  },
  options: { plugins:{legend:{display:false}} }
});

new Chart(document.getElementById('balanceChart'), {
  type: 'doughnut',
  data: {
    labels: [
      <?php foreach ($accounts as $a) echo "'".$a['account_type']."',"; ?>
    ],
    datasets: [{
      data: [
        <?php foreach ($accounts as $a) echo (float)$a['balance'].","; ?>
      ],
      backgroundColor: ['#0d6efd','#198754','#ffc107','#dc3545']
    }]
  }
});
</script>

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