<?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('facturas', function (Blueprint $table) {
            $table->decimal('subtotal', 10, 2)->default(0)->after('user_id');
            $table->decimal('impuesto_total', 10, 2)->default(0)->after('subtotal');
            $table->json('impuestos_desglose')->nullable()->after('impuesto_total');
        });

        DB::table('facturas')->update([
            'subtotal' => DB::raw('subtotal_gravado + subtotal_exento'),
            'impuesto_total' => DB::raw('iva_monto'),
        ]);

        Schema::table('facturas', function (Blueprint $table) {
            $table->dropColumn(['subtotal_gravado', 'subtotal_exento', 'iva_porcentaje', 'iva_monto']);
        });
    }

    public function down(): void
    {
        Schema::table('facturas', function (Blueprint $table) {
            $table->decimal('subtotal_gravado', 10, 2)->default(0);
            $table->decimal('subtotal_exento', 10, 2)->default(0);
            $table->decimal('iva_porcentaje', 5, 2)->default(0);
            $table->decimal('iva_monto', 10, 2)->default(0);
            $table->dropColumn(['subtotal', 'impuesto_total', 'impuestos_desglose']);
        });
    }
};
