<?php
/**
 * Pure algorithmic loan recommendation engine (no DB calls)
 * @param array $user_data Contains: savings, balance, loan_history
 * @return float Recommended loan amount
 */
function calculateLoanRecommendation(array $user_data): float {
    // Extract inputs
    $saving = $user_data['saving'] ?? 0;
    $balance = $user_data['balance'] ?? 0;
    $loans = $user_data['loan_history'] ?? [];

    // --- Algorithm Core ---
    // 1. Base case: No loan history → 50% savings or 30% balance (whichever is smaller)
    if (empty($loans)) {
        return round(min($saving * 0.5, $balance * 0.3), 2);
    }

    // 2. Calculate repayment behavior score (0-10)
    $total_loans = count($loans);
    $timely_payments = 0;
    $defaulted_loans = 0;
    $late_payments = 0;

    foreach ($loans as $loan) {
        switch ($loan['status']) {
            case 'Paid': $timely_payments++; break;
            case 'Default': $defaulted_loans++; break;
            case 'Delayed': $late_payments++; break;
        }
    }

    $timeliness_score = 10 * ($timely_payments / $total_loans);
    $default_penalty = 10 * (1 - exp(-3 * $defaulted_loans / $total_loans));
    $late_penalty = 5 * ($late_payments / $total_loans);
    $repayment_score = max(0, $timeliness_score - $default_penalty - $late_penalty);

    // 3. Financial health score (0-10)
    $savings_ratio = ($balance > 0) ? $saving / $balance : 0;
    $financial_score = min(10, $savings_ratio * (10 / 1.5));

    // 4. Risk adjustment for recent defaults (last 12 months)
    $recent_defaults = 0;
    $recent_loans = 0;
    $current_time = time();

    foreach ($loans as $loan) {
        if (strtotime($loan['end_date']) > ($current_time - 31536000)) { // 1 year ago
            $recent_loans++;
            if ($loan['status'] === 'Default') $recent_defaults++;
        }
    }

    $recent_risk_penalty = ($recent_loans > 0) 
        ? 10 * (1 - exp(-5 * ($recent_defaults / $recent_loans)))
        : 0;
    $risk_score = max(0, 10 - $recent_risk_penalty);

    // 5. Composite score (weighted average)
    $composite_score = (
        0.35 * $repayment_score + 
        0.25 * $financial_score + 
        0.15 * $risk_score
    );

    // 6. Loan amount calculation
    $avg_loan = array_sum(array_column($loans, 'amount')) / $total_loans;
    $max_base = max(
        $saving * 1.2,
        $balance * 0.8,
        $avg_loan * 3
    );

    return round($max_base * ($composite_score / 10), 2);
}

// --- Example Usage ---
$user_data = [
    'saving' => 50000,
    'balance' => 30000,
    'loan_history' => [
        [
            'amount' => 20000,
            'status' => 'Paid',
            'end_date' => '2023-01-15'
        ],
        [
            'amount' => 15000,
            'status' => 'Default',
            'end_date' => '2024-03-10'
        ]
    ]
];

$recommended_loan = calculateLoanRecommendation($user_data);
echo "Recommended Loan: Rs. " . number_format($recommended_loan, 2);
?>