<?php
// database/migrations/2024_01_01_000000_add_category_id_to_commission_rates_table.php

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

return new class extends Migration
{
    public function up()
    {
        Schema::table('commission_rates', function (Blueprint $table) {
            // Add category_id column (nullable foreign key)
            $table->unsignedBigInteger('category_id')->nullable()->after('commission_id');

            // Add foreign key constraint
            $table->foreign('category_id')
                  ->references('category_id')
                  ->on('occupation_categories')
                  ->onDelete('set null');

            // Index for better performance
            $table->index(['category_id', 'is_active']);
        });
    }

    public function down()
    {
        Schema::table('commission_rates', function (Blueprint $table) {
            // Drop foreign key first
            $table->dropForeign(['category_id']);

            // Drop index
            $table->dropIndex(['category_id', 'is_active']);

            // Drop column
            $table->dropColumn('category_id');
        });
    }
};
