<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('tenants', function (Blueprint $table) {
            $table->boolean('auto_billing_enabled')->default(false)->after('settings')->index();
            $table->string('auto_billing_cycle')->nullable()->after('auto_billing_enabled');
            $table->string('auto_billing_method')->nullable()->after('auto_billing_cycle');
            $table->string('auto_billing_reference')->nullable()->after('auto_billing_method');
            $table->string('auto_billing_status')->default('inactive')->after('auto_billing_reference')->index();
            $table->timestamp('auto_billing_started_at')->nullable()->after('auto_billing_status');
            $table->timestamp('auto_billing_last_charged_at')->nullable()->after('auto_billing_started_at');
            $table->timestamp('auto_billing_next_charge_at')->nullable()->after('auto_billing_last_charged_at')->index();
            $table->timestamp('auto_billing_failed_at')->nullable()->after('auto_billing_next_charge_at');
            $table->text('auto_billing_failure_reason')->nullable()->after('auto_billing_failed_at');
        });

        Schema::table('tenant_payments', function (Blueprint $table) {
            $table->string('payment_channel')->default('manual')->after('billing_cycle')->index();
            $table->boolean('is_auto_billed')->default(false)->after('payment_channel')->index();
            $table->string('gateway_reference')->nullable()->after('reference')->index();
            $table->timestamp('processed_at')->nullable()->after('approved_at');
        });
    }

    public function down(): void
    {
        Schema::table('tenant_payments', function (Blueprint $table) {
            $table->dropColumn([
                'payment_channel',
                'is_auto_billed',
                'gateway_reference',
                'processed_at',
            ]);
        });

        Schema::table('tenants', function (Blueprint $table) {
            $table->dropColumn([
                'auto_billing_enabled',
                'auto_billing_cycle',
                'auto_billing_method',
                'auto_billing_reference',
                'auto_billing_status',
                'auto_billing_started_at',
                'auto_billing_last_charged_at',
                'auto_billing_next_charge_at',
                'auto_billing_failed_at',
                'auto_billing_failure_reason',
            ]);
        });
    }
};
