<?php
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

if (!function_exists('changeTenantEnv')) {
    function changeTenantEnv(array $data = [])
    {
        if (count($data) === 0) {
            return false;
        }

        DB::disconnect('tenant');

        $config = Config::get('database.connections.tenant');

        $prefix = config('app.db_own_prefix', env('DB_OWN_PREFIX', ''));

        foreach ($data as $key => $value) {

            if ($key === 'database') {

                if (!str_starts_with($value, $prefix)) {
                    $config[$key] = $prefix . $value;
                } else {
                    $config[$key] = $value;
                }
            }
        }

        Config::set('database.connections.tenant', $config);

        DB::purge('tenant');

        return true;
    }
}
