<?php

class OSKUserModel {
	/*
	 * Database handle
	 */
	private $dbh = null;

	public function __construct()
	{
		$conf = $GLOBALS['conf'];
		$dbpass = OSKKeyMaster::getInstance()->getKey("outspark.{$conf['read_dbuser']}");

		try {
			$this->dbh = new PDO("mysql:host=$conf[read_dbhost];dbname=$conf[user_dbname]", $conf['read_dbuser'], $dbpass);
			$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$this->dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
		} catch (PDOException $e) {
			$GLOBALS['logger']->crit($e->getMessage());
			throw new Exception($e->getMessage());
		}
	}

	public function getUserInfo($userid)
	{
		if (!$userid) {
			return false;
		}

		try {
			$stmt = $this->dbh->prepare("select userid, sparkid, password, status, verified, unix_timestamp(created) as created, internal
										 from users
										 where (sparkid = ? or email = ?)");
			if( $stmt->execute(array($userid, $userid)) ) {
				$userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
				if ($userInfo) {
					$GLOBALS['logger']->debug("{$userid}: found (".__FUNCTION__.")");
				} else {
					$GLOBALS['logger']->debug("{$userid}: not found (".__FUNCTION__.")");
					return false;
				}
			} else {
				$GLOBALS['logger']->debug("{$userid}: query failed (".__FUNCTION__.")");
				return false;
			}
		} catch (PDOException $e) {
			$GLOBALS['logger']->err($e->getMessage() . " (".__FUNCTION__.")");
			return false;
		}

		return $userInfo;
	}


	public function getUserInfoByUID($userid)
	{
		if (!$userid) {
			return false;
		}

		try {
			$stmt = $this->dbh->prepare("select userid, sparkid, password, status, verified, unix_timestamp(created) as created, internal
										 from users
										 where userid = ?");
			if( $stmt->execute(array($userid)) ) {
				$userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
				if ($userInfo) {
					$GLOBALS['logger']->debug("{$userid}: found (".__FUNCTION__.")");
				} else {
					$GLOBALS['logger']->debug("{$userid}: not found (".__FUNCTION__.")");
					return false;
				}
			} else {
				$GLOBALS['logger']->debug("{$userid}: query failed (".__FUNCTION__.")");
				return false;
			}
		} catch (PDOException $e) {
			$GLOBALS['logger']->err($e->getMessage() . " (".__FUNCTION__.")");
			return false;
		}

		return $userInfo;
	}

	public function __destruct()
	{
		$this->dbh = null;
	}
}

?>
