<?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
    {
        Schema::table('mengajars', function (Blueprint $table) {
            $table->unsignedBigInteger('id_guru')->nullable()->after('nip');
        });

        DB::statement("UPDATE mengajars m JOIN gurus g ON m.nip = g.nip SET m.id_guru = g.id_guru");

        Schema::table('mengajars', function (Blueprint $table) {
            $table->unsignedBigInteger('id_guru')->nullable(false)->change();
            $table->foreign('id_guru', 'mengajars_id_guru_new_foreign')
                  ->references('id_guru')->on('gurus')->onDelete('cascade');
        });

        Schema::table('mengajars', function (Blueprint $table) {
            $table->dropColumn('nip');
        });
    }

    public function down(): void
    {
        throw new \Exception('Rollback tidak didukung. Restore dari backup.');
    }
};