<?php

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

class ExtendFinanceSettingsUiFields extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('finance_settings')) {
            return;
        }

        Schema::table('finance_settings', function (Blueprint $table) {
            if (!Schema::hasColumn('finance_settings', 'wp_base_url')) {
                $table->string('wp_base_url')->nullable()->after('school_id');
            }

            if (!Schema::hasColumn('finance_settings', 'api_url')) {
                $table->string('api_url')->nullable()->after('base_url');
            }

            if (!Schema::hasColumn('finance_settings', 'payment_url')) {
                $table->string('payment_url')->nullable()->after('api_key');
            }

            if (!Schema::hasColumn('finance_settings', 'last_sync_at')) {
                $table->timestamp('last_sync_at')->nullable()->after('enabled');
            }

            if (!Schema::hasColumn('finance_settings', 'last_webhook_at')) {
                $table->timestamp('last_webhook_at')->nullable()->after('last_sync_at');
            }

            if (!Schema::hasColumn('finance_settings', 'last_connection_status')) {
                $table->string('last_connection_status', 30)->nullable()->after('last_webhook_at');
            }

            if (!Schema::hasColumn('finance_settings', 'last_connection_message')) {
                $table->string('last_connection_message')->nullable()->after('last_connection_status');
            }

            if (!Schema::hasColumn('finance_settings', 'last_response_time_ms')) {
                $table->unsignedInteger('last_response_time_ms')->nullable()->after('last_connection_message');
            }
        });
    }

    public function down()
    {
        if (!Schema::hasTable('finance_settings')) {
            return;
        }

        Schema::table('finance_settings', function (Blueprint $table) {
            foreach ([
                'last_response_time_ms',
                'last_connection_message',
                'last_connection_status',
                'last_webhook_at',
                'last_sync_at',
                'payment_url',
                'api_url',
                'wp_base_url',
            ] as $column) {
                if (Schema::hasColumn('finance_settings', $column)) {
                    $table->dropColumn($column);
                }
            }
        });
    }
}
