<?php

namespace App\Console\Commands;

use App\Domain\Notification\Services\NotificationService;
use App\Domain\Training\Models\Enrollment;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SendExpiringSoonReminders extends Command
{
    protected $signature = 'reminders:expiring-enrollments {--days=7 : Days before expiry to send reminder}';
    protected $description = 'Send reminders for enrollments expiring soon';

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

        $enrollments = Enrollment::with(['participant.person', 'group.program'])
            ->where('status', 'active')
            ->whereDate('expiry_date', $targetDate)
            ->get();

        $sent = 0;
        foreach ($enrollments as $enrollment) {
            $participant = $enrollment->participant;
            $person = $participant?->person;

            if (!$person) {
                continue;
            }

            try {
                $notificationService->send(
                    eventType: 'enrollment_expiring',
                    recipientType: 'participant',
                    recipientId: $participant->id,
                    academyId: $enrollment->academy_id,
                    variables: [
                        'participant_name' => $person->name_ar ?? $person->name ?? '',
                        'program_name' => $enrollment->group?->program?->name_ar ?? '',
                        'group_name' => $enrollment->group?->name_ar ?? '',
                        'expiry_date' => $enrollment->expiry_date?->format('Y-m-d') ?? '',
                        'days_remaining' => (string) $days,
                    ],
                    recipientEmail: $person->email,
                    recipientPhone: $person->phone,
                );
                $sent++;
            } catch (\Throwable $e) {
                Log::warning("Failed to send expiry reminder for enrollment {$enrollment->id}: " . $e->getMessage());
            }
        }

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