<?php

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

class CreateMohonAnggotaTable extends Migration
{
    // Dapatkan semua sambungan DB aktif (kecuali mysql7 pusat)
    public function getActiveDB()
    {
        $config_db = array_keys(config("database.connections"));

        $db_connection = array_filter($config_db, function($connection) {
            try {
                if ($connection == 'mysql7') return false; // skip pusat
                DB::connection($connection)->getPdo();
                return true;
            } catch (\Exception $e) {
                return false;
            }
        });

        return $db_connection;
    }

    /**
     * Jalankan migration
     */
    public function up()
    {
        $db_connection = $this->getActiveDB();

        foreach ($db_connection as $dbase) {
            if (!Schema::connection($dbase)->hasTable('mohon_anggota')) {
                Schema::connection($dbase)->create('mohon_anggota', function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->date('tarikh')->nullable();
                    $table->string('nokp', 20)->nullable();
                    $table->string('nama', 100)->nullable();
                    $table->string('status', 50)->default('MENUNGGU OPERASI');
                    $table->text('komen')->nullable();
                    $table->string('teller', 100)->nullable();
                    $table->string('peloperasi', 100)->nullable();
                    $table->dateTime('datetime_pelulus')->nullable();
                    $table->timestamps();
                });
            }
        }
    }

    /**
     * Undur migration
     */
    public function down()
    {
        $db_connection = $this->getActiveDB();

        foreach ($db_connection as $dbase) {
            Schema::connection($dbase)->dropIfExists('mohon_anggota');
        }
    }
}
