<?php

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

class AddStatusColumnToPalsuTable 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;
                }

                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()
    {
        $db_connection = $this->getActiveDB();

        foreach ($db_connection as $dbase) {
            Schema::connection($dbase)->table('palsu', function (Blueprint $table) use ($dbase) {
                if (!Schema::connection($dbase)->hasColumn('palsu', 'status')) {
                    $table->unsignedSmallInteger('status')->default(0)->comment('Status value');
                }
            });

            // Update existing rows to have status = 0
            DB::connection($dbase)->table('palsu')
                ->whereNull('status')
                ->update(['status' => 0]);
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $db_connection = $this->getActiveDB();

        foreach ($db_connection as $dbase) {
            Schema::connection($dbase)->table('palsu', function (Blueprint $table) use ($dbase) {
                if (Schema::connection($dbase)->hasColumn('palsu', 'status')) {
                    $table->dropColumn('status');
                }
            });
        }
    }
}
