<?php

namespace App\Support;

class LoanCalculator
{
    /**
     * Parse net income safely and return numeric value as string.
     */
    public static function parseNetIncome(string $netIncome): string
    {
        $incomeClean = str_replace(['$', ','], '', $netIncome);

        if (str_contains($incomeClean, '-')) {
            $parts = array_map('trim', explode('-', $incomeClean));
            $incomeValue = $parts[1]; // upper bound
        } elseif (str_ends_with($incomeClean, '+')) {
            $incomeValue = rtrim($incomeClean, '+');
        } else {
            $incomeValue = $incomeClean;
        }

        return is_numeric($incomeValue) ? (string) $incomeValue : '0';
    }

    /**
     * Calculate total interest (simple interest) as string
     */
    public static function calculateInterest(string $amount, string $rate, string $duration): string
    {
        return bcmul(bcmul($amount, $rate, 4), $duration, 2);
    }

    /**
     * Calculate monthly repayment as string
     */
    public static function monthlyRepayment(string $amount, string $totalInterest, string $duration): string
    {
        $totalRepayment = bcadd($amount, $totalInterest, 2);
        return bcdiv($totalRepayment, $duration, 2);
    }

    /**
     * Maximum loan allowed based on net income as string
     */
    public static function maxLoan(string $netIncome): string
    {
        $multiplier = (string) config('loan.max_income_multiplier', '5');
        return bcmul($netIncome, $multiplier, 2);
    }
}
