<?php

namespace App\Console\Commands;

use App\Models\Subscription;
use App\Notifications\PaymentReminder;
use Carbon\Carbon;
use Illuminate\Console\Command;

class SendPaymentReminders extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'payments:send-reminders';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Enviar recordatorios de pago a usuarios con suscripciones próximas a vencer';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Enviando recordatorios de pago...');

        // Recordatorios 15 días antes
        $this->sendReminders(15);

        // Recordatorios 7 días antes
        $this->sendReminders(7);

        // Recordatorios 3 días antes (más urgente)
        $this->sendReminders(3);

        $this->info('Recordatorios enviados correctamente.');
    }

    /**
     * Enviar recordatorios para suscripciones que vencen en X días
     */
    private function sendReminders(int $days)
    {
        $targetDate = Carbon::now()->addDays($days)->toDateString();

        $subscriptions = Subscription::where('status', 'active')
            ->whereDate('end_date', $targetDate)
            ->with('user')
            ->get();

        foreach ($subscriptions as $subscription) {
            if ($subscription->user) {
                $subscription->user->notify(new PaymentReminder($subscription, $days));
                $this->info("Recordatorio enviado a {$subscription->user->name} ({$days} días)");
            }
        }

        $count = $subscriptions->count();
        $this->info("Total: {$count} recordatorios de {$days} días enviados.");
    }
}
