masterConnection === null) { $config = Config::getMasterDatabaseConfig(); $this->masterConnection = new mysqli( $config['host'], $config['user'], $config['password'], $config['database'] ); if ($this->masterConnection->connect_error) { throw new Exception("Error conexión master DB: " . $this->masterConnection->connect_error); } $this->masterConnection->set_charset($config['charset']); } return $this->masterConnection; } /** * Obtiene conexión para empresa específica */ public function getConnection($empresaId) { if (!isset($this->connections[$empresaId])) { $config = Config::getDatabaseConfig($empresaId); $mysqli = new mysqli( $config['host'], $config['user'], $config['password'], $config['database'] ); if ($mysqli->connect_error) { throw new Exception("Error conexión empresa $empresaId: " . $mysqli->connect_error); } $mysqli->set_charset($config['charset']); $this->connections[$empresaId] = $mysqli; } return $this->connections[$empresaId]; } /** * Establece empresaId actual basado en usuario en sesión */ public function setEmpresaByUser($userId) { $this->currentEmpresaId = Config::getEmpresaIdByUserId($userId); if (!$this->currentEmpresaId) { throw new Exception("No se pudo determinar empresaId para usuario: $userId"); } // Almacenar en sesión para uso posterior $_SESSION['empresaId'] = $this->currentEmpresaId; } /** * Obtiene conexión para empresa actual */ public function getCurrentConnection() { if (!$this->currentEmpresaId) { throw new Exception("No hay empresaId establecido"); } return $this->getConnection($this->currentEmpresaId); } /** * Cierra todas las conexiones */ public function closeAll() { if ($this->masterConnection) { $this->masterConnection->close(); } foreach ($this->connections as $connection) { $connection->close(); } $this->connections = []; $this->masterConnection = null; } // Destructor para asegurar cierre de conexiones public function __destruct() { $this->closeAll(); } } ?>