<?php

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

class RemoveForeignKeyFromLinkManagement extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Check if foreign key exists before trying to drop it
        $foreignKeys = DB::select("
            SELECT CONSTRAINT_NAME
            FROM information_schema.TABLE_CONSTRAINTS
            WHERE CONSTRAINT_SCHEMA = DATABASE()
            AND TABLE_NAME = 'link_management'
            AND CONSTRAINT_NAME = 'link_management_created_by_foreign'
        ");

        if (!empty($foreignKeys)) {
            Schema::table('link_management', function (Blueprint $table) {
                $table->dropForeign(['created_by']);
            });
        }

        // The rest of your migration can proceed without changes
        Schema::table('link_management', function (Blueprint $table) {
            $table->integer('created_by')->change(); // Change column type to integer (if needed)
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Check if foreign key already exists before trying to add it
        $foreignKeys = DB::select("
            SELECT CONSTRAINT_NAME
            FROM information_schema.TABLE_CONSTRAINTS
            WHERE CONSTRAINT_SCHEMA = DATABASE()
            AND TABLE_NAME = 'link_management'
            AND CONSTRAINT_NAME = 'link_management_created_by_foreign'
        ");

        if (empty($foreignKeys)) {
            Schema::table('link_management', function (Blueprint $table) {
                $table->unsignedBigInteger('created_by')->change();
                $table->foreign('created_by')->references('id')->on('emp_company_details')->onDelete('cascade');
            });
        }
    }
}