<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\LoanInstallment;
use App\Notifications\LoanReminderNotification;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class SendLoanReminders extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'loans:send-reminders';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send reminders to users for upcoming loan installments';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $reminderDays = config('loan.reminder_days', 3);
        $targetDate = now()->addDays($reminderDays)->startOfDay();

        LoanInstallment::pending()
            ->whereDate('due_date', $targetDate)
            ->with('loan.user')
            ->chunk(100, function ($installments) {

                foreach ($installments as $installment) {
                    $user = $installment->loan->user;

                    if (!$user)
                        continue;

                    try {
                        $user->notify(new LoanReminderNotification($installment->loan, $installment));
                        $this->info("Reminder sent to {$user->email} for installment #{$installment->installment_number} of Loan ID {$installment->loan->id}");
                    } catch (\Throwable $e) {
                        Log::error('Failed to send loan reminder', [
                            'loan_id' => $installment->loan->id,
                            'installment_id' => $installment->id,
                            'user_id' => $user->id,
                            'exception' => $e,
                        ]);
                    }
                }

            });

        $this->info('Loan reminders sent successfully.');
    }
}
