<?php
header('Content-Type: application/json');
require_once __DIR__ . '/db.php';
session_start();

if (!isset($_SESSION['user_id'])) {
  echo json_encode(['success' => false, 'error' => 'Not authenticated']);
  exit;
}

try {
  $pdo = getDB();
  $input = json_decode(file_get_contents('php://input'), true) ?: [];
  $amount = isset($input['amount']) ? floatval($input['amount']) : 0;
  $term = isset($input['term_months']) ? intval($input['term_months']) : 0;
  $rate = isset($input['rate_apr']) ? floatval($input['rate_apr']) : 6.90;
  $purpose = isset($input['purpose']) ? trim($input['purpose']) : null;

  if ($amount <= 0 || $term <= 0) {
    echo json_encode(['success' => false, 'error' => 'Invalid amount or term']);
    exit;
  }

  $stmt = $pdo->prepare("INSERT INTO loans (user_id, amount, term_months, rate_apr, purpose, balance_outstanding, status) VALUES (:uid, :amount, :term, :rate, :purpose, :balance, 'pending')");
  $stmt->execute([
    ':uid' => $_SESSION['user_id'],
    ':amount' => $amount,
    ':term' => $term,
    ':rate' => $rate,
    ':purpose' => $purpose,
    ':balance' => $amount,
  ]);

  echo json_encode(['success' => true, 'message' => 'Loan application submitted', 'id' => $pdo->lastInsertId()]);
} catch (Throwable $e) {
  echo json_encode(['success' => false, 'error' => 'Server error']);
}
