<?php

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

return new class extends Migration {
    public function up(): void
    {
        Schema::table('employee_loans', function (Blueprint $table) {
            // Pengecekan aman agar tidak error jika kolom sudah ada
            if (!Schema::hasColumn('employee_loans', 'loan_number')) {
                $table->string('loan_number', 50)->unique()->after('employee_id');
            }
            if (!Schema::hasColumn('employee_loans', 'loan_amount')) {
                $table->decimal('loan_amount', 15, 2)->default(0)->after('loan_number');
            }
            if (!Schema::hasColumn('employee_loans', 'installment_amount')) {
                $table->decimal('installment_amount', 15, 2)->default(0)->after('loan_amount');
            }
            if (!Schema::hasColumn('employee_loans', 'remaining_balance')) {
                $table->decimal('remaining_balance', 15, 2)->default(0)->after('installment_amount');
            }
            if (!Schema::hasColumn('employee_loans', 'loan_date')) {
                $table->date('loan_date')->nullable()->after('remaining_balance');
            }
            if (!Schema::hasColumn('employee_loans', 'notes')) {
                $table->text('notes')->nullable()->after('loan_date');
            }
            if (!Schema::hasColumn('employee_loans', 'status')) {
                $table->enum('status', ['active', 'paid_off'])->default('active')->after('notes');
            }
            if (!Schema::hasColumn('employee_loans', 'created_by')) {
                $table->bigInteger('created_by')->unsigned()->nullable()->after('status');
            }
        });
    }

    public function down(): void
    {
        Schema::table('employee_loans', function (Blueprint $table) {
            $table->dropColumn([
                'loan_number', 'loan_amount', 'installment_amount', 
                'remaining_balance', 'loan_date', 'notes', 'status', 'created_by'
            ]);
        });
    }
};