<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Add subscription_id to invoices table if it doesn't exist
        if (!Schema::hasColumn('invoices', 'subscription_id')) {
            Schema::table('invoices', function (Blueprint $table) {
                $table->foreignId('subscription_id')->nullable()->after('user_id')->constrained()->onDelete('cascade');
            });
        }

        // Add subscription_id to transactions table if it doesn't exist
        if (!Schema::hasColumn('transactions', 'subscription_id')) {
            Schema::table('transactions', function (Blueprint $table) {
                $table->foreignId('subscription_id')->nullable()->after('invoice_id')->constrained()->onDelete('cascade');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('invoices', function (Blueprint $table) {
            $table->dropForeign(['subscription_id']);
            $table->dropColumn('subscription_id');
        });

        Schema::table('transactions', function (Blueprint $table) {
            $table->dropForeign(['subscription_id']);
            $table->dropColumn('subscription_id');
        });
    }
};
