<?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';
$u = current_user();
$userId = (int)$u['id'];

/* ===============================
   HANDLE APPLICATION
================================ */
if (is_post()) {
    csrf_verify();

    $amount = (float)($_POST['amount'] ?? 0);
    $term   = (int)($_POST['term_months'] ?? 0);

    if ($amount <= 0 || $term <= 0) {
        flash('err','Invalid loan details.');
        redirect('loan_apply.php');
    }

    // BANK RULES (adjust anytime)
    if ($amount < 100) {
        flash('err','Minimum loan amount is 100.');
        redirect('loan_apply.php');
    }

    if ($term > 60) {
        flash('err','Maximum loan term is 60 months.');
        redirect('loan_apply.php');
    }

    // Interest logic (admin-controlled)
    $interestRate = 5.0; // default 5%

    $st = $conn->prepare("
        INSERT INTO loans
            (user_id, amount, interest_rate, term_months, status, created_at)
        VALUES (?, ?, ?, ?, 'pending', NOW())
    ");
    $st->bind_param("iddi", $userId, $amount, $interestRate, $term);
    $st->execute();

    // Audit
    $meta = json_encode([
        'user_id' => $userId,
        'amount' => $amount,
        'term_months' => $term
    ]);
    $ip = client_ip();

    $a = $conn->prepare("
        INSERT INTO audit_logs (actor_id, action, meta, ip)
        VALUES (?, 'LOAN_APPLY', ?, ?)
    ");
    $a->bind_param("iss", $userId, $meta, $ip);
    $a->execute();

    flash('msg','Loan application submitted. Awaiting approval.');
    redirect('loans.php');
}

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

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

<h3 class="fw-bold mb-3">Apply for a Loan</h3>

<?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">
  <div class="col-lg-6">

    <div class="card ab-card p-4">

      <form method="post">
        <?= csrf_field() ?>

        <div class="mb-3">
          <label class="form-label">Loan Amount</label>
          <input
            type="number"
            name="amount"
            class="form-control"
            min="100"
            step="0.01"
            placeholder="Enter amount"
            required>
        </div>

        <div class="mb-3">
          <label class="form-label">Loan Term (Months)</label>
          <select name="term_months" class="form-select" required>
            <option value="">Select term</option>
            <option value="6">6 Months</option>
            <option value="12">12 Months</option>
            <option value="24">24 Months</option>
            <option value="36">36 Months</option>
            <option value="48">48 Months</option>
            <option value="60">60 Months</option>
          </select>
        </div>

        <div class="alert alert-info small">
          <b>Interest Rate:</b> 5% per annum  
          <br>
          Final rate may change after admin review.
        </div>

        <button class="btn ab-btn text-white w-100">
          Submit Application
        </button>

      </form>

    </div>

  </div>

  <!-- INFO -->
  <div class="col-lg-6">
    <div class="card ab-card p-4">
      <h6 class="fw-bold">How it works</h6>
      <ul class="small text-muted mb-0">
        <li>Submit loan application</li>
        <li>Admin reviews your request</li>
        <li>Approved loans are disbursed to your primary account</li>
        <li>Repayments are posted by admin</li>
      </ul>
    </div>
  </div>

</div>

</div>
</main>

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