<?php

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

/**
 * Persist customer billing details on the user row.
 *
 * Why on users (not just payments): the payments table already snapshots
 * billing_* per transaction (frozen at checkout for EU invoice
 * compliance) — but that means a customer has to retype their company,
 * VAT, tax ID and address on EVERY purchase. Putting the same fields on
 * the user lets the checkout form pre-fill from the last entered values,
 * while the payments row keeps its own frozen copy for the invoice PDF.
 *
 * Existing CheckoutController already reads from $user->billing_* as the
 * form default, so the read path is wired — this migration just gives it
 * something to read.
 */
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('id');
            }
            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_email')) {
                $t->string('billing_email', 255)->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_email'] as $col) {
                if (Schema::hasColumn('users', $col)) {
                    $t->dropColumn($col);
                }
            }
        });
    }
};
