<?php

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

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

echo "=== Manual Subscription Sync from Stripe ===\n\n";

$subscriptionId = 46;
$sub = DB::table('subscriptions')->where('id', $subscriptionId)->first();

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

echo "Syncing subscription ID: {$subscriptionId}\n";
echo "Stripe Subscription: {$sub->stripe_subscription_id}\n\n";

// Get API key
$gateway = DB::table('payment_gateways')->where('provider', 'stripe')->first();
Stripe\Stripe::setApiKey($gateway->test_secret_key);

try {
    // Fetch from Stripe
    $stripeSub = \Stripe\Subscription::retrieve($sub->stripe_subscription_id);
    
    $newPeriodEnd = date('Y-m-d H:i:s', $stripeSub->current_period_end);
    $newPeriodStart = date('Y-m-d H:i:s', $stripeSub->current_period_start);
    
    echo "Current in database:\n";
    echo "  Period Start: {$sub->current_period_start}\n";
    echo "  Period End: {$sub->current_period_end}\n\n";
    
    echo "Latest in Stripe:\n";
    echo "  Period Start: {$newPeriodStart}\n";
    echo "  Period End: {$newPeriodEnd}\n\n";
    
    // Update database
    DB::table('subscriptions')->where('id', $subscriptionId)->update([
        'current_period_start' => $newPeriodStart,
        'current_period_end' => $newPeriodEnd,
        'expires_at' => $newPeriodEnd,
    ]);
    
    echo "✅ Database updated successfully!\n\n";
    
    // Fetch latest invoices from Stripe
    echo "=== Fetching Invoices from Stripe ===\n";
    $stripeInvoices = \Stripe\Invoice::all([
        'subscription' => $sub->stripe_subscription_id,
        'limit' => 10,
    ]);
    
    echo "Found " . count($stripeInvoices->data) . " invoices in Stripe\n";
    echo "Database has " . DB::table('invoices')->where('subscription_id', $subscriptionId)->count() . " invoices\n\n";
    
    foreach ($stripeInvoices->data as $stripeInv) {
        // Check if invoice exists
        $existingInv = DB::table('invoices')
            ->where('subscription_id', $subscriptionId)
            ->where('amount', $stripeInv->amount_total / 100)
            ->where('status', 'paid')
            ->whereDate('created_at', date('Y-m-d', $stripeInv->created))
            ->first();
        
        if (!$existingInv && $stripeInv->status === 'paid') {
            echo "Creating missing invoice for " . date('Y-m-d', $stripeInv->created) . "...\n";
            
            $invoiceId = DB::table('invoices')->insertGetId([
                'user_id' => $sub->user_id,
                'subscription_id' => $subscriptionId,
                'invoice_number' => 'INV-' . strtoupper(uniqid()),
                'amount' => $stripeInv->amount_total / 100,
                'currency' => strtoupper($stripeInv->currency),
                'status' => 'paid',
                'paid_at' => date('Y-m-d H:i:s', $stripeInv->status_transitions->paid_at),
                'created_at' => date('Y-m-d H:i:s', $stripeInv->created),
                'updated_at' => now(),
            ]);
            
            // Create transaction
            DB::table('transactions')->insert([
                'invoice_id' => $invoiceId,
                'subscription_id' => $subscriptionId,
                'user_id' => $sub->user_id,
                'gateway_provider' => 'stripe',
                'gateway_transaction_id' => $stripeInv->payment_intent ?? $stripeInv->id,
                'amount' => $stripeInv->amount_total / 100,
                'currency' => strtoupper($stripeInv->currency),
                'status' => 'completed',
                'payment_method' => $stripeInv->payment_intent ? 'card' : null,
                'processed_at' => date('Y-m-d H:i:s', $stripeInv->status_transitions->paid_at),
                'created_at' => date('Y-m-d H:i:s', $stripeInv->created),
                'updated_at' => now(),
            ]);
            
            echo "✅ Invoice created: INV-{$invoiceId}\n";
        }
    }
    
    echo "\n✅ Sync complete!\n";
    echo "\nNow check:\n";
    echo "- Database should show Period End: {$newPeriodEnd}\n";
    echo "- Invoices table should have all renewals\n";
    
} catch (\Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
