<?php
/**
 * WebEngine CMS
 * https://webenginecms.org/
 * 
 * @version 1.2.0
 * @author Lautaro Angelico <http://lautaroangelico.com/>
 * @copyright (c) 2013-2019 Lautaro Angelico, All Rights Reserved
 * 
 * Licensed under the MIT license
 * http://opensource.org/licenses/MIT
 */

class Connection {
	
	public static function Database($database='', $realm=null) {
		if(class_exists('NexoraRealm') && NexoraRealm::enabled()) {
			if(!in_array($database, array('MuOnline', 'Me_MuOnline', 'Platform'), true)) return;

			$connection = NexoraRealm::connection($database, $realm);
			$db = new dB(
				$connection['host'],
				$connection['port'],
				$connection['database'],
				$connection['username'],
				$connection['password'],
				$connection['driver']
			);

			if($db->dead) {
				if(defined('WEBENGINE_DATABASE_ERRORLOG') && check_value($db->error)) {
					@error_log(
						'['.date('Y/m/d H:i:s').'] [Nexora realm '.$connection['realm'].'] '.$db->error."\r\n",
						3,
						WEBENGINE_DATABASE_ERRORLOG
					);
				}
				throw new Exception('No fue posible conectar con el reino '.$connection['label'].'.');
			}

			return $db;
		}

		switch($database) {
			case 'MuOnline':
				$db = new dB(self::_config('SQL_DB_HOST'), self::_config('SQL_DB_PORT'), self::_config('SQL_DB_NAME'), self::_config('SQL_DB_USER'), self::_config('SQL_DB_PASS'), self::_config('SQL_PDO_DRIVER'));
				if($db->dead) {
					throw new Exception('Connection to database failed.');
				}
				return $db;
			case 'Me_MuOnline':
				if(!self::_config('SQL_USE_2_DB')) return self::Database('MuOnline');
				$db = new dB(self::_config('SQL_DB_HOST'), self::_config('SQL_DB_PORT'), self::_config('SQL_DB_2_NAME'), self::_config('SQL_DB_USER'), self::_config('SQL_DB_PASS'), self::_config('SQL_PDO_DRIVER'));
				if($db->dead) {
					throw new Exception('Connection to database failed.');
				}
				return $db;
			default:
				return;
		}
	}
	
	private static function _config($config) {
		$webengineConfig = webengineConfigs();
		if(!is_array($webengineConfig)) return;
		if(!array_key_exists($config, $webengineConfig)) return;
		return $webengineConfig[$config];
	}
	
}
