<?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
    {
        try {
        DB::statement('ALTER TABLE rekomendasi_ahli DROP FOREIGN KEY rekomendasi_ahli_makanan_id_foreign');
    } catch (\Throwable $e) {
        // Abaikan jika FK tidak ada
    }

    // 2. Hapus kolom makanan_id jika masih ada
    if (Schema::hasColumn('rekomendasi_ahli', 'makanan_id')) {
        Schema::table('rekomendasi_ahli', function (Blueprint $table) {
            $table->dropColumn('makanan_id');
        });
    }

    // 3. Tambahkan nama_makanan hanya jika belum ada
    if (!Schema::hasColumn('rekomendasi_ahli', 'nama_makanan')) {
        Schema::table('rekomendasi_ahli', function (Blueprint $table) {
            $table->text('nama_makanan')->after('id');
        });
    }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Revert ke kondisi sebelumnya
        Schema::table('rekomendasi_ahli', function (Blueprint $table) {
            $table->dropColumn('nama_makanan');
            $table->unsignedBigInteger('makanan_id')->nullable();
            $table->foreign('makanan_id')->references('id')->on('makanans')->onDelete('cascade');
        });
    }
};
