<?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 loan currency */
$currency = 'GHS';

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

/* ===============================
   LOAD LOAN
================================ */
$st = $conn->prepare("
  SELECT l.*, u.full_name, u.email
  FROM loans l
  JOIN users u ON u.id = l.user_id
  WHERE l.id = ?
");
$st->bind_param("i", $id);
$st->execute();
$loan = $st->get_result()->fetch_assoc();
if (!$loan) die('Loan not found');

/* ===============================
   POST REPAYMENT
================================ */
if (is_post()) {
  csrf_verify();

  $amt = (float)($_POST['amount'] ?? 0);
  if ($amt <= 0) {
    flash('err','Invalid amount');
    redirect("loan_view.php?id=$id");
  }

  $st = $conn->prepare("
    INSERT INTO loan_repayments (loan_id, amount, posted_by, created_at)
    VALUES (?, ?, ?, NOW())
  ");
  $st->bind_param("idi", $id, $amt, $admin['id']);
  $st->execute();

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

  flash('msg','Repayment posted successfully');
  redirect("loan_view.php?id=$id");
}

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

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

$title = 'Loan View — 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 #<?= (int)$loan['id'] ?></h3>
    <a class="btn btn-sm btn-outline-secondary" href="loan_approvals.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="row g-3">

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

        <div class="fw-bold mb-2">Customer</div>
        <div class="fw-semibold"><?= e($loan['full_name']) ?></div>
        <div class="text-muted small"><?= e($loan['email']) ?></div>

        <hr>

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

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

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

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

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

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

      </div>
    </div>

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

        <div class="fw-bold mb-2">Post Repayment</div>
        <form method="post">
          <?= csrf_field() ?>
          <div class="row g-2">
            <div class="col-md-8">
              <input class="form-control" name="amount" type="number" step="0.01" placeholder="Amount">
            </div>
            <div class="col-md-4">
              <button class="btn ab-btn text-white w-100">Post</button>
            </div>
          </div>
        </form>

        <hr>

        <div class="fw-bold mb-2">Repayment History</div>
        <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'], 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>
    </div>

  </div>
</div>

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