<?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';
$user = current_user();
$userId = (int)$user['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);
}

/* ===============================
   ENSURE PRIMARY ACCOUNT
================================ */
ensure_primary_account($conn, $userId);

/* ===============================
   ACTIONS
================================ */

/* SET PRIMARY */
if (is_post() && isset($_POST['make_primary'])) {
    $accId = (int)($_POST['account_id'] ?? 0);

    $st = $conn->prepare("SELECT id FROM accounts WHERE id=? AND user_id=?");
    $st->bind_param("ii", $accId, $userId);
    $st->execute();

    if ($st->get_result()->fetch_assoc()) {
        set_primary_account($conn, $userId, $accId);
        flash('msg','Primary account updated');
    } else {
        flash('msg','Invalid account');
    }
    redirect('accounts.php');
}

/* SAVE NICKNAME */
if (is_post() && isset($_POST['save_nickname'])) {
    $accId = (int)$_POST['account_id'];
    $nick  = trim($_POST['nickname']);

    $st = $conn->prepare("UPDATE accounts SET nickname=? WHERE id=? AND user_id=?");
    $st->bind_param("sii", $nick, $accId, $userId);
    $st->execute();

    flash('msg','Nickname saved');
    redirect('accounts.php');
}

/* ===============================
   LOAD ACCOUNTS
================================ */
$accounts = [];
$st = $conn->prepare("
    SELECT *
    FROM accounts
    WHERE user_id=?
    ORDER BY is_primary DESC, id DESC
");
$st->bind_param("i", $userId);
$st->execute();
$res = $st->get_result();
while ($r = $res->fetch_assoc()) {
    // 🔥 FORCE REAL BALANCE FROM LEDGER
    $r['balance'] = ledger_balance($conn, (int)$r['id']);
    $accounts[] = $r;
}

$title = 'My Accounts — Astrabank';
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">

<?php if ($m = flash('msg')): ?>
  <div class="alert alert-success"><?= e($m) ?></div>
<?php endif; ?>

<!-- HEADER -->
<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h3 class="fw-bold mb-1">My Accounts</h3>
    <div class="text-muted">
      Your primary account is used for cards, wire transfers and crypto.
    </div>
  </div>

  <div class="d-flex gap-2">
    <a href="internal_transfer.php" class="btn btn-outline-primary btn-sm">
      <i class="bi bi-arrow-left-right me-1"></i>Internal Transfer
    </a>
    <a href="account_analytics.php" class="btn btn-outline-secondary btn-sm">
      <i class="bi bi-graph-up me-1"></i>Analytics
    </a>
  </div>
</div>

<!-- ACCOUNTS GRID -->
<div class="row g-4">

<?php foreach ($accounts as $a): ?>
<div class="col-xl-4 col-lg-6">

  <div class="card ab-card h-100 shadow-sm border-0">

    <div class="card-body pb-2">

      <div class="d-flex justify-content-between mb-2">
        <span class="badge bg-primary text-uppercase">
          <?= e($a['account_type']) ?>
        </span>

        <?php if (!empty($a['is_primary'])): ?>
          <span class="badge bg-success">PRIMARY</span>
        <?php endif; ?>
      </div>

      <div class="mb-2">
        <div class="text-muted small">Account Number</div>
        <div class="fw-semibold"><?= e($a['account_no']) ?></div>
      </div>

      <div class="mb-3">
        <div class="text-muted small">Balance</div>
        <div class="fs-3 fw-bold text-success">
          <?= e($a['currency'] ?? 'GHS') ?>
          <?= number_format((float)$a['balance'], 2) ?>
        </div>
      </div>

      <div class="mb-3">
        <?php
          $status = $a['status'] ?? 'active';
          $badge = $status === 'frozen'
            ? 'danger'
            : ($status === 'limited' ? 'warning' : 'secondary');
        ?>
        <span class="badge bg-<?= $badge ?>">
          <?= strtoupper($status) ?>
        </span>
      </div>

      <!-- NICKNAME -->
      <form method="post" class="mb-2">
        <input type="hidden" name="account_id" value="<?= (int)$a['id'] ?>">
        <div class="input-group input-group-sm">
          <input
            name="nickname"
            class="form-control"
            placeholder="Account nickname"
            value="<?= e($a['nickname'] ?? '') ?>">
          <button class="btn btn-outline-secondary" name="save_nickname">
            Save
          </button>
        </div>
      </form>

    </div>

    <!-- ACTIONS -->
    <div class="card-footer bg-transparent border-0">
      <div class="d-flex gap-2">

        <a href="transactions.php?account_id=<?= (int)$a['id'] ?>"
           class="btn btn-outline-primary btn-sm w-100">
          <i class="bi bi-list-ul me-1"></i>Transactions
        </a>

        <?php if (empty($a['is_primary'])): ?>
        <form method="post" class="w-100">
          <input type="hidden" name="account_id" value="<?= (int)$a['id'] ?>">
          <button class="btn btn-outline-success btn-sm w-100"
                  name="make_primary">
            Make Primary
          </button>
        </form>
        <?php endif; ?>

      </div>
    </div>

  </div>

</div>
<?php endforeach; ?>

<?php if (!$accounts): ?>
<div class="col-12">
  <div class="alert alert-info text-center">
    No accounts found.
  </div>
</div>
<?php endif; ?>

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

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