<?php

// -----------------------------------------------------------------------
// This file is part of aroundme
// 
// Copyright (C) 2003, 2005 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.org
// 
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option) any
// later version.
// 
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
// -----------------------------------------------------------------------



class Poll {
	// CLASS FUNCTIONS
	// Poll
	// getPoll
	// getOptions
	// answerSummary
	// pollUserCurrentVote
	// getPolls
	// updatePoll
	// insertPoll
	// deletePoll
	// insertOption
	// updateOption
	// deleteOption
	// pollUserVoteHistory
	// getUserPollParticipation
	// updateAnswer
	// getPollCount
	
	

	// Poll --------------------------------------------------------------------
	// the constuctor
	// tom calthrop - 24th Feb 2004
	//
	function Poll($db, $section_id, $date) {
		$this->db = $db;
		$this->section_id = $section_id;
		$this->date = $date;
	}//EO Poll

	
	
	
	// getPoll --------------------------------------------------------------------
	// returns a single record from the DB
	// tom calthrop - 24th Feb 2004
	//
	function getPoll() {

		$query = "
			SELECT p.*
			FROM " . $this->db->prefix . "_poll p
			WHERE 
			p.poll_id=" . $this->poll_id
		;

		$result = $this->db->Execute($query);
	
		if (isset($result->fields)) {
		
			$temp = $result->fields;

			$temp['display_poll_start_datetime'] = $this->date->formatDate($temp['poll_start_datetime']);
			$temp['display_poll_end_datetime'] = $this->date->formatDate($temp['poll_end_datetime']);

			$temp['options'] = $this->getOptions();
			$temp['total_votes'] = $this->total_votes;

		
			//get percentages
			foreach($temp['options'] as $key => $i):
				$temp['options'][$key]['percent'] = 0;
	
				if ($i['votes'] > 0) {
				    $percent = round((100/$this->total_votes)* $i['votes']);
					$temp['options'][$key]['percent'] = $percent;
				}
			endforeach;
			
			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=getPoll class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getPoll
	
	
	
	// getOptions --------------------------------------------------------------------
	// get the options for the poll
	// tom calthrop - 24th Feb 2004
	//
	function getOptions() {
		$total_votes = 0;

		$query = "
			SELECT option_id, option_body, option_create_datetime 
			FROM " . $this->db->prefix . "_poll_option 
			WHERE 
			poll_id=" . $this->poll_id
		;
		
		$result = $this->db->Execute($query);
	
		if (isset($result->fields)) {
		
			$temp = array();

			while (!$result->EOF) {
				$temp1 =  $result->fields;
				$temp1['votes'] = $this->answerSummary($temp1['option_id']);
				$total_votes = $total_votes + $temp1['votes'];
				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();

			$this->total_votes = $total_votes;
			return $temp;
		}
		else {
			$error_info = "function=getOptions class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getOptions

	
		
	// answerSummary --------------------------------------------------------------------
	// returns count of the ansers received per poll option given
	// tom calthrop - 24th Feb 2004
	//
	function answerSummary($option_id) {
		$query = "
			SELECT count(answer_id) as total 
			FROM " . $this->db->prefix . "_poll_answer 
			WHERE
			current_answer=1 and
			option_id=" . $option_id
		;
		
		$result = $this->db->Execute($query);
	
		if (isset($result->fields)) {
			$temp = $result->fields;
			$result->Close();
			return $temp['total'];
		}
		else {
			$error_info = "function=answerSummary class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO answerSummary
	
	
	
	// pollUserCurrentVote --------------------------------------------------------------------
	// returns the current vote for a user
	// tom calthrop - 24th Feb 2004
	//
	function pollUserCurrentVote($user_id = null) {
		
		if (empty($user_id)) {
		    $user_id = $this->user_id;
		}
		
		$query = "
			SELECT answer_id, poll_id, current_answer, answer_create_datetime, 
			option_id 
			FROM " . $this->db->prefix . "_poll_answer 
			WHERE 
			user_id=" . $user_id . " and
			poll_id=" . $this->poll_id . " and
			current_answer=1
			order by answer_create_datetime"
		;
		$result = $this->db->Execute($query);
	
		if (isset($result->fields)) {
			$temp = $result->fields;
			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=pollUserCurrentVote class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO pollUserCurrentVote

	
	
	// getPolls --------------------------------------------------------------------
	// returns multiple rows of polls
	// tom calthrop - 24th Feb 2004
	//
	function getPolls() {
		
		$query = "
			SELECT poll_id, section_item_id, poll_question, poll_anon, vote_required, 
			poll_create_datetime, poll_start_datetime, poll_end_datetime 
			FROM " . $this->db->prefix . "_poll 
			WHERE 
			section_id=" . $this->section_id . " AND "
		;
		
		if (isset($this->section_item_id)) {
		    $query .= "section_item_id=" . $this->section_item_id . " AND ";
		}
		
		if (isset($this->before_start_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->before_start_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "poll_start_datetime <= " . $datetime . " AND ";
		}

		if (isset($this->after_start_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->after_start_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "poll_start_datetime >= " . $datetime . " AND ";
		}
		
		if (isset($this->before_end_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->before_end_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "poll_end_datetime <= " . $datetime . " AND ";
		}

		if (isset($this->after_end_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->after_end_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "poll_end_datetime >= " . $datetime . " AND ";
		}
		
		if (isset($this->poll_ids)) {
			$poll_ids = "";
			foreach($this->poll_ids as $key => $i):
				$poll_ids .= $i;
				if (count($this->poll_ids) > $key+1) {
				    $poll_ids .=",";
				}
			endforeach;
			$query .= "poll_id in (" . $poll_ids . ") AND ";
		}
		
		$query .="1=1 ";
		
		if (isset($this->order_by)) {
		    $query .= "order by " . $this->order_by;
		}
		else {
			$query .= "order by poll_question";
		}
		
		if (isset($this->limit)) {
			$result = $this->db->SelectLimit($query, $this->limit);
		} else {
			$result = $this->db->Execute($query);
		}
		
		$result = $this->db->Execute($query);
	
		if (isset($result->fields)) {

			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;

				$temp1['display_poll_start_datetime'] = $this->date->formatDate($temp1['poll_start_datetime'], 1);
				$temp1['display_poll_end_datetime'] = $this->date->formatDate($temp1['poll_end_datetime'], 1);
				
				$this->poll_id = $temp1['poll_id'];
				
				$temp1['options'] = $this->getOptions();
				$temp1['total_votes'] = $this->total_votes;
	
			
				//get percentages
				if (isset($temp1['options'])) {
					
					foreach($temp1['options'] as $key => $i):
						$temp1['options'][$key]['percent'] = 0;
			
						if ($i['votes'] > 0) {
						    $percent = round((100/$this->total_votes)* $i['votes']);
							$temp1['options'][$key]['percent'] = $percent;
						}
					endforeach;
				}
			
				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=getPolls class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getPolls




	// updatePoll --------------------------------------------------------------------
	// updates a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function updatePoll($data) {

		$poll_start_datetime = $_POST['start_year']."-".$_POST['start_month']."-".$_POST['start_day']." ".$_POST['start_hour'].":".$_POST['start_minute'].":00";

		$poll_end_datetime = $_POST['end_year']."-".$_POST['end_month']."-".$_POST['end_day']." ".$_POST['end_hour'].":".$_POST['end_minute'].":00";

		if (isset($data['poll_anon'])) {
			$poll_anon = 1;
		}
		else {
			$poll_anon = "null";
		}

		if (isset($data['vote_required'])) {
			$vote_required = 1;
		}
		else {
			$vote_required = "null";
		}

		$query = "
			UPDATE " . $this->db->prefix . "_poll SET
			poll_question='" . $data['poll_question'] . "',
			poll_start_datetime='" . $poll_start_datetime . "',
			poll_end_datetime ='" . $poll_end_datetime . "',
			poll_anon=" . $poll_anon . ",
			vote_required=" . $vote_required . "
			WHERE poll_id=" . $this->poll_id
		;

		$result = $this->db->Execute($query);
	
		if (empty($result)) {
			$error_info = "function=updatePoll class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO updatePoll



	// insertPoll --------------------------------------------------------------------
	// inserts a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function insertPoll($data) {

		$datetime = date("Y-m-d H:i:s");
		$datetime = $this->db->DBDate($datetime);

		$poll_start_datetime = $_POST['start_year']."-".$_POST['start_month']."-".$_POST['start_day']." ".$_POST['start_hour'].":".$_POST['start_minute'].":00";

		$poll_end_datetime = $_POST['end_year']."-".$_POST['end_month']."-".$_POST['end_day']." ".$_POST['end_hour'].":".$_POST['end_minute'].":00";

		if (isset($data['poll_anon'])) {
			$poll_anon = $data['poll_anon'];
		}
		else {
			$poll_anon = "null";
		}

		if (isset($data['vote_required'])) {
			$vote_required = $data['vote_required'];
		}
		else {
			$vote_required = "null";
		}

		$query = "
			INSERT INTO " . $this->db->prefix . "_poll
			(section_id, section_item_id, poll_question, poll_start_datetime, poll_end_datetime, poll_anon,
			poll_create_datetime, user_id, vote_required
			) VALUES (
			" . $this->section_id . ",
			" . $this->section_item_id . ",
			'" . $data['poll_question'] . "',
			'" . $poll_start_datetime . "',
			'" . $poll_end_datetime . "',
			" . $poll_anon . ",
			" . $datetime . ",
			" . $this->user_id . ",
			" . $vote_required . "
			)"
		;
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
				$query = "
					SELECT poll_id  
					FROM " . $this->db->prefix . "_poll 
					WHERE 
					section_id=" . $this->section_id . " AND 
					section_item_id=" . $this->section_item_id . " AND 
					poll_create_datetime=" . $datetime 
				;
		
				$result = $this->db->SelectLimit($query, 1);
				
				if (isset($result->fields['poll_id'])) {
					$this->poll_id = $result->fields['poll_id'];
				}
				else {
					$error_info = "function=insertPoll class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
					$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
				}
			}
			else {
			$error_info = "function=insertPoll class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO insertPoll


	
	// deletePoll --------------------------------------------------------------------
	// inserts a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function deletePoll() {

		$query = "
			DELETE FROM " . $this->db->prefix . "_poll
			WHERE 
			poll_id=" .  $this->poll_id
		;

		$result = $this->db->Execute($query);
		
		if (empty($result->fields)) {
			$error_info = "function=deletePoll class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO deletePoll

	
	
	// insertOption --------------------------------------------------------------------
	// inserts a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function insertOption($option_body) {
		$datetime = date("Y-m-d H:i:s");
		$datetime = $this->db->DBDate($datetime);

		$query = "
			INSERT INTO " . $this->db->prefix . "_poll_option
			(poll_id, option_body, option_create_datetime, user_id)
			VALUES (
			" . $this->poll_id . ",
			'" . $option_body . "',
			" . $datetime . ",
			" . $this->user_id . "
			)"
		;
		
		$result = $this->db->Execute($query);
		
		if (empty($result->fields)) {
			$error_info = "function=insertOption class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
		
	}//EO insertOption
	
	
	
	// updateOption --------------------------------------------------------------------
	// updates a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function updateOption($option_id, $option_body) {
		$datetime = date("Y-m-d H:i:s");
		$datetime = $this->db->DBDate($datetime);

		$query = "
			UPDATE " . $this->db->prefix . "_poll_option SET
			option_body='" . $option_body . "',
			option_edit_datetime=" . $datetime . ",
			user_id=" . $this->user_id . "
			WHERE
			option_id=" . $option_id
		;
		
		$result = $this->db->Execute($query);
		
		if (empty($result->fields)) {
			$error_info = "function=updateOption class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO updateOption



	// deleteOption --------------------------------------------------------------------
	// deletes a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function deleteOption($option_id) {

		$query = "
			DELETE FROM " . $this->db->prefix . "_poll_option
			WHERE
			option_id=" . $option_id
		;
		
		$result = $this->db->Execute($query);
		
		if (empty($result->fields)) {
			$error_info = "function=deleteOption class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO deleteOption




	// pollUserVoteHistory --------------------------------------------------------------------
	// returns the history of the votes given by a user to a poll (used in forum subjects)
	// tom calthrop - 24th Feb 2004
	//
	function pollUserVoteHistory($user_id) {

		//display a poll
		$query = "
			SELECT pa.answer_create_datetime, o.option_body
			FROM " . $this->db->prefix . "_poll_answer pa, " . $this->db->prefix . "_poll_option o
			where
			pa.option_id = o.option_id and
			pa.user_id=" . $user_id . " and
			pa.poll_id=" . $this->poll_id . "
			order by pa.answer_create_datetime"
		;
		
		$result = $this->db->Execute($query);
	
		if (isset($result->fields)) {

			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;

				$temp1['answer_create_datetime'] = $this->date->formatDate($temp1['answer_create_datetime'],1);

				array_push($temp, $temp1);
				$result->MoveNext();
			}
			$result->Close();
			
			return $temp;
		}
		else {
			$error_info = "function=pollUserVoteHistory class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
		
	}//EO pollUserVoteHistory
	
	
	
	// getUserPollParticipation --------------------------------------------------------------------
	// returns the history of the polls and votes by a given user (for user publishing page)
	// tom calthrop - 11th December 2004
	//
	function getUserPollParticipation () {
		
		$query = "
			SELECT p.poll_question, pa.answer_create_datetime, o.option_body
			FROM " . $this->db->prefix . "_poll p, 
			" . $this->db->prefix . "_poll_option o, 
			" . $this->db->prefix . "_poll_answer pa
			WHERE
			p.poll_id=o.poll_id and
			o.option_id=pa.option_id and
			pa.user_id=" . $this->user_id . " and
			pa.current_answer=1 and
			p.poll_anon is null
			order by pa.answer_create_datetime desc"
		;
		
		$result = $this->db->Execute($query);
	
		if (isset($result->fields)) {
			$temp = array();
	
			while (!$result->EOF) {
				$temp1 = $result->fields;
				$temp1['answer_create_datetime'] = $this->date->formatDate($temp1['answer_create_datetime']);
	
				array_push($temp, $temp1);
				$result->MoveNext();
			}
	
			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=getUserPollParticipation class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getUserPollParticipation

	
	
	
	// updateAnswer --------------------------------------------------------------------
	// update defaults and insert new answer
	// tom calthrop - 28th December 2004
	//
	function updateAnswer($option_id) {
		$query = "
			UPDATE " . $this->db->prefix . "_poll_answer SET
			current_answer=null
			WHERE
			poll_id=" . $this->poll_id . " AND 
			user_id=" . $this->user_id
		;
		
		$result = $this->db->Execute($query);

		//insert record
		$datetime = date("Y-m-d H:i:s");
		$datetime = $this->db->DBDate($datetime);

		$query = "
			INSERT INTO " . $this->db->prefix . "_poll_answer (
			user_id, 
			poll_id, 
			option_id, 
			current_answer, 
			answer_create_datetime
			) VALUES (
			" . $this->user_id . ",
			" . $this->poll_id . ",
			" . $option_id . ",
			1,
			" . $datetime . "
			)"
		;
		
		$result = $this->db->Execute($query);
	}//EO updateAnswer
	
	
	
	
	// getPollCount --------------------------------------------------------------------
	// will get the coutn of unique page names
	// tom calthrop - 27th December 2004
	//
	function getPollCount() {
		$query = "
			SELECT poll_id as total 
			FROM " . $this->db->prefix . "_poll 
			WHERE 
			section_id=" . $this->section_id . " and 
			section_item_id=" . $this->section_item_id . " and "
		;
		
		if (isset($this->user_id)) {
		    $query .= "user_id=" . $this->user_id . " and ";
		}
		
		$query .= "1=1 ";
		
		$result = $this->db->Execute($query);

		if (isset($result->fields['total'])) {
			return $result->fields['total'];
		}
		else {
			$error_info = "function=getPollCount class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}

	}//EO getPollCount

}
?>
