<?php

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

class CreatePampasanTable extends Migration
{
    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) : [];
    }

    public function up()
    {
        foreach ($this->getActiveDB() as $dbase) {
            if (!Schema::connection($dbase)->hasTable('pampasan')) {
                Schema::connection($dbase)->create('pampasan', function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->string('norujukan', 50)->unique()->index();
                    $table->string('baucerno', 30)->index();
                    $table->string('kodcaw', 20)->index();
                    $table->decimal('jumlah_pampasan', 11, 2);

                    if (Schema::getConnection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION) >= '5.7') {
                        $table->json('denominasi')->nullable();
                    } else {
                        $table->longText('denominasi')->nullable();
                    }
                    $table->string('teller', 100);
                    $table->tinyInteger('status')
                    ->default(0)
                    ->comment('0 = belum dituntut, 1 = dituntut');            
                    $table->timestamps();
                });
            }
        }
    }

    public function down()
    {
        foreach ($this->getActiveDB() as $dbase) {
            Schema::connection($dbase)->dropIfExists('pampasan');
        }
    }
}
