<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Subscription;
use App\Mail\SubscriptionExpiring;
use App\Mail\SubscriptionExpired;
use Illuminate\Support\Facades\Mail;
use Carbon\Carbon;

class CheckSubscriptionExpiry extends Command
{
    protected $signature = 'subscription:check-expiry';
    protected $description = 'Check for expiring and expired subscriptions';

    public function handle()
    {
        $today = Carbon::today();

        // 1. Reminders (7, 3, 1 days before expiry)
        $reminderDays = [7, 3, 1];
        foreach ($reminderDays as $days) {
            $expiryDate = $today->copy()->addDays($days);
            $subscriptions = Subscription::whereDate('end_date', $expiryDate)
                                         ->where('status', 'active')
                                         ->get();

            foreach ($subscriptions as $sub) {
                Mail::to($sub->seller->user->email)->send(new SubscriptionExpiring($sub, $days));
                $this->info("Reminder sent to {$sub->seller->company_name} ({$days} days left)");
            }
        }

        // 2. Move to Grace Period (Expired today)
        $expiredSubscriptions = Subscription::whereDate('end_date', '<', $today)
                                            ->where('status', 'active')
                                            ->get();

        foreach ($expiredSubscriptions as $sub) {
            $sub->update(['status' => 'grace_period']);
            $this->info("Moved {$sub->seller->company_name} to grace period");
        }

        // 3. Final Expiry (Grace period over - 3 days after expiry)
        $gracePeriodOverDate = $today->copy()->subDays(3);
        $finalExpiredSubscriptions = Subscription::whereDate('end_date', '<=', $gracePeriodOverDate)
                                                 ->where('status', 'grace_period')
                                                 ->get();

        foreach ($finalExpiredSubscriptions as $sub) {
            $sub->update(['status' => 'inactive']);
            Mail::to($sub->seller->user->email)->send(new SubscriptionExpired($sub));
            $this->info("Expired subscription for {$sub->seller->company_name}");
        }

        $this->info('Subscription check completed.');
    }
}
