<?php
namespace Clevercherry\Backslash4\Traits;

use Illuminate\Support\Str;
use Clevercherry\Backslash4\Backslash4;
use Illuminate\Support\Facades\DB;
use Clevercherry\Backslash4\Resolvers\TenantConnectionResolver;
use Illuminate\Support\Facades\Config;

trait OnTenant
{
    
    public function getConnection()
    {
        $conn = parent::getConnection();

        $tenant = config('backslash4.tenants-on',0);
        if(!empty($tenant))
        {   //if tenants-on isset
            $tenantKey = \Clevercherry\Backslash4\Backslash4::getTenantKey();
            if(!empty($tenantKey))
            {   //and we have a key
                $database = config('backslash4.tenants.'.$tenantKey.'.database', null);
                
                if(!empty($database))
                {   //and we have a database
                    $conn->disconnect(); 
                    $conn->setDatabaseName($database);
                    Config::set("database.connections.".config('database.default').".database", $database);
                    $conn->reconnect();
                }
            }
        }

        return $conn;
    }
}