<?php

namespace App\Console\Commands;

use App\Models\Transaction;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class ExpirePendingTransactions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'transactions:expire-pending {--hours=24 : Hours after which to expire pending transactions}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Expire pending transactions that are older than specified hours (default: 24)';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $hours = $this->option('hours');
        $cutoffTime = Carbon::now()->subHours($hours);
        
        $this->info("Looking for pending transactions older than {$hours} hours (before {$cutoffTime})...");
        
        // Get pending transactions older than specified hours
        $pendingTransactions = Transaction::where('status', 'pending')
            ->where('created_at', '<', $cutoffTime)
            ->get();
        
        if ($pendingTransactions->isEmpty()) {
            $this->info('No pending transactions found to expire.');
            return 0;
        }
        
        $this->info("Found {$pendingTransactions->count()} pending transaction(s) to expire.");
        
        $expiredCount = 0;
        
        foreach ($pendingTransactions as $transaction) {
            try {
                $transaction->update(['status' => 'expired']);
                
                $this->line("Expired transaction #{$transaction->id} - User: {$transaction->user->name} - Package: {$transaction->package->name} - Created: {$transaction->created_at}");
                
                Log::info('Transaction expired by cron', [
                    'transaction_id' => $transaction->id,
                    'user_id' => $transaction->user_id,
                    'package_id' => $transaction->package_id,
                    'amount' => $transaction->amount,
                    'payment_method' => $transaction->payment_method,
                    'created_at' => $transaction->created_at,
                    'hours_old' => $transaction->created_at->diffInHours(Carbon::now())
                ]);
                
                $expiredCount++;
                
            } catch (\Exception $e) {
                $this->error("Failed to expire transaction #{$transaction->id}: {$e->getMessage()}");
                Log::error('Failed to expire transaction', [
                    'transaction_id' => $transaction->id,
                    'error' => $e->getMessage()
                ]);
            }
        }
        
        $this->info("Successfully expired {$expiredCount} transaction(s).");
        
        return 0;
    }
}