<?php

require __DIR__ . '/vendor/autoload.php';

$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

use App\Models\ImmigoProSubscription;
use App\Models\PaymentGateway;

// Get the session ID from command line
$sessionId = $argv[1] ?? null;

if (!$sessionId) {
    echo "Usage: php activate_immigopro_subscription.php <stripe_session_id>\n";
    exit(1);
}

// Find the subscription
$subscription = ImmigoProSubscription::where('stripe_checkout_session_id', $sessionId)
    ->where('status', 'pending')
    ->first();

if (!$subscription) {
    echo "Subscription not found or already activated\n";
    exit(1);
}

// Load Stripe API key
$gateway = PaymentGateway::where('provider', 'stripe')->first();
$secretKey = $gateway->is_live_mode ? $gateway->live_secret_key : $gateway->test_secret_key;

if (!$secretKey) {
    echo "Stripe API key not configured\n";
    exit(1);
}

\Stripe\Stripe::setApiKey($secretKey);

try {
    // Retrieve the session from Stripe
    $session = \Stripe\Checkout\Session::retrieve($sessionId);
    
    echo "Session status: " . $session->payment_status . "\n";
    echo "Payment Intent: " . ($session->payment_intent ?? 'N/A') . "\n";
    
    if ($session->payment_status === 'paid') {
        // Update subscription status
        $updateData = [
            'status' => 'active',
            'stripe_payment_intent_id' => $session->payment_intent,
        ];
        
        // Store payment method for future charges if there are installments
        if ($subscription->installments > 0 && $session->payment_intent) {
            $paymentIntent = \Stripe\PaymentIntent::retrieve($session->payment_intent);
            if ($paymentIntent->payment_method) {
                $updateData['stripe_payment_method_id'] = $paymentIntent->payment_method;
                $updateData['next_charge_date'] = now()->addDays(30);
                echo "Payment method stored: " . $paymentIntent->payment_method . "\n";
                echo "Next charge date: " . now()->addDays(30)->format('Y-m-d') . "\n";
            }
        } else {
            // Full payment - mark as completed
            $updateData['status'] = 'completed';
            $updateData['completed_at'] = now();
            echo "Full payment - marking as completed\n";
        }
        
        $subscription->update($updateData);
        
        echo "\nSubscription activated successfully!\n";
        echo "Subscription ID: " . $subscription->id . "\n";
        echo "Status: " . $updateData['status'] . "\n";
        echo "Package: " . $subscription->package_name . "\n";
        echo "Payment plan: " . $subscription->payment_plan . "\n";
        
    } else {
        echo "Payment not completed yet. Status: " . $session->payment_status . "\n";
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}
