<?php

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

return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasColumn('users', 'company_id')) {
            // 1) Drop the foreign key (default Laravel name)
            try {
                Schema::table('users', function (Blueprint $t) {
                    $t->dropForeign('users_company_id_foreign'); // or: $t->dropForeign(['company_id']);
                });
            } catch (\Throwable $e) {
                // Some hosts use different names; last resort temporarily disable checks
                DB::statement('SET FOREIGN_KEY_CHECKS=0');
            }

            // 2) Drop the column
            Schema::table('users', function (Blueprint $t) {
                $t->dropColumn('company_id');
            });

            // Re-enable checks
            try { DB::statement('SET FOREIGN_KEY_CHECKS=1'); } catch (\Throwable $e) {}
        }
    }

    public function down(): void
    {
        // restore if rolled back
        Schema::table('users', function (Blueprint $t) {
            $t->foreignId('company_id')->nullable()
              ->constrained('companies')->nullOnDelete();
        });
    }
};
