<?php

if (! function_exists('setTenant')) {
    function setTenant()
    {
        $user = auth()->user();

        if ($user) {
            Log::info('Setting database connection', [
                'database' => $user->tenant_database,
                'username' => $user->tenant_username,
                'password' => $user->tenant_password
            ]);

            $connection = [
                'driver' => 'mysql',
                'host' => '127.0.0.1',
                'port' => '3306',
                'database' => $user->tenant_database,
                'username' => $user->tenant_username,
                'password' => $user->tenant_password,
            ];

            config(['database.connections.tenant' => $connection]);

            config(['database.default' => 'tenant']);
            DB::purge('tenant');
            DB::reconnect('tenant');

            session(['currentClient' => $user->tenant_database]);

            session(['db_connection' => $connection]);

            Log::info('Current database after setup: ' . DB::connection()->getDatabaseName());
            Log::info('Current default connection: ' . DB::getDefaultConnection());
        }
    }
}