<?php

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

class AddFinanceIntegrationSettings extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('finance_settings')) {
            Schema::create('finance_settings', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->unsignedInteger('school_id')->nullable();
                $table->string('base_url')->nullable();
                $table->string('api_key')->nullable();
                $table->string('webhook_secret')->nullable();
                $table->boolean('enabled')->default(false);
                $table->timestamps();

                $table->unique('school_id', 'finance_settings_school_unique');
            });
        }

        if (Schema::hasTable('users')) {
            Schema::table('users', function (Blueprint $table) {
                if (!Schema::hasColumn('users', 'finance_balance')) {
                    $table->decimal('finance_balance', 15, 2)->nullable();
                }

                if (!Schema::hasColumn('users', 'finance_status')) {
                    $table->string('finance_status', 50)->nullable();
                }

                if (!Schema::hasColumn('users', 'last_payment_at')) {
                    $table->timestamp('last_payment_at')->nullable();
                }
            });
        }
    }

    public function down()
    {
        if (Schema::hasTable('users')) {
            Schema::table('users', function (Blueprint $table) {
                if (Schema::hasColumn('users', 'last_payment_at')) {
                    $table->dropColumn('last_payment_at');
                }

                if (Schema::hasColumn('users', 'finance_status')) {
                    $table->dropColumn('finance_status');
                }

                if (Schema::hasColumn('users', 'finance_balance')) {
                    $table->dropColumn('finance_balance');
                }
            });
        }

        Schema::dropIfExists('finance_settings');
    }
}
