<?php

namespace App\Services\Notifications;

use App\Models\Business;
use App\Models\Loan;
use App\Models\LoanInstallment;
use App\Models\NotificationTemplate;
use App\Services\MoneyMath;

class ReminderMessageRenderer
{
    public function __construct(private MoneyMath $money) {}

    /** @return array{subject:?string,message:string} */
    public function render(NotificationTemplate $template, Business $business, Loan $loan, LoanInstallment $installment, int $daysFromDue): array
    {
        $loan->loadMissing(['customer','branch']);
        $amount=$this->money->fromMinor($this->money->toMinor((string)$installment->remaining));
        $tokens=[
            '{customer_name}'=>$loan->customer->full_name,
            '{customer_number}'=>$loan->customer->customer_number,
            '{loan_number}'=>$loan->loan_number,
            '{installment_number}'=>(string)$installment->installment_number,
            '{amount_due}'=>trim($business->currency_symbol.' '.$amount),
            '{due_date}'=>$installment->due_date->format('d M Y'),
            '{days_overdue}'=>(string)max(0,$daysFromDue),
            '{business_name}'=>$business->name,
            '{branch_name}'=>$loan->branch->name,
        ];

        return [
            'subject'=>$template->subject !== null ? strtr($template->subject,$tokens) : null,
            'message'=>strtr($template->body,$tokens),
        ];
    }
}
