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

/* ===============================
   LEDGER BALANCE (SOURCE OF TRUTH)
================================ */
function ledger_balance(mysqli $conn, int $accountId): float {
  $st = $conn->prepare("
    SELECT COALESCE(
      SUM(CASE WHEN direction='credit' THEN amount ELSE -amount END),0
    )
    FROM ledger_entries
    WHERE account_id=?
  ");
  $st->bind_param("i", $accountId);
  $st->execute();
  return (float)($st->get_result()->fetch_row()[0] ?? 0);
}

/* ===============================
   LOAD USER ACCOUNTS
================================ */
$accounts = [];
$st = $conn->prepare("
  SELECT *
  FROM accounts
  WHERE user_id=?
  ORDER BY is_primary DESC, id ASC
");
$st->bind_param("i", $userId);
$st->execute();
$res = $st->get_result();
while ($r = $res->fetch_assoc()) $accounts[] = $r;

if (!$accounts) die('No account');

/* ===============================
   SELECT ACCOUNT
================================ */
$accountId = (int)($_GET['account_id'] ?? $accounts[0]['id']);
$own = false;
foreach ($accounts as $a) {
  if ((int)$a['id'] === $accountId) { $own = true; break; }
}
if (!$own) die('Invalid account');

/* CURRENT BALANCE */
$currentBalance = ledger_balance($conn, $accountId);

/* ===============================
   FILTERS
================================ */
$q = trim($_GET['q'] ?? '');
$direction = $_GET['direction'] ?? '';

/* ===============================
   BUILD QUERY
================================ */
$sql = "
  SELECT
    t.ref,
    t.type,
    t.status,
    t.narration,
    t.created_at,
    e.direction,
    e.amount,
    e.currency,
    e.balance_after
  FROM ledger_entries e
  JOIN ledger_txn t ON t.id = e.txn_id
  WHERE e.account_id = ?
";

$types = "i";
$params = [$accountId];

if ($direction === 'credit' || $direction === 'debit') {
  $sql .= " AND e.direction = ?";
  $types .= "s";
  $params[] = $direction;
}

if ($q !== '') {
  $sql .= " AND (t.ref LIKE ? OR t.type LIKE ? OR t.narration LIKE ?)";
  $types .= "sss";
  $like = "%{$q}%";
  $params[] = $like;
  $params[] = $like;
  $params[] = $like;
}

$sql .= " ORDER BY e.id DESC LIMIT 250";

/* ===============================
   EXECUTE
================================ */
$st = $conn->prepare($sql);
$st->bind_param($types, ...$params);
$st->execute();
$res = $st->get_result();

$rows = [];
$creditTotal = 0;
$debitTotal  = 0;
$chart = [];

while ($r = $res->fetch_assoc()) {
  $rows[] = $r;

  if ($r['direction'] === 'credit') {
    $creditTotal += (float)$r['amount'];
  } else {
    $debitTotal += (float)$r['amount'];
  }

  $day = substr($r['created_at'], 0, 10);
  if (!isset($chart[$day])) {
    $chart[$day] = ['credit'=>0,'debit'=>0];
  }
  $chart[$day][$r['direction']] += (float)$r['amount'];
}

$labels = array_keys(array_reverse($chart, true));
$creditSeries = array_column(array_reverse($chart, true), 'credit');
$debitSeries  = array_column(array_reverse($chart, true), 'debit');

$title = 'Transactions';
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">

<!-- HEADER -->
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h3 class="fw-bold mb-0">Transactions</h3>
    <div class="ab-muted">
      Current Balance:
      <b><?= e($accounts[0]['currency']) ?> <?= money($currentBalance) ?></b>
    </div>
  </div>

  <div class="d-flex gap-2">
    <a class="btn btn-sm btn-outline-secondary" href="dashboard.php">
      <i class="bi bi-speedometer2 me-1"></i>Dashboard
    </a>
  </div>
</div>

<!-- FILTERS -->
<div class="card ab-card p-3 mb-3">
  <form class="row g-2 align-items-end">
    <div class="col-md-4">
      <label class="form-label">Account</label>
      <select class="form-select" name="account_id" onchange="this.form.submit()">
        <?php foreach ($accounts as $a): ?>
          <option value="<?= (int)$a['id'] ?>" <?= (int)$a['id']===$accountId?'selected':'' ?>>
            <?= e($a['account_type']) ?> • <?= e($a['account_no']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="col-md-4">
      <label class="form-label">Search</label>
      <input class="form-control" name="q" value="<?= e($q) ?>" placeholder="Ref / Narration">
    </div>

    <div class="col-md-3">
      <label class="form-label">Direction</label>
      <select class="form-select" name="direction">
        <option value="">All</option>
        <option value="credit" <?= $direction==='credit'?'selected':'' ?>>Credit</option>
        <option value="debit" <?= $direction==='debit'?'selected':'' ?>>Debit</option>
      </select>
    </div>

    <div class="col-md-1">
      <button class="btn ab-btn text-white w-100">Go</button>
    </div>
  </form>
</div>

<!-- CHART -->
<div class="card ab-card p-3 mb-3">
  <canvas id="txnChart" height="90"></canvas>
</div>

<!-- TABLE -->
<div class="card ab-card p-3">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead>
        <tr>
          <th>Date</th>
          <th>Ref</th>
          <th>Type</th>
          <th>Narration</th>
          <th>Direction</th>
          <th class="text-end">Amount</th>
          <th class="text-end">Balance</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php if (!$rows): ?>
          <tr>
            <td colspan="8" class="text-center ab-muted py-4">
              No transactions.
            </td>
          </tr>
        <?php endif; ?>

        <?php foreach ($rows as $r): ?>
        <tr>
          <td><?= e($r['created_at']) ?></td>
          <td class="fw-semibold"><?= e($r['ref']) ?></td>
          <td><?= e($r['type']) ?></td>
          <td class="ab-muted"><?= e($r['narration'] ?? '-') ?></td>
          <td>
            <span class="badge bg-<?= $r['direction']==='credit'?'success':'danger' ?>">
              <?= strtoupper($r['direction']) ?>
            </span>
          </td>
          <td class="text-end">
            <?= e($r['currency']) ?> <?= money((float)$r['amount']) ?>
          </td>
          <td class="text-end fw-semibold">
            <?= e($r['currency']) ?> <?= money((float)$r['balance_after']) ?>
          </td>
          <td class="text-end">
            <button
              class="btn btn-sm btn-outline-primary"
              onclick='showReceipt(<?= json_encode($r) ?>)'>
              Receipt
            </button>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

</div>

<!-- RECEIPT MODAL -->
<div class="modal fade" id="receiptModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content ab-card p-3">
      <h5 class="fw-bold mb-2">Transaction Receipt</h5>
      <div id="receiptBody"></div>
      <button class="btn btn-outline-secondary mt-3" data-bs-dismiss="modal">
        Close
      </button>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
new Chart(document.getElementById('txnChart'), {
  type: 'line',
  data: {
    labels: <?= json_encode($labels) ?>,
    datasets: [
      { label:'Credit', data: <?= json_encode($creditSeries) ?>, borderColor:'green', tension:.3 },
      { label:'Debit',  data: <?= json_encode($debitSeries) ?>,  borderColor:'red',   tension:.3 }
    ]
  }
});

function showReceipt(r){
  document.getElementById('receiptBody').innerHTML = `
    <div><b>Ref:</b> ${r.ref}</div>
    <div><b>Type:</b> ${r.type}</div>
    <div><b>Status:</b> ${r.status}</div>
    <div><b>Date:</b> ${r.created_at}</div>
    <div><b>Direction:</b> ${r.direction}</div>
    <div><b>Amount:</b> ${r.currency} ${r.amount}</div>
    <div><b>Balance:</b> ${r.currency} ${r.balance_after}</div>
    <div><b>Narration:</b> ${r.narration ?? '-'}</div>
  `;
  new bootstrap.Modal(document.getElementById('receiptModal')).show();
}
</script>

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