<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Relasi Tabel Wilayah ke Masjid
        Schema::table('Wilayah', function (Blueprint $table) {
            $table->foreign('id_masjid')->references('id_masjid')->on('Masjid')->onDelete('cascade');
        });

        // Relasi Tabel users ke Wilayah & Masjid
        Schema::table('users', function (Blueprint $table) {
            $table->foreign('id_wilayah')->references('id_wilayah')->on('Wilayah')->onDelete('set null');
            $table->foreign('id_masjid')->references('id_masjid')->on('Masjid')->onDelete('cascade');
        });

        // Relasi Tabel DataKK ke Wilayah & Masjid
        Schema::table('DataKK', function (Blueprint $table) {
            $table->foreign('id_wilayah')->references('id_wilayah')->on('Wilayah')->onDelete('cascade');
            $table->foreign('id_masjid')->references('id_masjid')->on('Masjid')->onDelete('cascade');
        });

        // Relasi Tabel DataMustahik
        Schema::table('DataMustahik', function (Blueprint $table) {
            $table->foreign('nik_kepala_kk')->references('nik_kepala_kk')->on('DataKK')->onDelete('cascade');
            $table->foreign('id_masjid')->references('id_masjid')->on('Masjid')->onDelete('cascade');
        });

        // Relasi Tabel MustahikHistory
        Schema::table('MustahikHistory', function (Blueprint $table) {
            $table->foreign('id_mustahik')->references('id_mustahik')->on('DataMustahik')->onDelete('cascade');
            $table->foreign('diupdate_oleh')->references('id_user')->on('users')->onDelete('cascade');
        });

        // Relasi Tabel PenerimaanZakat
        Schema::table('PenerimaanZakat', function (Blueprint $table) {
            $table->foreign('id_masjid')->references('id_masjid')->on('Masjid')->onDelete('cascade');
            $table->foreign('petugas_id')->references('id_user')->on('users')->onDelete('cascade');
        });

        // Relasi Tabel DistribusiZakat
        Schema::table('DistribusiZakat', function (Blueprint $table) {
            $table->foreign('id_mustahik')->references('id_mustahik')->on('DataMustahik')->onDelete('cascade');
            $table->foreign('id_masjid')->references('id_masjid')->on('Masjid')->onDelete('cascade');
            $table->foreign('petugas_id')->references('id_user')->on('users')->onDelete('cascade');
        });
    }

    public function down(): void
    {
        // Abaikan fungsi down ini karena kita pakai migrate:fresh jika reset
    }
};