<?php

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

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        if (Schema::hasTable('expenses')) {
            Schema::table('expenses', function (Blueprint $table) {
                if (!Schema::hasColumn('expenses', 'expense_number')) {
                    $table->string('expense_number')->nullable()->unique()->after('id');
                }
                if (!Schema::hasColumn('expenses', 'title')) {
                    $table->string('title')->nullable()->after('expense_category');
                }
                if (!Schema::hasColumn('expenses', 'approved_by')) {
                    // Add approved_by with FK to users if users table exists, else as plain bigint
                    if (Schema::hasTable('users')) {
                        $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete()->after('status');
                    } else {
                        $table->unsignedBigInteger('approved_by')->nullable()->after('status');
                    }
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if (Schema::hasTable('expenses')) {
            Schema::table('expenses', function (Blueprint $table) {
                if (Schema::hasColumn('expenses', 'approved_by')) {
                    // Drop FK if exists then column
                    try {
                        $table->dropForeign(['approved_by']);
                    } catch (\Throwable $e) {
                        // Ignore if no foreign key exists
                    }
                    $table->dropColumn('approved_by');
                }
                if (Schema::hasColumn('expenses', 'title')) {
                    $table->dropColumn('title');
                }
                if (Schema::hasColumn('expenses', 'expense_number')) {
                    $table->dropUnique('expenses_expense_number_unique');
                    $table->dropColumn('expense_number');
                }
            });
        }
    }
};