<?php

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

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

    public function getActiveDB(){
        $config_db = array_keys(config("database.connections"));

        $db_connection = array_filter($config_db,function($connection){
            try{
                if($connection == 'mysql7')
                    return false;

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

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

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

                $isTunggakanUjrah = Schema::connection($dbase)->hasColumn('imbang_duga_backup', 'ujrah');
                $isTunggakkanOnePercent = Schema::connection($dbase)->hasColumn('imbang_duga_backup', 'onepercent');

                if (! $isTunggakanUjrah) {
                    $table->decimal('ujrah', 9, 2);
                }

                if (! $isTunggakkanOnePercent) {
                    $table->decimal('onepercent', 9, 2);
                }
            });
        }
    }

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

        foreach($db_connection as $dbase){
            $columns = ['onepercent', 'ujrah'];

            $columns_exist = array_filter($columns,function($column) use($dbase){
                return Schema::connection($dbase)->hasColumn('imbang_duga_backup', $column);
            });

            Schema::connection($dbase)->table('imbang_duga_backup', function(Blueprint $table) use($columns_exist){
                foreach($columns_exist as $column){
                        $table->dropColumn($column);
                }
            });
        }
    }
}
