<?php

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

class AddTHtrAgToSerahbakiTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */

    protected $db_connection;
    public function getActiveDB()
    {
        $config_db = array_keys(config('database.connections'));

        return array_filter($config_db, function ($connection) {
            $config = config("database.connections.$connection");

            // Skip if host is empty
            if (empty($config['host'])) return false;

            try {
                DB::connection($connection)->getPdo();
                return true;
            } catch (\Exception $e) {
                return false;
            }
        });
    }


    public function up()
    {
        $db_connection = $this->getActiveDB();

        $key = array_search('mysql7', $db_connection);

        if ($key !== false) {
            unset($db_connection[$key]);
        }

        foreach ($db_connection as $dbase) {
            Schema::connection($dbase)->table('serahbaki', function (Blueprint $table) use ($dbase) {

                if (!Schema::connection($dbase)->hasColumn('serahbaki', 't_htr_ag')) {
                    $table->date('t_htr_ag')->nullable()->after('aktif');
                }
            });
        }
    }



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

        $key = array_search('mysql7', $db_connection);

        if ($key !== false) {
            unset($db_connection[$key]);
        }

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

