<?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('profit_sweep_transactions', function (Blueprint $table) {
            if (!Schema::hasColumn('profit_sweep_transactions', 'year_month')) {
                $table->string('year_month')->nullable()->after('sweep_date'); // Format: '2024-04'
            }
            if (!Schema::hasColumn('profit_sweep_transactions', 'month_revenue')) {
                $table->decimal('month_revenue', 15, 2)->default(0)->after('subsidiary_profit');
            }
            if (!Schema::hasColumn('profit_sweep_transactions', 'month_expenses')) {
                $table->decimal('month_expenses', 15, 2)->default(0)->after('month_revenue');
            }
            if (!Schema::hasColumn('profit_sweep_transactions', 'month_net_profit')) {
                $table->decimal('month_net_profit', 15, 2)->default(0)->after('month_expenses');
            }
            if (!Schema::hasColumn('profit_sweep_transactions', 'is_no_profit_month')) {
                $table->boolean('is_no_profit_month')->default(false)->after('month_net_profit');
            }
        });

        // Add index for year_month
        Schema::table('profit_sweep_transactions', function (Blueprint $table) {
            try {
                $table->index('year_month');
            } catch (\Exception $e) {}
        });
    }

    public function down(): void
    {
        Schema::table('profit_sweep_transactions', function (Blueprint $table) {
            $table->dropIndex(['year_month']);
            $table->dropColumn([
                'year_month',
                'month_revenue',
                'month_expenses',
                'month_net_profit',
                'is_no_profit_month'
            ]);
        });
    }
};
