<?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('users', function (Blueprint $t) {
            if (! Schema::hasColumn('users', 'internal_margin_pct')) {
                $t->decimal('internal_margin_pct', 5, 2)->nullable()->after('hourly_rate');
            }
        });

        Schema::table('work_orders', function (Blueprint $t) {
            if (! Schema::hasColumn('work_orders', 'override_margin_pct')) {
                $t->decimal('override_margin_pct', 5, 2)->nullable()->after('discount_pct');
            }
        });

        Schema::table('wo_works', function (Blueprint $t) {
            if (! Schema::hasColumn('wo_works', 'salary_base')) {
                // Frozen at save time so changing margin later doesn't rewrite history
                $t->decimal('salary_base', 10, 2)->nullable()->after('total');
            }
            if (! Schema::hasColumn('wo_works', 'applied_margin_pct')) {
                // The exact margin % used when salary_base was computed
                $t->decimal('applied_margin_pct', 5, 2)->nullable()->after('salary_base');
            }
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $t) {
            if (Schema::hasColumn('users', 'internal_margin_pct')) $t->dropColumn('internal_margin_pct');
        });
        Schema::table('work_orders', function (Blueprint $t) {
            if (Schema::hasColumn('work_orders', 'override_margin_pct')) $t->dropColumn('override_margin_pct');
        });
        Schema::table('wo_works', function (Blueprint $t) {
            foreach (['salary_base', 'applied_margin_pct'] as $col) {
                if (Schema::hasColumn('wo_works', $col)) $t->dropColumn($col);
            }
        });
    }
};
