<?php
/**
 * class database
 *
 * Description for class database
 *
 * @author:
*/
namespace core;

class database extends \PDO {
	public $query;

	public function __construct($dsn, $username = '', $password = '', $driver_options = array()) {
		parent::__construct($dsn, $username, $password, $driver_options);
		$this->setAttribute(\PDO::ATTR_STATEMENT_CLASS, array('core\\databaseStatement', array($this)));
		
		$this->exec("SET character_set_client=utf8_polish_ci");
		$this->exec("SET character_set_results=utf8_polish_ci");
		$this->exec("SET character_set_connection=utf8_polish_ci");
		$this->exec("SET collation_connection=utf8_polish_ci");
		$this->exec("SET CHARSET utf8_polish_ci");
		$this->exec("SET NAMES utf8 COLLATE utf8_polish_ci");
	}

	public function prepare($statement, $driver_options = array()) {
		$this->query = $statement;
		return parent::prepare($statement, $driver_options = array());
	}

	public static function newGuid() {
		global $__database;

		$query = $__database->query("SELECT UUID() AS `guid`");
		if($record = $query->fetch(\PDO::FETCH_ASSOC)) {
			return $record["guid"];
		}

		if(function_exists("com_create_guid")) {
			return com_create_guid();
		} else {
			mt_srand((double)microtime()*10000);
			$CharId = strtoupper(md5(uniqid(rand(), true)));
			$Separator = chr(45);
			
			return substr($CharId, 0, 8).$Separator.substr($CharId, 8, 4).$Separator.substr($CharId,12, 4).$Separator.substr($CharId,16, 4).$Separator.substr($CharId,20,12);
		}
	}

	public static function newPresentationCode() {
		global $__database;

		$code = "000000";
		$isSet = false;

		while(!$isSet) {
			$code = rand(100000, 999999);

			$query = $__database->prepare("SELECT `presentation_id` FROM `presentations` WHERE `accessKey`=:code");
			$query->bindParam(":code", $code);
			$query->execute();
			if(!$record = $query->fetch()) {
				$isSet = true;
			}
		}

		return $code;
	}
}
?>