<?php

namespace App\Console\Commands;

use App\Models\ImmigoProSubscription;
use App\Models\ImmigoProInstallmentPayment;
use App\Models\PaymentGateway;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Stripe\Stripe;
use Stripe\PaymentIntent;

class ChargeImmigoProInstallments extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'immigopro:charge-installments {--dry-run : Preview charges without executing}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Charge monthly installments for active ImmigoPro subscriptions (does not affect regular subscriptions)';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $dryRun = $this->option('dry-run');
        
        if ($dryRun) {
            $this->info('🔍 DRY RUN MODE - No charges will be made');
        }
        
        $this->info('📦 ImmigoPro Installment Charging System');
        $this->info('=====================================');
        $this->info('This command ONLY processes ImmigoPro packages (immigo_pro_subscriptions table)');
        $this->info('Regular subscriptions are NOT affected by this command.');
        $this->info('');

        // Load Stripe API key
        $gateway = PaymentGateway::where('provider', 'stripe')->first();
        
        if (!$gateway) {
            $this->error('Stripe gateway not configured');
            return 1;
        }

        $secretKey = $gateway->is_live_mode 
            ? $gateway->live_secret_key 
            : $gateway->test_secret_key;
            
        if (!$secretKey) {
            $this->error('Stripe API key not configured');
            return 1;
        }

        Stripe::setApiKey($secretKey);

        // Find ImmigoPro subscriptions due for payment
        // Only queries immigo_pro_subscriptions table - completely separate from subscriptions table
        $subscriptions = ImmigoProSubscription::with('user')
            ->where('status', 'active')
            ->where('next_charge_date', '<=', now())
            ->whereColumn('paid_installments', '<', 'installments')
            ->whereNotNull('stripe_payment_method_id')
            ->get();

        $this->info("Found {$subscriptions->count()} ImmigoPro subscriptions due for charging");
        
        if ($subscriptions->isEmpty()) {
            $this->info('No charges needed at this time.');
            return 0;
        }

        $successCount = 0;
        $failCount = 0;

        foreach ($subscriptions as $subscription) {
            $nextInstallment = $subscription->paid_installments + 1;
            
            $this->line('');
            $this->info("Processing: ImmigoPro Subscription #{$subscription->id}");
            $this->line("  Package: {$subscription->package_name}");
            $this->line("  User ID: {$subscription->user_id}");
            $this->line("  Installment: {$nextInstallment} of {$subscription->installments}");
            $this->line("  Amount: \${$subscription->monthly_amount}");
            
            if ($dryRun) {
                $this->warn("  [DRY RUN] Would charge this subscription");
                $successCount++;
                continue;
            }

            try {
                // Get user's Stripe customer ID
                $user = $subscription->user;
                if (!$user || !$user->stripe_customer_id) {
                    throw new \Exception("User has no Stripe customer ID (User ID: {$subscription->user_id})");
                }

                // Create payment intent with stored payment method
                $paymentIntent = PaymentIntent::create([
                    'amount' => round($subscription->monthly_amount * 100), // Convert to cents
                    'currency' => 'cad',
                    'customer' => $user->stripe_customer_id,
                    'payment_method' => $subscription->stripe_payment_method_id,
                    'confirm' => true,
                    'off_session' => true,
                    'description' => "ImmigoPro Installment {$nextInstallment}/{$subscription->installments} - {$subscription->package_name}",
                    'metadata' => [
                        'type' => 'immigopro_installment',
                        'subscription_id' => $subscription->id,
                        'installment_number' => $nextInstallment,
                        'package_name' => $subscription->package_name,
                        'user_id' => $subscription->user_id,
                    ],
                ]);

                if ($paymentIntent->status === 'succeeded') {
                    // Create payment record for this installment
                    ImmigoProInstallmentPayment::create([
                        'subscription_id' => $subscription->id,
                        'installment_number' => $nextInstallment,
                        'amount' => $subscription->monthly_amount,
                        'stripe_payment_intent_id' => $paymentIntent->id,
                        'status' => 'completed',
                        'paid_at' => now(),
                    ]);

                    // Update subscription progress
                    $newPaidInstallments = $nextInstallment;
                    $isCompleted = $newPaidInstallments >= $subscription->installments;
                    
                    $subscription->update([
                        'paid_installments' => $newPaidInstallments,
                        'next_charge_date' => $isCompleted ? null : now()->addDays(30),
                        'status' => $isCompleted ? 'completed' : 'active',
                        'completed_at' => $isCompleted ? now() : null,
                    ]);

                    $this->info("  ✓ SUCCESS: Charged \${$subscription->monthly_amount}");
                    $this->line("  Payment Intent: {$paymentIntent->id}");
                    $this->line("  Progress: {$newPaidInstallments}/{$subscription->installments} paid");
                    
                    if ($isCompleted) {
                        $this->info("  🎉 Subscription completed! All installments paid.");
                    } else {
                        $this->line("  Next charge: " . now()->addDays(30)->format('Y-m-d'));
                    }
                    
                    $successCount++;
                    
                    Log::info('ImmigoPro installment charged successfully', [
                        'subscription_id' => $subscription->id,
                        'installment' => $newPaidInstallments,
                        'amount' => $subscription->monthly_amount,
                        'payment_intent' => $paymentIntent->id,
                    ]);
                    
                } else {
                    throw new \Exception("Payment intent status: {$paymentIntent->status}");
                }
                
            } catch (\Stripe\Exception\CardException $e) {
                // Card was declined
                $this->error("  ✗ FAILED: Card declined - {$e->getMessage()}");
                $failCount++;
                
                Log::error('ImmigoPro installment charge failed - Card declined', [
                    'subscription_id' => $subscription->id,
                    'error' => $e->getMessage(),
                ]);
                
                // TODO: Send email to user about failed payment
                
            } catch (\Exception $e) {
                $this->error("  ✗ FAILED: {$e->getMessage()}");
                $failCount++;
                
                Log::error('ImmigoPro installment charge failed', [
                    'subscription_id' => $subscription->id,
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString(),
                ]);
            }
        }

        $this->line('');
        $this->info('=====================================');
        $this->info("Summary:");
        $this->line("  Total processed: {$subscriptions->count()}");
        $this->line("  Successful: {$successCount}");
        $this->line("  Failed: {$failCount}");
        $this->info('=====================================');
        
        if ($dryRun) {
            $this->warn('This was a DRY RUN - no actual charges were made');
        }

        return 0;
    }
}
