<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Only proceed if table exists (for backward compatibility)
        if (!Schema::hasTable('buku_tamu')) {
            return;
        }

        Schema::table('buku_tamu', function (Blueprint $table) {
            // Drop old FK if exists
            try {
                DB::statement('ALTER TABLE buku_tamu DROP FOREIGN KEY buku_tamu_ibfk_1');
            } catch (\Exception $e) {
                // Ignore
            }

            try {
                $table->dropForeign(['id_user']);
            } catch (\Exception $e) {
                // Ignore if FK doesn't exist
            }

            // Change column type if needed
            DB::statement('ALTER TABLE buku_tamu MODIFY id_user BIGINT UNSIGNED NULL');

            // Add correct FK
            $table->foreign('id_user')
                ->references('id')
                ->on('users')
                ->onDelete('set null');
        });
    }

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