<?php

namespace App\Console\Commands;

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

class SendOverdueReminders extends Command
{
    protected $signature = 'reminders:overdue-invoices';
    protected $description = 'Send reminders for overdue invoices';

    public function handle(NotificationService $notificationService): int
    {
        $invoices = Invoice::whereIn('status', ['overdue', 'partially_paid'])
            ->where('due_date', '<', now()->toDateString())
            ->with(['billable.person'])
            ->get();

        $sent = 0;
        foreach ($invoices as $invoice) {
            $participant = $invoice->billable;
            $person = $participant?->person;

            if (!$person) {
                continue;
            }

            $daysOverdue = now()->diffInDays($invoice->due_date);
            $balanceDue = $invoice->total_amount - $invoice->paid_amount;

            try {
                $notificationService->send(
                    eventType: 'invoice_overdue_reminder',
                    recipientType: 'participant',
                    recipientId: $participant->id,
                    academyId: $invoice->academy_id,
                    variables: [
                        'participant_name' => $person->name_ar ?? $person->name ?? '',
                        'invoice_number' => $invoice->number ?? '',
                        'balance_due' => number_format($balanceDue / 100, 2),
                        'due_date' => $invoice->due_date?->format('Y-m-d') ?? '',
                        'days_overdue' => (string) $daysOverdue,
                    ],
                    recipientEmail: $person->email,
                    recipientPhone: $person->phone,
                );
                $sent++;
            } catch (\Throwable $e) {
                Log::warning("Overdue reminder failed for invoice {$invoice->id}: " . $e->getMessage());
            }
        }

        $this->info("Sent {$sent} overdue invoice reminders.");
        return self::SUCCESS;
    }
}
