<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();

$conn = require __DIR__ . '/../../app/config/database.php';
require_admin($conn);

$admin = current_user();

/* Default currency (until loans become multi-currency) */
$currency = 'GHS';

/* ===============================
   APPROVE / REJECT LOAN
================================ */
if (is_post()) {
  csrf_verify();

  $id     = (int)($_POST['id'] ?? 0);
  $action = $_POST['action'] ?? '';
  $note   = trim($_POST['note'] ?? '');

  $conn->begin_transaction();
  try {
    $st = $conn->prepare("SELECT * FROM loans WHERE id=? FOR UPDATE");
    $st->bind_param("i", $id);
    $st->execute();
    $loan = $st->get_result()->fetch_assoc();

    if (!$loan) throw new Exception('Loan not found');
    if ($loan['status'] !== 'pending') throw new Exception('Already processed');

    if ($action === 'reject') {
      $st = $conn->prepare("
        UPDATE loans
        SET status='rejected', note=?, approved_by=?, approved_at=NOW()
        WHERE id=?
      ");
      $st->bind_param("sii", $note, $admin['id'], $id);
      $st->execute();

      flash('msg','Loan rejected.');
    }

    if ($action === 'approve') {
      $st = $conn->prepare("
        UPDATE loans
        SET status='active', note=?, approved_by=?, approved_at=NOW()
        WHERE id=?
      ");
      $st->bind_param("sii", $note, $admin['id'], $id);
      $st->execute();

      /* Notify customer */
      $msg = "Your loan request has been approved. Loan ID: #{$id}.";
      $n = $conn->prepare("
        INSERT INTO notifications (user_id, title, message)
        VALUES (?, 'Loan Approved', ?)
      ");
      $n->bind_param("is", $loan['user_id'], $msg);
      $n->execute();

      flash('msg','Loan approved.');
    }

    /* Audit */
    $meta = json_encode(['loan_id'=>$id,'action'=>$action]);
    $ip   = client_ip();
    $a = $conn->prepare("
      INSERT INTO audit_logs (actor_id, action, meta, ip)
      VALUES (?, 'LOAN_REVIEW', ?, ?)
    ");
    $a->bind_param("iss", $admin['id'], $meta, $ip);
    $a->execute();

    $conn->commit();

  } catch (Throwable $e) {
    $conn->rollback();
    flash('err', $e->getMessage());
  }

  redirect('loan_approvals.php');
}

/* ===============================
   LOAD PENDING LOANS
================================ */
$rows = [];
$res = $conn->query("
  SELECT l.*, u.full_name, u.email
  FROM loans l
  JOIN users u ON u.id = l.user_id
  WHERE l.status = 'pending'
  ORDER BY l.id DESC
  LIMIT 200
");
while ($r = $res->fetch_assoc()) $rows[] = $r;

$title = 'Loan Approvals — Admin';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';
?>

<div class="container-fluid py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="fw-bold mb-0">Loan Approvals</h3>
    <a class="btn btn-sm btn-outline-secondary" href="dashboard.php">Back</a>
  </div>

  <?php if ($m=flash('msg')): ?><div class="alert alert-success"><?= e($m) ?></div><?php endif; ?>
  <?php if ($m=flash('err')): ?><div class="alert alert-danger"><?= e($m) ?></div><?php endif; ?>

  <div class="card ab-card p-3">
    <div class="table-responsive">
      <table class="table align-middle mb-0">
        <thead>
          <tr>
            <th>ID</th>
            <th>Customer</th>
            <th>Amount</th>
            <th>Interest %</th>
            <th>Term</th>
            <th>Date</th>
            <th class="text-end">Action</th>
          </tr>
        </thead>
        <tbody>

        <?php foreach ($rows as $r): ?>
          <tr>
            <td>#<?= (int)$r['id'] ?></td>

            <td>
              <div class="fw-semibold"><?= e($r['full_name']) ?></div>
              <div class="text-muted small"><?= e($r['email']) ?></div>
            </td>

            <td><?= e($currency) ?> <?= number_format((float)$r['amount'], 2) ?></td>

            <td><?= number_format((float)$r['interest_rate'], 2) ?>%</td>

            <td><?= (int)$r['term_months'] ?> mo</td>

            <td><?= e($r['created_at']) ?></td>

            <td class="text-end">
              <a class="btn btn-sm btn-outline-dark" href="loan_view.php?id=<?= (int)$r['id'] ?>">View</a>

              <form method="post" class="d-inline">
                <?= csrf_field() ?>
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <button class="btn btn-sm btn-success" name="action" value="approve">Approve</button>
              </form>

              <form method="post" class="d-inline">
                <?= csrf_field() ?>
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <input type="text" name="note"
                       class="form-control form-control-sm d-inline-block"
                       style="width:160px"
                       placeholder="Reason (optional)">
                <button class="btn btn-sm btn-outline-danger" name="action" value="reject">Reject</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>

        <?php if (!$rows): ?>
          <tr>
            <td colspan="7" class="text-center text-muted py-4">
              No pending loan requests.
            </td>
          </tr>
        <?php endif; ?>

        </tbody>
      </table>
    </div>
  </div>
</div>

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