<?php

namespace App\Console\Commands;

use App\Jobs\SendBasketReminderJob;
use App\Services\BasketService;
use Illuminate\Console\Command;

class SendBasketRemindersCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'baskets:send-reminders 
                            {--days=7 : Number of days since last activity to send reminders}
                            {--dry-run : Show what would be sent without actually sending}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send reminder emails for abandoned baskets';

    protected BasketService $basketService;

    public function __construct(BasketService $basketService)
    {
        parent::__construct();
        $this->basketService = $basketService;
    }

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $days = (int) $this->option('days');
        $dryRun = $this->option('dry-run');

        $this->info("Starting basket reminder process for baskets inactive for {$days} days...");

        // Hatırlatma gönderilecek sepetleri al
        $baskets = $this->basketService->getBasketsForReminder($days);

        if ($baskets->isEmpty()) {
            $this->info('No baskets found that need reminders.');

            return Command::SUCCESS;
        }

        $this->info("Found {$baskets->count()} baskets that need reminders.");

        if ($dryRun) {
            $this->info('DRY RUN MODE - No emails will be sent');
        }

        $bar = $this->output->createProgressBar($baskets->count());
        $bar->start();

        $sentCount = 0;
        $skippedCount = 0;

        foreach ($baskets as $basket) {
            try {
                if ($dryRun) {
                    $this->line("\nWould send reminder for basket {$basket->id} to {$basket->client?->email}");
                } else {
                    // Hatırlatma job'ını kuyruğa ekle
                    SendBasketReminderJob::dispatch($basket);
                    $sentCount++;
                }
            } catch (\Exception $e) {
                $this->error("\nFailed to process basket {$basket->id}: ".$e->getMessage());
                $skippedCount++;
            }

            $bar->advance();
        }

        $bar->finish();
        $this->newLine(2);

        if ($dryRun) {
            $this->info("DRY RUN COMPLETED: Would send {$baskets->count()} reminders");
        } else {
            $this->info('Reminder process completed:');
            $this->info("- Reminders queued: {$sentCount}");
            $this->info("- Skipped: {$skippedCount}");
        }

        // İstatistikleri göster
        $this->newLine();
        $this->info('Basket Statistics:');
        $stats = $this->basketService->getStatistics();
        $this->table(
            ['Metric', 'Count'],
            [
                ['Total Baskets', $stats['total']],
                ['Active Baskets', $stats['active']],
                ['Expired Baskets', $stats['expired']],
                ['Client Baskets', $stats['client']],
                ['Anonymous Baskets', $stats['anonymous']],
                ['Recent Activity (7 days)', $stats['recent_activity']],
                ['Old Baskets (30+ days)', $stats['old']],
            ]
        );

        return Command::SUCCESS;
    }
}
