<?php
namespace EasyChat\Library;

class DB {
	private $adaptor;

	public function __construct($adaptor, $hostname, $username, $password, $database, $port = NULL) {
		$this->assertRuntimeSupportsAdaptor($adaptor);
		require_once(__DIR__ . '/db/' . $adaptor . '.php');
		
		$class = 'DB\\' . $adaptor;

		if (class_exists($class)) {
			$this->adaptor = new $class($hostname, $username, $password, $database, $port);
		} else {
			throw new \Exception('Error: Could not load database adaptor ' . $adaptor . '!');
		}
	}

	public function query($sql, $params = array()) {
		return $this->adaptor->query($sql, $params);
	}

	public function escape($value) {
		return $this->adaptor->escape($value);
	}

	public function countAffected() {
		return $this->adaptor->countAffected();
	}

	public function getLastId() {
		return $this->adaptor->getLastId();
	}
	
	public function connected() {
		return $this->adaptor->connected();
	}

	public function getRawConnection() {
		return $this->adaptor->getRawConnection();
	}

	



	public function close() {
		if (method_exists($this->adaptor, 'close')) {
			$this->adaptor->close();
		}
	}

	public function reconnect() {
		if (method_exists($this->adaptor, 'reconnect')) {
			$this->adaptor->reconnect();
		}
	}

	public function setSessionTimezoneOffset($offset) {
		if (!preg_match('/^[+-](?:0[0-9]|1[0-4]):[0-5][0-9]$/D', (string)$offset)) {
			throw new \InvalidArgumentException('Invalid database timezone offset.');
		}
		if (method_exists($this->adaptor, 'setSessionTimezoneOffset')) {
			$this->adaptor->setSessionTimezoneOffset((string)$offset);
			return true;
		}
		return false;
	}

	




	private function assertRuntimeSupportsAdaptor($adaptor) {
		$normalized = strtolower(trim((string)$adaptor));
		if ($normalized === 'mysqli' && !class_exists('\\mysqli')) {
			throw new \RuntimeException(
				'PHP runtime does not provide the mysqli extension. '
				. 'mysqlnd alone is not enough; select a PHP CLI binary with mysqli enabled.'
			);
		}
		if ($normalized === 'mpdo'
			&& (!class_exists('\\PDO') || !in_array('mysql', \PDO::getAvailableDrivers(), true))) {
			throw new \RuntimeException(
				'PHP runtime does not provide the pdo_mysql extension required by the configured database adaptor.'
			);
		}
		if ($normalized === 'mysql' && !function_exists('mysql_connect')) {
			throw new \RuntimeException(
				'The legacy mysql extension is unavailable. It was removed from PHP 7; use the mysqli adaptor.'
			);
		}
	}
}
