<?php
function throwPollData( $iPollId = null ){
	$oDB = DataBase::getInstance( );
	if( $iPollId === null ) $iPollId = $GLOBALS['config']['current_poll'];
	$aData = $oDB->throwData( DB_POLLS, $iPollId, 'iPollId' );
	if( isset( $aData ) ){
		$sql = 'SELECT `iAnswerId`, `sText`, `iVotes` FROM `' . $oDB->throwTableName( DB_POLLS_ANSWERS ) . '` WHERE `iPollId` = \'' . $iPollId . '\' ORDER BY `iAnswerId`;';
		$aData['aPollAnswers'] = $oDB->executeSQL( $sql, true );
		return $aData;
	} else{
		return null;
	}
}
function throwPoll( $iPollId = null, $sSuffix = null ){
	if( $iPollId === null ) $iPollId = $GLOBALS['config']['current_poll'];
	$aData = throwPollData( $iPollId );
	if( isset( $aData ) ){
		$oTpl = TplParser::getInstance( );
		$aData['bAnswered'] = isset( $_SESSION['poll_voted_' . $iPollId] ) && ( $_SESSION['poll_voted_' . $iPollId] == 1 );
		return $aData;
	}
}
function throwPollVotes( $iPollId = null, $bPercent = true ){
	$oDB = DataBase::getInstance( );
	$oTpl = TplParser::getInstance( );
	if( $iPollId === null ) $iPollId = $GLOBALS['config']['current_poll'];
	$sql = 'SELECT `iAnswerId`, `sText`, `iVotes` FROM `' . $oDB->throwTableName( DB_POLLS_ANSWERS ) . '` WHERE `iPollId` = \'' . $iPollId . '\' ORDER BY `iAnswerId`;';
	$aPollAnswers = $oDB->executeSQL( $sql, true );
	$iVotesSum = 0;
	foreach( $aPollAnswers as $key => $aAnswer ){
		$aPollAnswers[$key]['iAnswerKey'] = $key + 1;
		$iVotesSum+= $aAnswer['iVotes'];
	}
	if( $bPercent ) foreach( $aPollAnswers as $key => $aAnswer ){
		$aPollAnswers[$key]['iVotesPercent'] = round( ( (float)$aAnswer['iVotes'] * 100 ) / $iVotesSum, 0 );
	}
	return $aPollAnswers;
}
function savePollVote( $vote ){
	$oDB = DataBase::getInstance( );
	$sql = 'UPDATE `' . $oDB->throwTableName( DB_POLLS_ANSWERS ) . '` SET `iVotes` = `iVotes`+1 WHERE `iAnswerId` = \'' . $vote . '\';';
	$oDB->executeSQL( $sql );
	$sql = 'SELECT `iPollId` FROM `' . $oDB->throwTableName( DB_POLLS_ANSWERS ) . '` WHERE `iAnswerId` = \'' . $vote . '\';';
	$iPollId = $oDB->executeSQL( $sql, true, DataBase::SINGLE_VALUE );
	if( $iPollId === null ) $iPollId = $oDB->throwLastId( DB_POLLS, 'iPollId' );
	$_SESSION['poll_voted_' . $iPollId] = '1';
}
?>