<?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('permanent_employee_salary_payments', function (Blueprint $table) {
            $table->decimal('base_salary', 12, 2)->nullable()->after('salary_month');
            $table->decimal('allowance', 12, 2)->default(0)->after('base_salary');
            $table->decimal('bonus', 12, 2)->default(0)->after('allowance');
            $table->string('status', 20)->default('draft')->after('bonus');
        });

        DB::table('permanent_employee_salary_payments')->orderBy('id')->each(function (object $row): void {
            DB::table('permanent_employee_salary_payments')
                ->where('id', $row->id)
                ->update([
                    'base_salary' => $row->amount,
                    'allowance' => 0,
                    'bonus' => 0,
                    'status' => $row->paid_at !== null ? 'paid' : 'draft',
                ]);
        });

        Schema::table('permanent_employee_salary_payments', function (Blueprint $table) {
            $table->decimal('base_salary', 12, 2)->nullable(false)->change();
            $table->string('payment_method', 20)->nullable()->change();
            $table->timestamp('paid_at')->nullable()->change();
        });
    }

    public function down(): void
    {
        Schema::table('permanent_employee_salary_payments', function (Blueprint $table) {
            $table->dropColumn(['base_salary', 'allowance', 'bonus', 'status']);
            $table->string('payment_method', 20)->nullable(false)->change();
            $table->timestamp('paid_at')->nullable(false)->change();
        });
    }
};
