<?php

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

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

    /**
     *
     * @var object $db_connection
     */

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

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

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

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

        foreach ($db_connection as $dbase) {

            $columns = ['ujrah', 'onepercent'];

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

            Schema::connection($dbase)->table('tebus', function (Blueprint $table) use ($columns_not_exist) {

                array_walk($columns_not_exist, function ($column) use ($table) {
                    $table->decimal($column, 9, 2);
                });

            });
        };
    }

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

        foreach ($db_connection as $dbase) {

            $columns = ['ujrah', 'onepercent'];

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

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