<?php

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

if (! function_exists('changeEnv')) {
    function changeEnv($data = array()){
         /* 'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST_SECOND', '127.0.0.1'),
            'port' => env('DB_PORT_SECOND', '3306'),
            'database' => env('DB_DATABASE_SECOND', 'forge'),
            'username' => env('DB_USERNAME_SECOND', 'forge'),
            'password' => env('DB_PASSWORD_SECOND', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            */
        if(count($data) > 0){
            DB::disconnect('tenant');
            // Loop through given data
            $config = Config::get('database.connections.tenant');
            foreach((array)$data as $key => $value){
                // Loop through .env-data
                foreach($config as $config_key => $config_value){

                    // Check, if new key fits the actual .env-key
                    if($config_key == $key){
                        // If yes, overwrite it with the new one
                        $config[$config_key] = $value;
                        if ($key == 'database') {
                            $config[$config_key] = config('app.db_own_prefix').$value;
                        }
                    }
                   config(['database.connections.tenant'=> $config]);
                   DB::purge('tenant');

                    //else {
                     //   // If not, keep the old one
                     //   $config[$config_key] = $config_value;
                   // }
                }
            }
            return true;
        } else {
            return false;
        }
    }
}


if (! function_exists('logs')) {
    function logs($data = array()){
        //
    }
}
