<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('tbl_upa', function (Blueprint $table) {
            // Tambah kolom relasi alamat
            $table->unsignedBigInteger('provinsi_id')->nullable()->after('alamat');
            $table->unsignedBigInteger('kota_id')->nullable()->after('provinsi_id');
            $table->unsignedBigInteger('kecamatan_id')->nullable()->after('kota_id');
            $table->unsignedBigInteger('kelurahan_id')->nullable()->after('kecamatan_id');
            
            // Tambah foreign key constraints
            $table->foreign('provinsi_id')->references('id')->on('ref_provinsi')->onDelete('set null');
            $table->foreign('kota_id')->references('id')->on('ref_kota')->onDelete('set null');
            $table->foreign('kecamatan_id')->references('id')->on('ref_kecamatan')->onDelete('set null');
            $table->foreign('kelurahan_id')->references('id')->on('ref_kelurahan')->onDelete('set null');
            
            // Tambah index untuk performance
            $table->index('provinsi_id');
            $table->index('kota_id');
            $table->index('kecamatan_id');
            $table->index('kelurahan_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('tbl_upa', function (Blueprint $table) {
            // Drop foreign key constraints first
            $table->dropForeign(['provinsi_id']);
            $table->dropForeign(['kota_id']);
            $table->dropForeign(['kecamatan_id']);
            $table->dropForeign(['kelurahan_id']);
            
            // Drop columns
            $table->dropColumn(['provinsi_id', 'kota_id', 'kecamatan_id', 'kelurahan_id']);
        });
    }
};
