<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
requireUserLogin();
$currentUser = currentUser($pdo);
$uid = (int)$_SESSION['user_id'];
$error = ''; $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $amount  = (float)$_POST['loan_amount'] ?? 0;
    $type    = $_POST['loan_type'] ?? 'personal';
    $term    = (int)($_POST['loan_term'] ?? 12);
    $purpose = trim($_POST['loan_purpose'] ?? '');
    $colat   = trim($_POST['collateral'] ?? '');

    if ($amount <= 0 || $term <= 0) { $error = 'Please enter valid amount and term.'; goto done; }
    $rates = ['personal'=>12,'business'=>9,'mortgage'=>5,'auto'=>8,'student'=>6];
    $rate  = $rates[$type] ?? 12;
    $monthly = round(($amount * ($rate/100/12)) / (1 - pow(1+($rate/100/12),-$term)), 2);
    $totalPayable = round($monthly * $term, 2);
    $ref = generateRef('LOAN');
    $pdo->prepare("INSERT INTO loans (user_id,reference_number,loan_type,loan_amount,interest_rate,loan_term,monthly_payment,total_payable,outstanding,loan_purpose,collateral,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,'pending')")->execute([$uid,$ref,$type,$amount,$rate,$term,$monthly,$totalPayable,$totalPayable,$purpose,$colat]);
    addNotification($pdo,$uid,'Loan Application Submitted',"Your $type loan application of ".money($amount,$currentUser['currency'])." (Ref: $ref) has been submitted.",'info');
    $success = "Loan application submitted! Reference: <strong>$ref</strong>. Monthly payment: <strong>".money($monthly,$currentUser['currency'])."</strong>.";
}
done:

$loans = $pdo->prepare("SELECT * FROM loans WHERE user_id=? ORDER BY created_at DESC");
$loans->execute([$uid]); $loanList = $loans->fetchAll();
$pageTitle = 'Loans';
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?> | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body>
<?php include 'includes/header.php'; ?>
<div class="page-wrapper"><div class="container">
<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="page-title mb-0"><i class="fa fa-hand-holding-usd me-2 text-danger"></i>Loans</div>
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#applyModal"><i class="fa fa-plus me-1"></i>Apply</button>
</div>
<?php if ($error): ?><div class="alert alert-danger"><?= sanitize($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= $success ?></div><?php endif; ?>

<!-- Loan Products -->
<div class="row g-3 mb-4">
  <?php $products=[['Personal Loan','12%','Up to $50,000','personal'],['Business Loan','9%','Up to $500,000','business'],['Mortgage','5%','Up to $2,000,000','mortgage'],['Auto Loan','8%','Up to $100,000','auto'],['Student Loan','6%','Up to $80,000','student']];
  foreach ($products as [$name,$rate,$limit,$type]): ?>
  <div class="col-6 col-md-4 col-lg" >
    <div class="card text-center p-3 h-100">
      <div class="feature-icon-box mx-auto"><i class="fa fa-building"></i></div>
      <h6 class="fw-bold"><?= $name ?></h6>
      <div class="text-danger fw-bold fs-5"><?= $rate ?> APR</div>
      <div class="text-muted small"><?= $limit ?></div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<div class="card">
  <div class="card-header">My Loan Applications</div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead><tr><th>Reference</th><th>Type</th><th>Amount</th><th>Rate</th><th>Term</th><th>Monthly</th><th>Outstanding</th><th>Status</th></tr></thead>
      <tbody>
      <?php if (empty($loanList)): ?>
      <tr><td colspan="8" class="text-center py-4 text-muted">No loan applications.</td></tr>
      <?php else: foreach ($loanList as $l): ?>
      <tr>
        <td><code class="small"><?= sanitize($l['reference_number']) ?></code></td>
        <td><?= ucfirst($l['loan_type']) ?></td>
        <td><?= money((float)$l['loan_amount'],$currentUser['currency']) ?></td>
        <td><?= $l['interest_rate'] ?>%</td>
        <td><?= $l['loan_term'] ?> mo</td>
        <td><?= money((float)$l['monthly_payment'],$currentUser['currency']) ?></td>
        <td><?= money((float)$l['outstanding'],$currentUser['currency']) ?></td>
        <td><?= statusBadge($l['status']) ?></td>
      </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>
</div></div>
<?php include 'includes/footer.php'; ?>
<!-- Apply Modal -->
<div class="modal fade" id="applyModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">Apply for a Loan</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?>
    <div class="row g-3">
      <div class="col-12"><label class="form-label">Loan Type</label>
        <select name="loan_type" class="form-select">
          <option value="personal">Personal</option><option value="business">Business</option>
          <option value="mortgage">Mortgage</option><option value="auto">Auto</option><option value="student">Student</option>
        </select>
      </div>
      <div class="col-md-6"><label class="form-label">Amount (<?= $currentUser['currency'] ?>)</label><div class="input-group"><span class="input-group-text">$</span><input type="number" name="loan_amount" class="form-control" step="100" min="500" required></div></div>
      <div class="col-md-6"><label class="form-label">Term (months)</label><input type="number" name="loan_term" class="form-control" min="3" max="360" value="12" required></div>
      <div class="col-12"><label class="form-label">Purpose</label><textarea name="loan_purpose" class="form-control" rows="2"></textarea></div>
      <div class="col-12"><label class="form-label">Collateral (if any)</label><textarea name="collateral" class="form-control" rows="2"></textarea></div>
    </div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary">Submit Application</button></div>
  </form>
</div></div></div>
</body></html>
