<?php

namespace App\Console\Commands;

use App\Models\Setting;
use App\Models\User;
use App\Notifications\PointsExpiryReminderNotification;
use Carbon\Carbon;
use Illuminate\Console\Command;

class SendExpiryReminders extends Command
{
    protected $signature = 'loyalty:send-expiry-reminders';
    protected $description = 'Send points expiry reminder emails to members approaching their anniversary date.';

    public function handle(): int
    {
        $reminderDays = Setting::get('points_expiry_reminder_days', 30);
        $targetDate = Carbon::today()->addDays($reminderDays);

        $members = User::where('status', 'active')
            ->whereDate('points_expiry_date', $targetDate->toDateString())
            ->where('points_balance', '>', 0)
            ->get();

        $sent = 0;
        foreach ($members as $member) {
            $member->notify(new PointsExpiryReminderNotification(
                $member->points_balance,
                $member->points_expiry_date->format('d M Y'),
            ));
            $sent++;
        }

        $this->info("Sent {$sent} expiry reminder(s).");
        return self::SUCCESS;
    }
}
