<?php

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

class AddSettlementFieldsToEmployeeDismissals extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('employee_dismissals', function (Blueprint $table) {
            // Check if columns don't exist before adding
            if (!Schema::hasColumn('employee_dismissals', 'requires_settlement')) {
                $table->boolean('requires_settlement')->default(false);
            }
            
            if (!Schema::hasColumn('employee_dismissals', 'completion_comments')) {
                $table->text('completion_comments')->nullable();
            }
            
            if (!Schema::hasColumn('employee_dismissals', 'completed_by')) {
                $table->unsignedBigInteger('completed_by')->nullable();
            }
            
            if (!Schema::hasColumn('employee_dismissals', 'completed_at')) {
                $table->timestamp('completed_at')->nullable();
            }
            
            // Add foreign key constraint if it doesn't exist
            if (!Schema::hasColumn('employee_dismissals', 'completed_by')) {
                $table->foreign('completed_by')->references('id')->on('users')->onDelete('set null');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('employee_dismissals', function (Blueprint $table) {
            // Drop foreign key first
            if (Schema::hasColumn('employee_dismissals', 'completed_by')) {
                $table->dropForeign(['completed_by']);
            }
            
            // Drop columns
            $table->dropColumn([
                'requires_settlement',
                'completion_comments',
                'completed_by',
                'completed_at'
            ]);
        });
    }
}