<div class="card p-3">
  <div class="d-flex justify-content-between">
    <h5>Loan Details — <?= esc($loan['loan_uid']) ?></h5>
    <div>
      <?php if($loan['status'] == 'pending'): ?>
        <form method="post" action="/admin/loans/approve/<?= $loan['id'] ?>" class="d-inline">
          <?= csrf_field() ?>
          <button class="btn btn-sm btn-success">Approve</button>
        </form>
      <?php endif; ?>
      <?php if($loan['status'] != 'disbursed'): ?>
        <form method="post" action="/admin/loans/disburse/<?= $loan['id'] ?>" class="d-inline">
          <?= csrf_field() ?>
          <button class="btn btn-sm btn-primary">Disburse</button>
        </form>
      <?php endif; ?>
      <?php if($loan['status'] != 'closed'): ?>
        <form method="post" action="/admin/loans/close/<?= $loan['id'] ?>" class="d-inline">
          <?= csrf_field() ?>
          <button class="btn btn-sm btn-outline-danger">Close</button>
        </form>
      <?php endif; ?>
    </div>
  </div>

  <hr>
  <div class="row">
    <div class="col-md-6">
      <h6>Borrower</h6>
      <p><strong><?= esc($loan['user_name']) ?></strong><br><?= esc($loan['email'] ?? '') ?></p>
      <h6>Loan Info</h6>
      <p>Product: <?= esc($loan['product_name']) ?><br>
      Amount: ₹ <?= esc(number_format($loan['amount'],2)) ?><br>
      Term: <?= esc($loan['term']) ?><br>
      Interest: <?= esc(number_format($loan['interest_rate'],2)) ?>%</p>
    </div>
    <div class="col-md-6">
      <h6>EMI / Schedule</h6>
      <table class="table table-sm">
        <thead><tr><th>Due Date</th><th>Amount</th><th>Status</th></tr></thead>
        <tbody>
          <?php foreach($payments as $p): ?>
            <tr>
              <td><?= esc($p['due_date']) ?></td>
              <td>₹ <?= esc(number_format($p['amount'],2)) ?></td>
              <td><?= esc($p['status']) ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

  <hr>
  <h6>Documents</h6>
  <div class="row g-2">
    <?php
      $db = \\Config\\Database::connect();
      $docs = $db->table('documents')->where('loan_id', $loan['id'])->get()->getResultArray();
    ?>
    <?php if(empty($docs)): ?>
      <div class="col-12 small-muted">No documents uploaded.</div>
    <?php else: foreach($docs as $d): ?>
      <div class="col-4">
        <div class="card card-compact p-2">
          <div class="small-muted"><?= esc($d['original_name']) ?></div>
          <a href="/uploads/docs/<?= esc($d['filename']) ?>" target="_blank" class="btn btn-sm btn-outline-primary mt-2">View</a>
        </div>
      </div>
    <?php endforeach; endif; ?>
  </div>
</div>