<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $action = $_POST['action'] ?? '';
    $lid    = (int)$_POST['loan_id'];
    if ($action === 'approve') {
        $loan = $pdo->prepare("SELECT * FROM loans WHERE id=? LIMIT 1"); $loan->execute([$lid]); $l=$loan->fetch();
        if ($l) {
            $pdo->prepare("UPDATE loans SET status='approved',approved_at=NOW(),disbursed_at=NOW() WHERE id=?")->execute([$lid]);
            creditAccount($pdo,(int)$l['user_id'],(float)$l['loan_amount'],'Loan Disbursement - '.$l['loan_type'].' (Ref:'.$l['reference_number'].')','LDIS-'.$l['reference_number']);
            addNotification($pdo,(int)$l['user_id'],'Loan Approved','Your loan of '.money((float)$l['loan_amount']).' has been approved and disbursed to your account.','success');
            flash('success','Loan approved and disbursed.');
        }
    }
    if ($action === 'reject') {
        $pdo->prepare("UPDATE loans SET status='rejected' WHERE id=?")->execute([$lid]);
        $loan=$pdo->prepare("SELECT user_id FROM loans WHERE id=? LIMIT 1");$loan->execute([$lid]);$l=$loan->fetch();
        if ($l) addNotification($pdo,(int)$l['user_id'],'Loan Rejected','Your loan application has been rejected. Contact support for details.','danger');
        flash('success','Loan rejected.');
    }
    if ($action === 'mark_paid') {
        $pdo->prepare("UPDATE loans SET status='paid',outstanding=0 WHERE id=?")->execute([$lid]);
        flash('success','Loan marked as paid.');
    }
    header('Location: /admin/loans.php'); exit;
}

$sf = $_GET['status'] ?? 'pending';
$loans = $pdo->prepare("SELECT l.*, CONCAT(u.first_name,' ',u.last_name) AS user_name, u.email AS user_email FROM loans l JOIN users u ON l.user_id=u.id WHERE l.status=? ORDER BY l.created_at DESC");
$loans->execute([$sf]); $loanList=$loans->fetchAll();
$pageTitle = 'Loan Management';
?>
<?php include '../includes/header.php'; ?>
<div class="page-title"><i class="fa fa-hand-holding-usd me-2 text-danger"></i>Loan Management</div>
<ul class="nav nav-tabs mb-4">
  <?php foreach (['pending','approved','rejected','paid'] as $s): ?>
  <li class="nav-item"><a class="nav-link <?= $sf===$s?'active':'' ?>" href="?status=<?= $s ?>"><?= ucfirst($s) ?></a></li>
  <?php endforeach; ?>
</ul>
<div class="card">
  <div class="table-responsive">
    <table class="table table-hover mb-0 small">
      <thead><tr><th>User</th><th>Ref</th><th>Type</th><th>Amount</th><th>Rate</th><th>Term</th><th>Monthly</th><th>Outstanding</th><th>Date</th><th>Actions</th></tr></thead>
      <tbody>
      <?php if (empty($loanList)): ?><tr><td colspan="10" class="text-center py-4 text-muted">No <?= $sf ?> loans.</td></tr>
      <?php else: foreach ($loanList as $l): ?>
      <tr>
        <td><div class="fw-bold"><?= sanitize($l['user_name']) ?></div><div class="text-muted" style="font-size:.75rem"><?= sanitize($l['user_email']) ?></div></td>
        <td><code><?= sanitize($l['reference_number']) ?></code></td>
        <td><?= ucfirst($l['loan_type']) ?></td>
        <td class="fw-bold"><?= money((float)$l['loan_amount']) ?></td>
        <td><?= $l['interest_rate'] ?>%</td>
        <td><?= $l['loan_term'] ?> mo</td>
        <td><?= money((float)$l['monthly_payment']) ?></td>
        <td><?= money((float)$l['outstanding']) ?></td>
        <td><?= formatDate($l['created_at'],'M j, Y') ?></td>
        <td>
          <?php if ($l['status']==='pending'): ?>
          <form method="POST" class="d-flex gap-1">
            <?= csrf_field() ?><input type="hidden" name="loan_id" value="<?= $l['id'] ?>">
            <button name="action" value="approve" class="btn btn-xs btn-success" data-confirm="Approve and disburse this loan?"><i class="fa fa-check"></i> Approve</button>
            <button name="action" value="reject" class="btn btn-xs btn-danger"><i class="fa fa-times"></i> Reject</button>
          </form>
          <?php elseif ($l['status']==='approved'): ?>
          <form method="POST">
            <?= csrf_field() ?><input type="hidden" name="loan_id" value="<?= $l['id'] ?>">
            <button name="action" value="mark_paid" class="btn btn-xs btn-outline-success">Mark Paid</button>
          </form>
          <?php else: ?>
          <span class="text-muted small"><?= ucfirst($l['status']) ?></span>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include '../includes/footer.php'; ?>
