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

/* Default currency (derive later if needed) */
$currency = 'GHS';

/* ===============================
   LOAD CUSTOMER LOANS
================================ */
$loans = [];
$st = $conn->prepare("
  SELECT *
  FROM loans
  WHERE user_id=?
  ORDER BY id DESC
");
$st->bind_param("i", $userId);
$st->execute();
$res = $st->get_result();
while ($r = $res->fetch_assoc()) {
  $loans[] = $r;
}

$title = 'My Loans';
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">
  <h3 class="fw-bold mb-0">Loans</h3>
  <a href="loan_apply.php" class="btn btn-sm ab-btn text-white">
    Apply for Loan
  </a>
</div>

<div class="row g-4">

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

      <!-- STATUS -->
      <div class="d-flex justify-content-between mb-2">
        <span class="badge bg-<?=
          $l['status']==='active'?'success':
          ($l['status']==='pending'?'warning':
          ($l['status']==='rejected'?'danger':'secondary'))
        ?>">
          <?= strtoupper(e($l['status'] ?? 'unknown')) ?>
        </span>
        <span class="text-muted small">
          #<?= (int)$l['id'] ?>
        </span>
      </div>

      <!-- AMOUNT -->
      <div class="fw-bold fs-5 mb-1">
        <?= e($currency) ?>
        <?= number_format((float)($l['amount'] ?? 0), 2) ?>
      </div>

      <!-- DETAILS -->
      <div class="ab-muted small mb-2">
        Interest:
        <?= number_format((float)($l['interest_rate'] ?? 0), 2) ?>%
        •
        <?= (int)($l['term_months'] ?? 0) ?> months
      </div>

      <div class="ab-muted small mb-3">
        Applied on <?= e($l['created_at'] ?? '-') ?>
      </div>

      <a
        href="loan_view.php?id=<?= (int)$l['id'] ?>"
        class="btn btn-sm btn-outline-primary w-100">
        View Loan
      </a>

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

<?php if (!$loans): ?>
  <div class="col-12">
    <div class="alert alert-info">
      You have not applied for any loans yet.
    </div>
  </div>
<?php endif; ?>

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

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