<?php

namespace App\Console\Commands;

use App\Domain\Financial\Models\Installment;
use App\Domain\Notification\Services\PushNotificationService;
use App\Domain\Participant\Models\Participant;
use Illuminate\Console\Command;

class SendInstallmentDuePush extends Command
{
    protected $signature = 'push:installment-due {--days=1 : Days before due date to send reminder}';
    protected $description = 'Send push notification for upcoming installment due dates';

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

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

        $count = 0;
        foreach ($installments as $installment) {
            $invoice = $installment->paymentPlan?->invoice;
            if (!$invoice) {
                continue;
            }

            if ($invoice->billable_type !== 'App\\Domain\\Participant\\Models\\Participant') {
                continue;
            }

            $participant = Participant::find($invoice->billable_id);
            if (!$participant) {
                continue;
            }

            $amount = number_format($installment->amount / 100, 2);
            $dueLabel = $days === 1 ? 'غداً' : "خلال {$days} أيام";

            $pushService->sendToParticipantGuardians(
                $participant,
                'تذكير بالقسط',
                "قسط بقيمة {$amount} ج.م مستحق {$dueLabel}",
                [
                    'type' => 'installment_due',
                    'participant_uuid' => $participant->uuid,
                    'invoice_uuid' => $invoice->uuid,
                    'amount' => $installment->amount,
                    'due_date' => $targetDate,
                ],
                'installment.due_reminder'
            );

            $count++;
        }

        $this->info("Sent installment reminders for {$count} installments.");

        return self::SUCCESS;
    }
}
