<?php
namespace App\Notifications;

use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use App\Models\Loan;
use App\Models\LoanInstallment;

class LoanOverdueNotification extends Notification
{


    protected Loan $loan;
    protected LoanInstallment $installment;

    public function __construct(Loan $loan, LoanInstallment $installment)
    {
        $this->loan = $loan;
        $this->installment = $installment;
    }

    public function via($notifiable)
    {
        return ['mail', 'database'];
    }

    public function toMail($notifiable)
    {
        $daysOverdue = now()->diffInDays($this->installment->due_date, false);

        return (new MailMessage)
            ->subject('Loan Installment Overdue Notice')
            ->greeting("Dear {$notifiable->name},")
            ->line("Your loan installment #{$this->installment->installment_number} is now overdue by {$daysOverdue} day(s).")
            ->line("Due Date: {$this->installment->due_date->format('F d, Y')}")
            ->line("Original Amount Due: {$this->installment->principal} + {$this->installment->interest}")
            ->line("Penalty Applied: {$this->installment->penalty}")
            ->line("Total Outstanding for this Installment: {$this->installment->total}")
            ->line("Total Outstanding Loan Balance: {$this->loan->remaining_balance}")
            ->line('Please make payment immediately to avoid further penalties.')
            ->action('Make Payment', url('/loans/' . $this->loan->id))
            ->line('Thank you for banking with us. Prompt action helps you avoid additional fees.');
    }


    public function toArray($notifiable)
    {
        $daysOverdue = now()->diffInDays($this->installment->due_date, false);

        return [
            'loan_id' => $this->loan->id,
            'installment_number' => $this->installment->installment_number,
            'original_amount' => bcadd($this->installment->principal, $this->installment->interest, 2),
            'penalty' => $this->installment->penalty,
            'total_due' => $this->installment->total,
            'days_overdue' => $daysOverdue,
            'status' => 'overdue',
            'message' => "Installment #{$this->installment->installment_number} is overdue by {$daysOverdue} day(s). Total due: {$this->installment->total} (including penalties).",
        ];
    }

}
