<?php
header('Content-Type: application/json');

require_once '../config/db.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

requireLogin();

$loan_id = intval($_GET['id'] ?? 0);

if (!$loan_id) {
    echo json_encode(['success' => false, 'message' => 'Loan ID required']);
    exit();
}

$loan = getLoanById($conn, $loan_id);
if (!$loan) {
    echo json_encode(['success' => false, 'message' => 'Loan not found']);
    exit();
}

$total_paid = getTotalPaidByLoan($conn, $loan_id);

echo json_encode([
    'success' => true,
    'loan' => [
        'id' => $loan['id'],
        'borrower_name' => $loan['first_name'] . ' ' . $loan['last_name'],
        'loan_amount' => $loan['loan_amount'],
        'total_payable' => $loan['total_payable'],
        'total_paid' => $total_paid,
        'balance' => $loan['balance'],
        'status' => $loan['status']
    ]
]);
?>
