<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // 1. Matikan FK sementara
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        // 2. Hapus FK lama jika ada
        try {
            DB::statement('ALTER TABLE mengajars DROP FOREIGN KEY mengajars_id_mapel_foreign');
        } catch (\Exception $e) {}

        try {
            DB::statement('ALTER TABLE mengajars DROP FOREIGN KEY mengajars_id_kelas_foreign');
        } catch (\Exception $e) {}

        try {
            DB::statement('ALTER TABLE mengajars DROP FOREIGN KEY mengajars_id_guru_new_foreign');
        } catch (\Exception $e) {}

        // 3. Ubah tipe kolom
        DB::statement('ALTER TABLE mengajars MODIFY id_mapel BIGINT UNSIGNED');
        DB::statement('ALTER TABLE mengajars MODIFY id_kelas BIGINT UNSIGNED');
        DB::statement('ALTER TABLE mengajars MODIFY id_guru BIGINT UNSIGNED');

        // 4. Tambahkan FK baru
        DB::statement('
            ALTER TABLE mengajars
            ADD CONSTRAINT fk_mengajar_mapel
            FOREIGN KEY (id_mapel) REFERENCES mapels(id_mapel)
            ON DELETE CASCADE
        ');

        DB::statement('
            ALTER TABLE mengajars
            ADD CONSTRAINT fk_mengajar_kelas
            FOREIGN KEY (id_kelas) REFERENCES kelas(id_kelas)
            ON DELETE CASCADE
        ');

        DB::statement('
            ALTER TABLE mengajars
            ADD CONSTRAINT fk_mengajar_guru
            FOREIGN KEY (id_guru) REFERENCES gurus(id_guru)
            ON DELETE CASCADE
        ');

        // 5. Hidupkan lagi FK
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }

    public function down(): void
    {
        //
    }
};
