<?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('invoice_items', function (Blueprint $table) {
            // gross_total = quantity x unit_price, before any discount.
            // line_total remains the post-discount chargeable amount that VAT is
            // computed on, so the invoice header total still equals the sum of items.
            $table->decimal('gross_total', 14, 2)->nullable()->after('line_total');
            $table->enum('discount_type', ['fixed', 'percentage'])->nullable()->after('gross_total');
            $table->decimal('discount_value', 12, 2)->default(0)->after('discount_type');
            $table->decimal('discount_amount', 14, 2)->default(0)->after('discount_value');
        });

        // Backfill existing rows: no discount was ever possible before this column
        // existed, so gross_total equals the current line_total exactly.
        DB::table('invoice_items')->update(['gross_total' => DB::raw('line_total')]);

        Schema::table('invoice_items', function (Blueprint $table) {
            $table->decimal('gross_total', 14, 2)->nullable(false)->default(0)->change();
        });
    }

    public function down(): void
    {
        Schema::table('invoice_items', function (Blueprint $table) {
            $table->dropColumn(['gross_total', 'discount_type', 'discount_value', 'discount_amount']);
        });
    }
};
