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

$id = (int)($_GET['id'] ?? 0);
if (!$id) redirect('loans.php');

/* Default currency (since loans table has no currency column) */
$currency = 'GHS';

/* Load loan */
$st = $conn->prepare("
  SELECT *
  FROM loans
  WHERE id=? AND user_id=?
");
$st->bind_param("ii", $id, $userId);
$st->execute();
$loan = $st->get_result()->fetch_assoc();
if (!$loan) die('Loan not found');

/* Repayments */
$rep = [];
$res = $conn->query("
  SELECT *
  FROM loan_repayments
  WHERE loan_id={$id}
  ORDER BY id DESC
");
while ($r = $res->fetch_assoc()) $rep[] = $r;

$paid = 0;
foreach ($rep as $r) $paid += (float)($r['amount'] ?? 0);
$outstanding = max(0, (float)($loan['amount'] ?? 0) - $paid);

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

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

<a href="loans.php" class="btn btn-sm btn-outline-secondary mb-3">
  ← Back to Loans
</a>

<div class="row g-4">

  <!-- LOAN SUMMARY -->
  <div class="col-lg-6">
    <div class="card ab-card p-4">

      <h5 class="fw-bold mb-3">Loan Overview</h5>

      <div class="row g-2">
        <div class="col-6 text-muted">Loan ID</div>
        <div class="col-6 fw-semibold">#<?= (int)($loan['id'] ?? 0) ?></div>

        <div class="col-6 text-muted">Amount</div>
        <div class="col-6 fw-semibold">
          <?= e($currency) ?> <?= number_format((float)($loan['amount'] ?? 0), 2) ?>
        </div>

        <div class="col-6 text-muted">Interest</div>
        <div class="col-6 fw-semibold">
          <?= number_format((float)($loan['interest_rate'] ?? 0), 2) ?>%
        </div>

        <div class="col-6 text-muted">Term</div>
        <div class="col-6 fw-semibold">
          <?= (int)($loan['term_months'] ?? 0) ?> months
        </div>

        <div class="col-6 text-muted">Status</div>
        <div class="col-6 fw-semibold text-uppercase">
          <?= e($loan['status'] ?? 'unknown') ?>
        </div>

        <div class="col-6 text-muted">Total Paid</div>
        <div class="col-6 fw-semibold text-success">
          <?= e($currency) ?> <?= number_format((float)$paid, 2) ?>
        </div>

        <div class="col-6 text-muted">Outstanding</div>
        <div class="col-6 fw-semibold text-danger">
          <?= e($currency) ?> <?= number_format((float)$outstanding, 2) ?>
        </div>
      </div>

      <?php
        $amt = (float)($loan['amount'] ?? 0);
        $pc = $amt > 0 ? min(100, round(($paid / $amt) * 100)) : 0;
      ?>
      <hr>
      <div class="ab-muted small mb-2">Repayment progress (<?= $pc ?>%)</div>
      <div class="progress" style="height:10px;border-radius:999px">
        <div class="progress-bar bg-success" style="width:<?= $pc ?>%"></div>
      </div>

    </div>
  </div>

  <!-- REPAYMENTS -->
  <div class="col-lg-6">
    <div class="card ab-card p-4">

      <h5 class="fw-bold mb-3">Repayment History</h5>

      <div class="table-responsive">
        <table class="table table-sm align-middle mb-0">
          <thead>
            <tr>
              <th>Amount</th>
              <th>Date</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rep as $r): ?>
              <tr>
                <td>
                  <?= e($currency) ?>
                  <?= number_format((float)($r['amount'] ?? 0), 2) ?>
                </td>
                <td><?= e($r['created_at'] ?? '-') ?></td>
              </tr>
            <?php endforeach; ?>

            <?php if (!$rep): ?>
              <tr>
                <td colspan="2" class="text-center text-muted py-3">
                  No repayments yet.
                </td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <div class="alert alert-light mt-3 small mb-0">
        💡 Repayments are posted by admin after confirmation. If you paid, allow processing time.
      </div>

    </div>
  </div>

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

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