<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Subscription;
use App\Services\EmailService;
use Illuminate\Support\Facades\Log;

class SendSubscriptionExpiryReminders extends Command
{
    protected $signature = 'subscriptions:send-expiry-reminders';
    protected $description = 'Send email reminders to sellers whose subscriptions are expiring soon';

    public function handle()
    {
        $this->info('Checking for expiring subscriptions...');

        // 7 days reminder
        $this->sendReminders(7, 'subscription-expiring-7-days');
        
        // 3 days reminder
        $this->sendReminders(3, 'subscription-expiring-3-days');
        
        // 1 day reminder
        $this->sendReminders(1, 'subscription-expiring-1-day');

        // Expired today
        $this->sendExpiredNotifications();

        $this->info('Done.');
        return Command::SUCCESS;
    }

    protected function sendReminders(int $days, string $templateSlug)
    {
        $targetDate = now()->addDays($days)->toDateString();

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

        $count = 0;
        foreach ($subscriptions as $subscription) {
            if (!$subscription->seller || !$subscription->seller->user) {
                continue;
            }

            try {
                EmailService::send($templateSlug, $subscription->seller->user->email, [
                    'seller_name' => $subscription->seller->user->name,
                    'plan_name' => $subscription->plan->name ?? 'Your Plan',
                    'expiry_date' => $subscription->end_date->format('F j, Y'),
                    'days_left' => $days,
                    'renew_link' => route('seller.subscription.index'),
                ]);
                $count++;
            } catch (\Exception $e) {
                Log::error("Failed to send expiry reminder to {$subscription->seller->user->email}: " . $e->getMessage());
            }
        }

        if ($count > 0) {
            $this->info("Sent {$count} reminders for {$days}-day expiry.");
        }
    }

    protected function sendExpiredNotifications()
    {
        $subscriptions = Subscription::with(['seller.user', 'plan'])
            ->where('status', 'active')
            ->whereDate('end_date', now()->subDay()->toDateString())
            ->get();

        $count = 0;
        foreach ($subscriptions as $subscription) {
            if (!$subscription->seller || !$subscription->seller->user) {
                continue;
            }

            // Mark as expired
            $subscription->update(['status' => 'expired']);

            try {
                EmailService::send('subscription-expired', $subscription->seller->user->email, [
                    'seller_name' => $subscription->seller->user->name,
                    'plan_name' => $subscription->plan->name ?? 'Your Plan',
                    'renew_link' => route('seller.subscription.index'),
                ]);
                $count++;
            } catch (\Exception $e) {
                Log::error("Failed to send expiry notification to {$subscription->seller->user->email}: " . $e->getMessage());
            }
        }

        if ($count > 0) {
            $this->info("Marked {$count} subscriptions as expired and sent notifications.");
        }
    }
}
