<?php
error_reporting(-1);
$monthly = 5000;
$percents = [1.04,1.03,1.02];
$comission = [500, 1000, 0];
$firstPay = 7777;
$balance=39999;
function credit($balance, $monthly, $percents, $comission, $firstPay){
	$totalPayed=$firstPay;
	$balance+=$firstPay;
	echo "$balance $totalPayed $percents $comission $monthly \n";
	for($i=1;$i<=20;$i++){
		$balance=($balance*$percents)+$comission-$monthly;
		$totalPayed=$totalPayed + $monthly;
		echo "$balance $totalPayed \n";
		if ($balance<=0){
			$absBalance=abs($balance);
			$totalPayed-=$absBalance;
			$balance+=$absBalance;
			echo "Enough! Total payed: {$totalPayed} current balance: {$balance} $i \n";
			break;
		}
	
	}
	return $totalPayed;
}
$totalPayed1=credit($balance, $monthly, $percents[0], $comission[0], 0);
$totalPayed2=credit($balance, $monthly, $percents[1], $comission[1], 0);
$totalPayed3=credit($balance, $monthly, $percents[2], $comission[2], $firstPay);
echo "first: $totalPayed1 second: $totalPayed2 third: $totalPayed3 \n";
?>