<?php
if (!function_exists('generateLoanUID')) {
    function generateLoanUID($prefix = 'LM') {
        return $prefix . strtoupper(bin2hex(random_bytes(4))) . substr(time(), -5);
    }
}

if (!function_exists('calculateMonthlyEMI')) {
    function calculateMonthlyEMI($P, $annualRatePercent, $n) {
        $r = ($annualRatePercent / 100) / 12;
        if ($r <= 0) return round($P / max(1,$n),2);
        $emi = ($P * $r * pow(1+$r, $n)) / (pow(1+$r, $n) - 1);
        return round($emi,2);
    }
}

if (!function_exists('calculateInstallments')) {
    function calculateInstallments($P, $ratePercent, $term, $productSlug) {
        $inst = [];
        if ($productSlug == 'monthly') {
            $emi = calculateMonthlyEMI($P, $ratePercent, $term);
            $start = new DateTime();
            for ($i=1;$i<=$term;$i++){
                $d = clone $start;
                $d->modify("+{$i} month");
                $inst[] = ['due_date'=>$d->format('Y-m-d'),'amount'=>$emi];
            }
            return $inst;
        } elseif ($productSlug == 'weekly') {
            $weeklyRate = ($ratePercent/100) / 52;
            $weeklyAmount = round($P * (1 + $weeklyRate * $term) / $term,2);
            $start = new DateTime();
            for ($i=1;$i<=$term;$i++){
                $d = clone $start;
                $d->modify("+{$i} week");
                $inst[] = ['due_date'=>$d->format('Y-m-d'),'amount'=>$weeklyAmount];
            }
            return $inst;
        } else {
            $dailyRate = ($ratePercent/100) / 365;
            $dailyAmount = round($P * (1 + $dailyRate * $term) / $term,2);
            $start = new DateTime();
            for ($i=1;$i<=$term;$i++){
                $d = clone $start;
                $d->modify("+{$i} day");
                $inst[] = ['due_date'=>$d->format('Y-m-d'),'amount'=>$dailyAmount];
            }
            return $inst;
        }
    }
}
