<?php

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

class AddAgreementPrintedAtToPampasanTable extends Migration
{
    /**
     * Get active database connections
     */
    private function getActiveDB(): array
    {
        $config_db = array_keys(config("database.connections"));

        $db_connection = array_filter($config_db, function($connection) {
            try {
                if ($connection === 'mysql7') return false; // ikut pattern sedia ada
                DB::connection($connection)->select('SELECT 1');
                return true;
            } catch (\Exception $e) {
                return false;
            }
        });
        return $db_connection ? array_values($db_connection) : [];
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        foreach ($this->getActiveDB() as $dbase) {
            Schema::connection($dbase)->table('pampasan', function (Blueprint $table) use ($dbase) {
                if (!Schema::connection($dbase)->hasColumn('pampasan', 'agreement_printed_at')) {
                    $table->timestamp('agreement_printed_at')->nullable()->comment('Timestamp when agreement was printed');
                }
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        foreach ($this->getActiveDB() as $dbase) {
            Schema::connection($dbase)->table('pampasan', function (Blueprint $table) use ($dbase) {
                if (Schema::connection($dbase)->hasColumn('pampasan', 'agreement_printed_at')) {
                    $table->dropColumn('agreement_printed_at');
                }
            });
        }
    }
}
