<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('leave_requests', function (Blueprint $table) {
            $table->foreignId('manager_approved_by')
                ->nullable()
                ->after('approved_at')
                ->constrained('users')
                ->nullOnDelete();
            $table->timestamp('manager_approved_at')->nullable()->after('manager_approved_by');

            $table->foreignId('hr_approved_by')
                ->nullable()
                ->after('manager_approved_at')
                ->constrained('users')
                ->nullOnDelete();
            $table->timestamp('hr_approved_at')->nullable()->after('hr_approved_by');

            $table->foreignId('rejected_by')
                ->nullable()
                ->after('hr_approved_at')
                ->constrained('users')
                ->nullOnDelete();
            $table->timestamp('rejected_at')->nullable()->after('rejected_by');
        });

        // Backfill for legacy single-step "approved" flows.
        DB::table('leave_requests')
            ->whereNotNull('approved_by')
            ->whereNotNull('approved_at')
            ->update([
                'hr_approved_by' => DB::raw('approved_by'),
                'hr_approved_at' => DB::raw('approved_at'),
            ]);
    }

    public function down(): void
    {
        Schema::table('leave_requests', function (Blueprint $table) {
            $table->dropConstrainedForeignId('manager_approved_by');
            $table->dropColumn('manager_approved_at');

            $table->dropConstrainedForeignId('hr_approved_by');
            $table->dropColumn('hr_approved_at');

            $table->dropConstrainedForeignId('rejected_by');
            $table->dropColumn('rejected_at');
        });
    }
};

