<?php
function throwPolls( ){
	$oDB = DataBase::getInstance( );
	return $oDB->throwFileArray( DB_POLLS );
}
function savePoll( $aForm ){
	$oDB = DataBase::getInstance( );
	if( isset( $aForm['iPollId'] ) && is_numeric( $aForm['iPollId'] ) ){
		$sParam = 'iPollId';
	} else{
		$sParam = null;
		$aForm['sDate'] = date( 'Y-m-d' );
	}
	$aForm = changeMassTxt( $aForm, '' );
	if( $sParam ){
		$aAnsw = throwPollData( $aForm['iPollId'] );
		$aAnsw = $aAnsw['aPollAnswers'];
		foreach( $aAnsw as $aAnswer ){
			$aAnswers[$aAnswer['iAnswerId']] = $aAnswer;
		}
	} else{
		$aAnswers = null;
	}
	if( $sParam ){
		$oDB->update( DB_POLLS, array_intersect_key( $aForm, Array( 'sDate' => true, 'sQuestion' => true ) ), Array( $sParam => $aForm[$sParam] ) );
	} else{
		$aForm['iPollId'] = $oDB->save( DB_POLLS, $aForm, null, 'sort' );
		activatePoll( $aForm['iPollId'] );
	}
	$aAnswerIds = Array( );
	if( isset( $aForm['aAnswers'] ) ){
		foreach( $aForm['aAnswers'] as $aAnswer['iAnswerId'] => $aAnswer['sText'] ){
			$aAnswer['iPollId'] = $aForm['iPollId'];
			if( !empty( $aAnswer['sText'] ) ){
				if( $aAnswers[$aAnswer['iAnswerId']] ){
					$oDB->update( DB_POLLS_ANSWERS, Array( 'sText' => $aAnswer['sText'] ), Array( 'iAnswerId' => $aAnswer['iAnswerId'], 'iPollId' => $aForm['iPollId'] ) );
					$aAnswerIds[] = $aAnswer['iAnswerId'];
				} else{
					$aAnswer['iVotes'] = 0;
					unset( $aAnswer['iAnswerId'] );
					$aAnswerIds[] = $oDB->save( DB_POLLS_ANSWERS, $aAnswer );
				}
			}
		}
	}
	$oDB->executeSQL( 'DELETE FROM `' . $oDB->throwTableName( DB_POLLS_ANSWERS ) . '` WHERE ( `iAnswerId` NOT IN ( \'' . implode( '\', \'', $aAnswerIds ) . '\' ) ) AND ( `iPollId` = ' . intval( $aForm['iPollId'] ) . ' )' );
	return $aForm['iPollId'];
}
function deletePoll( $iPoll ){
	$oDB = DataBase::getInstance( );
	$oDB->deleteInFile( DB_POLLS, $iPoll, 'iPollId' );
	$oDB->deleteInFile( DB_POLLS_ANSWERS, $iPoll, 'iPollId' );
	// jeśli usuwana ankieta była aktualna - aktywować najnowszą
	if( $GLOBALS['config']['current_poll'] == $iPoll ) activatePoll( $oDB->throwLastId( DB_POLLS, 'iPollId' ) );
}
function activatePoll( $iPoll ){
	saveVariables( Array( 'current_poll' => $iPoll ), DB_CONFIG_LANG );
}
?>