<?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;
use Stripe\Stripe;
use Stripe\Customer;
use Stripe\PaymentMethod;

$subId = $argv[1] ?? null;

if (!$subId) {
    echo "Usage: php create_customer_attach_pm.php <subscription_id>\n";
    exit(1);
}

$sub = ImmigoProSubscription::find($subId);

if (!$sub) {
    echo "Subscription not found\n";
    exit(1);
}

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

$user = $sub->user;

echo "========================================\n";
echo "Creating Stripe Customer & Attaching Payment Method\n";
echo "========================================\n";
echo "User ID: {$user->id}\n";
echo "Email: {$user->email}\n";
echo "Payment Method: {$sub->stripe_payment_method_id}\n\n";

// Create or get Stripe customer
if ($user->stripe_customer_id) {
    echo "User already has customer ID: {$user->stripe_customer_id}\n";
    $customerId = $user->stripe_customer_id;
} else {
    echo "Creating new Stripe customer...\n";
    $customer = Customer::create([
        'email' => $user->email,
        'name' => $user->name,
        'metadata' => [
            'user_id' => $user->id,
        ],
    ]);
    $customerId = $customer->id;
    echo "✓ Created customer: $customerId\n";
    
    $user->update(['stripe_customer_id' => $customerId]);
    echo "✓ Updated user with customer ID\n";
}

// Attach payment method to customer
echo "\nAttaching payment method to customer...\n";
try {
    $paymentMethod = PaymentMethod::retrieve($sub->stripe_payment_method_id);
    
    // If already attached to a different customer, detach first
    if ($paymentMethod->customer && $paymentMethod->customer !== $customerId) {
        echo "Payment method attached to different customer, detaching first...\n";
        $paymentMethod->detach();
        $paymentMethod = PaymentMethod::retrieve($sub->stripe_payment_method_id);
    }
    
    // Attach to our customer
    if (!$paymentMethod->customer) {
        $paymentMethod->attach(['customer' => $customerId]);
        echo "✓ Payment method attached!\n";
    } else {
        echo "✓ Payment method already attached to this customer!\n";
    }
} catch (\Exception $e) {
    if (strpos($e->getMessage(), 'already been attached') !== false) {
        echo "✓ Payment method already attached!\n";
    } else {
        throw $e;
    }
}

echo "\n========================================\n";
echo "✓ Setup complete! Ready to charge installments.\n";
echo "========================================\n";
