<?php

namespace App\Console\Commands;

use App\Domain\Financial\Models\PaymentPlanInstallment;
use App\Domain\Notification\Services\NotificationService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SendInstallmentReminders extends Command
{
    protected $signature = 'reminders:installments {--days=3 : Days before due date to remind}';
    protected $description = 'Send reminders for upcoming installment payments';

    public function handle(NotificationService $notificationService): int
    {
        $days = (int) $this->option('days');
        $targetDate = now()->addDays($days)->toDateString();

        $installments = PaymentPlanInstallment::where('status', 'pending')
            ->whereDate('due_date', $targetDate)
            ->with(['paymentPlan.invoice.participant.person'])
            ->get();

        $sent = 0;
        foreach ($installments as $installment) {
            $participant = $installment->paymentPlan?->invoice?->participant;
            $person = $participant?->person;

            if (!$person) {
                continue;
            }

            try {
                $notificationService->send(
                    eventType: 'installment_due',
                    recipientType: 'participant',
                    recipientId: $participant->id,
                    academyId: $installment->paymentPlan->academy_id ?? $participant->academy_id,
                    variables: [
                        'participant_name' => $person->name_ar ?? $person->name ?? '',
                        'amount' => number_format($installment->amount / 100, 2),
                        'due_date' => $installment->due_date?->format('Y-m-d') ?? '',
                        'installment_number' => (string) $installment->installment_number,
                        'days_remaining' => (string) $days,
                    ],
                    recipientEmail: $person->email,
                    recipientPhone: $person->phone,
                );
                $sent++;
            } catch (\Throwable $e) {
                Log::warning("Installment reminder failed for installment {$installment->id}: " . $e->getMessage());
            }
        }

        $this->info("Sent {$sent} installment reminders ({$days} days before due).");
        return self::SUCCESS;
    }
}
