<?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';
$u = current_user();
$userId = (int)$u['id'];

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

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

<main style="margin-left:240px">
<div class="container-fluid py-4">

  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h3 class="fw-bold mb-0">Savings</h3>
      <div class="ab-muted">Your protected savings accounts</div>
    </div>
    <a href="accounts.php" class="btn btn-sm btn-outline-secondary">
      All Accounts
    </a>
  </div>

  <div class="row g-4">
    <?php foreach ($savings as $s): ?>
      <div class="col-md-6 col-lg-4">
        <div class="card ab-card p-4 h-100">

          <div class="d-flex justify-content-between align-items-center mb-2">
            <span class="badge bg-primary">SAVINGS</span>
            <?php if (!empty($s['is_primary'])): ?>
              <span class="badge bg-success">PRIMARY</span>
            <?php endif; ?>
          </div>

          <div class="fw-bold fs-5 mb-1">
            <?= money($s['balance']) ?> <?= e($s['currency']) ?>
          </div>

          <div class="ab-muted small mb-3">
            Account No: <?= e($s['account_no']) ?>
          </div>

          <div class="small text-muted mb-3">
            <div>Daily limit: <?= isset($s['daily_limit']) ? money($s['daily_limit']) : '—' ?></div>
            <div>Monthly limit: <?= isset($s['monthly_limit']) ? money($s['monthly_limit']) : '—' ?></div>
          </div>

          <a href="transactions.php?account_id=<?= (int)$s['id'] ?>"
             class="btn btn-sm btn-outline-primary w-100">
            View Transactions
          </a>

        </div>
      </div>
    <?php endforeach; ?>

    <?php if (!$savings): ?>
      <div class="col-12">
        <div class="alert alert-info">
          You don’t have a savings account yet.  
          Please contact support or admin.
        </div>
      </div>
    <?php endif; ?>
  </div>

</div>
</main>

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