<?php

namespace App\Console\Commands;

use App\Models\Loan;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class CheckLoanDefaults extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:check-loan-defaults';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check for loans that have exceeded their return date and mark them as defaulted';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Checking for defaulted loans...');

        // Find loans that have exceeded return date and are not fully paid
        $defaultedLoans = Loan::where('return_date', '<', now())
            ->where('status', '!=', 'paid')
            ->where('status', '!=', 'defaulted')
            ->whereRaw('(amount + (amount * interest_rate / 100)) > paid_amount')
            ->with('user')
            ->get();

        if ($defaultedLoans->isEmpty()) {
            $this->info('No defaulted loans found.');
            return;
        }

        $this->info("Found {$defaultedLoans->count()} defaulted loans.");

        $bar = $this->output->createProgressBar($defaultedLoans->count());
        $bar->start();

        foreach ($defaultedLoans as $loan) {
            try {
                // Update loan status to defaulted
                $loan->update(['status' => 'defaulted']);

                // Send email notification to member
                $this->sendDefaultNotification($loan);

                // Log the default
                Log::info('Loan marked as defaulted', [
                    'loan_id' => $loan->id,
                    'user_id' => $loan->user_id,
                    'return_date' => $loan->return_date,
                    'outstanding_balance' => $loan->balance
                ]);

                $bar->advance();
            } catch (\Exception $e) {
                $this->error("Failed to process loan {$loan->id}: " . $e->getMessage());
                Log::error('Failed to process defaulted loan', [
                    'loan_id' => $loan->id,
                    'error' => $e->getMessage()
                ]);
            }
        }

        $bar->finish();
        $this->newLine();
        $this->info('Loan default check completed.');
    }

    /**
     * Send default notification email to member
     */
    private function sendDefaultNotification(Loan $loan)
    {
        try {
            Mail::send('emails.loan-default-notification', [
                'loan' => $loan,
                'user' => $loan->user,
                'outstanding_balance' => $loan->balance,
                'return_date' => $loan->return_date,
                'application_date' => $loan->application_date,
            ], function ($message) use ($loan) {
                $message->to($loan->user->email)
                        ->subject('Loan Default Notice - Morio Sacco');
            });

            Log::info('Loan default notification email sent', [
                'loan_id' => $loan->id,
                'email' => $loan->user->email
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send loan default notification email', [
                'loan_id' => $loan->id,
                'email' => $loan->user->email,
                'error' => $e->getMessage()
            ]);
        }
    }
}
