<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class FixCascadeLaporan extends Migration
{
    public function up()
    {
        // Cek apakah foreign key dengan CASCADE masih ada
        $foreignKeys = $this->db->getForeignKeyData('detail_peminjaman');

        $hasCascadeBuku = false;
        $hasCascadePeminjaman = false;

        foreach ($foreignKeys as $fk) {
            if ($fk->column_name === 'buku_id' && $fk->delete_rule === 'CASCADE') {
                $hasCascadeBuku = true;
            }
            if ($fk->column_name === 'peminjaman_id' && $fk->delete_rule === 'CASCADE') {
                $hasCascadePeminjaman = true;
            }
        }

        // Jika masih ada CASCADE, kita ubah
        if ($hasCascadeBuku || $hasCascadePeminjaman) {
            // Hapus FK lama (pakai nama constraint dari database)
            foreach ($foreignKeys as $fk) {
                if ($fk->delete_rule === 'CASCADE') {
                    $this->db->query("ALTER TABLE `detail_peminjaman` DROP FOREIGN KEY `{$fk->constraint_name}`");
                }
            }

            // Tambah ulang dengan NO ACTION
            $this->forge->addForeignKey('peminjaman_id', 'peminjaman', 'id', 'NO ACTION', 'NO ACTION');
            $this->forge->addForeignKey('buku_id', 'buku', 'id', 'NO ACTION', 'NO ACTION');
        }
    }

    public function down()
    {
        // Kembalikan ke CASCADE
        $foreignKeys = $this->db->getForeignKeyData('detail_peminjaman');

        foreach ($foreignKeys as $fk) {
            $this->db->query("ALTER TABLE `detail_peminjaman` DROP FOREIGN KEY `{$fk->constraint_name}`");
        }

        $this->forge->addForeignKey('peminjaman_id', 'peminjaman', 'id', 'CASCADE', 'CASCADE');
        $this->forge->addForeignKey('buku_id', 'buku', 'id', 'CASCADE', 'CASCADE');
    }
}

