<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Only add foreign key if payment_methods table exists and subscriptions table exists
        if (Schema::hasTable('payment_methods') && Schema::hasTable('subscriptions')) {
            Schema::table('subscriptions', function (Blueprint $table) {
                // Check if foreign key doesn't already exist
                if (!$this->hasForeignKey('subscriptions', 'subscriptions_payment_method_id_foreign')) {
                    $table->foreign('payment_method_id')
                          ->references('id')
                          ->on('payment_methods')
                          ->onDelete('set null');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('subscriptions', function (Blueprint $table) {
            if ($this->hasForeignKey('subscriptions', 'subscriptions_payment_method_id_foreign')) {
                $table->dropForeign(['payment_method_id']);
            }
        });
    }

    /**
     * Check if a foreign key exists
     */
    private function hasForeignKey(string $table, string $foreignKey): bool
    {
        $databaseName = DB::getDatabaseName();
        
        $result = DB::select(
            "SELECT COUNT(*) as count 
             FROM information_schema.key_column_usage 
             WHERE table_schema = ? 
             AND table_name = ? 
             AND constraint_name = ?",
            [$databaseName, $table, $foreignKey]
        );
        
        return $result[0]->count > 0;
    }
};
