<?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('intercompany_loans', function (Blueprint $table) {
            // Make date columns nullable (loan not yet disbursed at creation)
            if (Schema::hasColumn('intercompany_loans', 'disbursement_date')) {
                $table->date('disbursement_date')->nullable()->change();
            }
            if (Schema::hasColumn('intercompany_loans', 'maturity_date')) {
                $table->date('maturity_date')->nullable()->change();
            }

            // Add tracking columns if they don't exist
            if (!Schema::hasColumn('intercompany_loans', 'requested_by')) {
                $table->foreignId('requested_by')->nullable()->constrained('users')->onDelete('set null');
            }
            if (!Schema::hasColumn('intercompany_loans', 'rejected_by')) {
                $table->foreignId('rejected_by')->nullable()->constrained('users')->onDelete('set null');
            }
            if (!Schema::hasColumn('intercompany_loans', 'rejected_at')) {
                $table->timestamp('rejected_at')->nullable();
            }
            if (!Schema::hasColumn('intercompany_loans', 'rejection_reason')) {
                $table->text('rejection_reason')->nullable();
            }
            if (!Schema::hasColumn('intercompany_loans', 'due_date')) {
                $table->date('due_date')->nullable();
            }
        });

        // Extend status enum to include 'rejected'
        DB::statement("ALTER TABLE intercompany_loans MODIFY COLUMN status ENUM('pending','approved','active','paid_off','defaulted','cancelled','rejected') NOT NULL DEFAULT 'pending'");
    }

    public function down(): void
    {
        Schema::table('intercompany_loans', function (Blueprint $table) {
            $cols = ['requested_by', 'rejected_by', 'rejected_at', 'rejection_reason', 'due_date'];
            foreach ($cols as $col) {
                if (Schema::hasColumn('intercompany_loans', $col)) {
                    $table->dropColumn($col);
                }
            }
        });
        DB::statement("ALTER TABLE intercompany_loans MODIFY COLUMN status ENUM('pending','approved','active','paid_off','defaulted','cancelled') NOT NULL DEFAULT 'pending'");
    }
};
