<?php

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

/**
 * Adds reusable billing profile fields to users so customers don't have
 * to re-type their VAT/Tax-ID/address on every purchase.
 *
 * At checkout, these values are COPIED onto the payment row (snapshot)
 * so subsequent profile edits never rewrite past invoices.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (!Schema::hasTable('users')) return;

        Schema::table('users', function (Blueprint $t) {
            if (!Schema::hasColumn('users', 'billing_company'))    $t->string('billing_company', 255)->nullable()->after('phone');
            if (!Schema::hasColumn('users', 'billing_tax_id'))     $t->string('billing_tax_id', 64)->nullable()->after('billing_company');
            if (!Schema::hasColumn('users', 'billing_vat_number')) $t->string('billing_vat_number', 64)->nullable()->after('billing_tax_id');
            if (!Schema::hasColumn('users', 'billing_address'))    $t->text('billing_address')->nullable()->after('billing_vat_number');
            if (!Schema::hasColumn('users', 'billing_country'))    $t->string('billing_country', 2)->nullable()->after('billing_address');
        });
    }

    public function down(): void
    {
        if (!Schema::hasTable('users')) return;
        Schema::table('users', function (Blueprint $t) {
            foreach (['billing_company','billing_tax_id','billing_vat_number','billing_address','billing_country'] as $col) {
                if (Schema::hasColumn('users', $col)) $t->dropColumn($col);
            }
        });
    }
};
