<?php

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

/**
 * Adds invoicing + EU-compliant tax/billing fields.
 *
 * Why all in one migration:
 * - The new columns are co-dependent: tax_rate on plans is meaningless
 *   without subtotal/tax_amount on payments to record the breakdown, and
 *   the billing_* snapshot fields on payments are what the invoice PDF
 *   needs to render. Splitting them across multiple files would leave
 *   half-broken intermediate states.
 *
 * Every add is gated on `Schema::hasColumn()` so customers who manually
 * back-port columns aren't blocked at migrate time — important on update
 * wizard runs.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('payments')) {
            Schema::table('payments', function (Blueprint $t) {
                // Invoice number — human-readable, unique. NULL until first PDF
                // generation so historical Stripe payments don't all collide on
                // a default value when the migration runs.
                if (!Schema::hasColumn('payments', 'invoice_number')) {
                    $t->string('invoice_number', 32)->nullable()->unique()->after('id');
                }
                // Path to the rendered PDF in storage (relative to disk root).
                // We regenerate on demand if missing, but cache the path so
                // repeat downloads don't re-render.
                if (!Schema::hasColumn('payments', 'invoice_pdf_path')) {
                    $t->string('invoice_pdf_path', 255)->nullable()->after('invoice_number');
                }
                // Tax breakdown — kept on the payment row (not derived) because
                // tax_rate on the plan can change later; the invoice must reflect
                // the rate AS-OF the purchase.
                if (!Schema::hasColumn('payments', 'subtotal_amount')) {
                    $t->decimal('subtotal_amount', 12, 2)->nullable()->after('original_amount');
                }
                if (!Schema::hasColumn('payments', 'tax_rate')) {
                    $t->decimal('tax_rate', 5, 2)->nullable()->after('subtotal_amount');
                }
                if (!Schema::hasColumn('payments', 'tax_amount')) {
                    $t->decimal('tax_amount', 12, 2)->nullable()->after('tax_rate');
                }
                // Customer billing snapshot — frozen at checkout so later
                // profile edits don't rewrite past invoices (EU compliance).
                if (!Schema::hasColumn('payments', 'billing_company')) {
                    $t->string('billing_company', 255)->nullable()->after('tax_amount');
                }
                if (!Schema::hasColumn('payments', 'billing_tax_id')) {
                    $t->string('billing_tax_id', 64)->nullable()->after('billing_company');
                }
                if (!Schema::hasColumn('payments', 'billing_vat_number')) {
                    $t->string('billing_vat_number', 64)->nullable()->after('billing_tax_id');
                }
                if (!Schema::hasColumn('payments', 'billing_address')) {
                    // Stored as TEXT (newline-delimited) rather than JSON so the
                    // PDF can interpolate the full block in one shot.
                    $t->text('billing_address')->nullable()->after('billing_vat_number');
                }
                if (!Schema::hasColumn('payments', 'billing_email')) {
                    $t->string('billing_email', 255)->nullable()->after('billing_address');
                }
            });
        }

        if (Schema::hasTable('plans')) {
            Schema::table('plans', function (Blueprint $t) {
                // Per-plan tax rate (overrides system default). Stored as %, so
                // 19.00 = 19% VAT. Default 0 means "use system default rate".
                if (!Schema::hasColumn('plans', 'tax_rate')) {
                    $t->decimal('tax_rate', 5, 2)->default(0)->after('yearly_price');
                }
                // If true, the plan price ALREADY INCLUDES tax — we display
                // the breakdown but don't add it on top. False = price is net
                // and tax adds to total. Most EU plans are inclusive.
                if (!Schema::hasColumn('plans', 'tax_inclusive')) {
                    $t->boolean('tax_inclusive')->default(false)->after('tax_rate');
                }
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasTable('payments')) {
            Schema::table('payments', function (Blueprint $t) {
                foreach ([
                    'invoice_number', 'invoice_pdf_path',
                    'subtotal_amount', 'tax_rate', 'tax_amount',
                    'billing_company', 'billing_tax_id', 'billing_vat_number',
                    'billing_address', 'billing_email',
                ] as $col) {
                    if (Schema::hasColumn('payments', $col)) {
                        $t->dropColumn($col);
                    }
                }
            });
        }
        if (Schema::hasTable('plans')) {
            Schema::table('plans', function (Blueprint $t) {
                foreach (['tax_rate', 'tax_inclusive'] as $col) {
                    if (Schema::hasColumn('plans', $col)) {
                        $t->dropColumn($col);
                    }
                }
            });
        }
    }
};
