<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.X
 *	LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Real Estate Agency
 *	DOMAIN: gevimmo.com
 *	FILE: RLPOLLS.CLASS.PHP
 *
 *	The software is a commercial product delivered under single, non-exclusive,
 *	non-transferable license for one domain or IP address. Therefore distribution,
 *	sale or transfer of the file in whole or in part without permission of Flynax
 *	respective owners is considered to be illegal and breach of Flynax License End
 *	User Agreement.
 *
 *	You are not allowed to remove this information from the file without permission
 *	of Flynax respective owners.
 *
 *	Flynax Classifieds Software 2017 |  All copyrights reserved.
 *
 *	http://www.flynax.com/
 *
 ******************************************************************************/

class rlPolls extends reefless
{
	/**
	* @var content code for polls blocks
	*/
	public $content = 'global $rlSmarty;
		$polls_array = unserialize(\'{$polls_replace}\');
		$count_max = count($polls_array);
		$index = rand(0, $count_max-1);
		shuffle($polls_array);
		$poll=$polls_array[$index];
		$polls = explode(",", $_COOKIE["polls"]);
		$poll_items = $poll["items"];
		if ( in_array( $poll["ID"], $polls ) )
		{
			$poll["voted"] = true;
		}
		foreach ($poll_items as $key => $pValue)
		{
			$poll_items[$key]["percent"] = floor(((int)$poll_items[$key]["Votes"]*100)/$poll["total"]);
		}
		$poll["items"] = $poll_items;
		$rlSmarty->assign("poll", $poll);
		$rlSmarty->display(RL_PLUGINS."polls".RL_DS."polls.block.tpl");';

	/**
	* @var content code for empty polls blocks
	*/
	public $empty_content = 'global $rlSmarty;
		$poll = "";
		$rlSmarty->assign("poll", $poll);
		$rlSmarty->display(RL_PLUGINS."polls".RL_DS."polls.block.tpl");';

	/**
	* get poll data by poll id
	*
	* @param int $poll_id - poll id
	*
	* @return array - poll data
	**/
	public function get($poll_id = false)
	{
		/* get poll */
		$where = $poll_id == 'all' ? array('Random' => 1, 'Status' => 'active') : array('ID' => $poll_id, 'Status' => 'active');

		$poll = $this->fetch(array('ID', 'ID` AS `Key', 'Random'), $where, null, null, 'polls');
		foreach($poll as $key => $val) {
			$where_sum = $poll_id != 'all' ? "`Poll_ID` = '{$poll_id}'" : "`Poll_ID` = '{$poll[$key]['ID']}'";

			if (!empty($poll[$key])) {
				foreach ($GLOBALS['languages'] as $lKey => $lVal) {
					$poll[$key]['name'][$lKey] = str_replace("'", "&#39;", $GLOBALS['rlLang']->replaceLangKeys('polls+name+'.$poll[$key]['Key'], null, null, $lKey));
				}

				/* get poll's items */
				$poll_items = $this->fetch(array('ID` AS `Key', 'Votes', 'Color'), array('Poll_ID' => $poll[$key]['ID']), "ORDER BY `ID`", null, 'polls_items');
				foreach ($poll_items as $pKey => $pVal) {
					foreach ($GLOBALS['languages'] as $lKey => $lVal) {
						$poll_items[$pKey]['name'][$lKey] = str_replace("'", "&#39;", $GLOBALS['rlLang']->replaceLangKeys('polls_items+name+'.$poll_items[$pKey]['Key'], null, null, $lKey));
					}
				}
				$total_votes = $this->getRow("SELECT SUM(`Votes`) AS `sum` FROM `" . RL_DBPREFIX . "polls_items` WHERE {$where_sum} LIMIT 1");

				foreach ($poll_items as $key2 => $pValue) {
					$poll_items[$key2]["percent"] = floor(((int)$poll_items[$key2]["Votes"]*100)/$poll[$key]["total"]);
				}

				$total_votes = $poll[$key]['total'] = $total_votes['sum'];
				$poll[$key]['items'] = $poll_items;
			}
		}
		return $poll;
	}

	/**
	* vote
	*
	* @param string $out - ajax response by reference
	*
	* @hook ajaxRequest
	*
	**/
	public function vote($out)
	{
		global $out;

		$poll_id = (int) $_REQUEST['item'];
		$vote_id = (int) $_REQUEST['vote'];

		if (!$poll_id || !$vote_id) {
			return false;
		}

		$out['status'] = 'ok';
		$out['results'] = $this->doVote($poll_id, $vote_id);
	}
	
	/**
	* vote
	*
	* @package xAjax
	*
	* @param int $poll_id - poll id
	* @param string $vote_id - vote id
	*
	**/
	public function ajaxVote($poll_id = false, $vote_id = false)
	{
		global $_response;

		if (!$poll_id || !$vote_id) {
			$_response->script("$('.poll-container input[type=button]').val('{$GLOBALS['lang']['vote']}');");
			return $_response;
		}

		$poll_id = (int) $poll_id;
		$vote_id = (int) $vote_id;
		
		$poll = $this->doVote($poll_id, $vote_id);

		$GLOBALS['rlSmarty']->assign('poll', $poll);
		$GLOBALS['rlSmarty']->assign('lang_site', RL_LANG_CODE);

		$tpl = RL_PLUGINS . 'polls' . RL_DS . 'results.tpl';
		$_response->assign('poll_results_'.$poll_id, 'innerHTML', $GLOBALS['rlSmarty']->fetch($tpl, null, null, false));
		$_response->script("
			printMessage('notice', '{$GLOBALS['lang']['notice_vote_accepted']}');
			$('#poll_container_{$poll_id} input[type=button]').val('{$GLOBALS['lang']['vote']}');
			$('#poll_container_{$poll_id} div.poll-total > b').text('{$poll['total']}');
			$('#poll_container_{$poll_id} div.poll-results-nav').hide();
			$('#poll_container_{$poll_id} div.poll-nav span.link').trigger('click');
			$('#poll_container_{$poll_id} div.poll-nav').slideUp();
		");

		return $_response;
	}

	/**
	* do vote
	*
	* @param int $poll_id - poll id
	* @param string $vote_id - vote id
	*
	* @return array - poll data
	*
	**/
	private function doVote($poll_id = false, $vote_id = false)
	{
		$polls = explode(',', $_COOKIE['polls']);
		$random = $this->getOne('Random', "`ID` = {$poll_id}", 'polls');

		if (!in_array($poll_id, $polls)) {
			$this->query("UPDATE `" .RL_DBPREFIX . "polls_items` SET `Votes` = `Votes` + 1 WHERE `Poll_ID` = '{$poll_id}' AND `ID` = '{$vote_id}'");

			/* save vote in cookie */
			$polls[] = $poll_id;
			$value = implode(',', $polls);
			$expire_time = time()+2592000;

            if (method_exists($this, 'createCookie')) {
                $this->createCookie('polls', $value, $expire_time);
            } else {
                setcookie('polls', $value, $expire_time, $GLOBALS['domain_info']['path'], $GLOBALS['domain_info']['domain']);
            }
		}

		$polls = serialize($this->get($random ? 'all' : $poll_id));
		$content = str_replace('{$polls_replace}', $polls, $this->content);
		$GLOBALS['rlValid']->sql($content);

		/* edit poll block */
		$postfix = $random ? '' : '_' . $poll_id;
		$this->query("UPDATE `" . RL_DBPREFIX . "blocks` SET `Content` = '{$content}' WHERE `Key` = 'polls{$postfix}' LIMIT 1");

		$array_polls = $this->get($poll_id);

		$poll = $array_polls[0];
		$poll_items = $poll['items'];

		$poll['voted'] = true;
		foreach ($poll_items as $key => $pValue) {
			$poll_items[$key]['percent'] = floor(((int)$poll_items[$key]['Votes']*100)/$poll['total']);
		}
		$poll['items'] = $poll_items;

		unset($array_polls, $poll_items);

		return $poll;
	}
	
	/**
	* delete poll
	*
	* @package xAjax
	*
	* @param int $poll_id - poll id
	*
	**/
	public function ajaxDeletePoll( $poll_id = false )
	{
		global $_response;

		// check admin session expire
		if ($this->checkSessionExpire() === false) {
			$redirect_url = RL_URL_HOME . ADMIN ."/index.php";
			$redirect_url .= empty($_SERVER['QUERY_STRING']) ? '?session_expired' : '?'. $_SERVER['QUERY_STRING'] .'&session_expired';
			$_response->redirect($redirect_url);
		}

		$poll_id = (int) $poll_id;
		if (!$poll_id) {
			return $_response;
		}

		$random = $this->getOne('Random', "`ID` = {$poll_id}", 'polls');

		// delete poll
		$this->query("DELETE FROM `". RL_DBPREFIX ."polls` WHERE `ID` = '{$poll_id}' LIMIT 1");

		// delete poll items
		$items = $this->fetch(array('ID'), array('Poll_ID' => $poll_id), null, null, 'polls_items');
		$this->query("DELETE FROM `". RL_DBPREFIX ."polls_items` WHERE `Poll_ID` = '{$poll_id}'");

		// delete poll land's phrases
		foreach ($items as $key => $value) {
			$this->query("DELETE FROM `". RL_DBPREFIX ."lang_keys` WHERE `Key` = 'polls_items+name+{$items[$key]['ID']}' AND `Plugin` = 'polls'");
		}

		if ($random) {
			$tmp_polls = $this->get('all');
			if (!empty($tmp_polls)) {
				$polls = serialize($tmp_polls);
				$content = str_replace('{$polls_replace}', $polls, $this->content);
			} else {
				$content = $empty_content;
			}
			$GLOBALS['rlValid']->sql($content);
		
			$this->query("UPDATE `". RL_DBPREFIX ."blocks` SET `Content` = '{$content}' WHERE `Key` = 'polls' AND `Plugin` = 'polls' LIMIT 1");
		} else {
			$this->query("DELETE FROM `". RL_DBPREFIX ."blocks` WHERE `Key` = 'polls_{$poll_id}' AND `Plugin` = 'polls' LIMIT 1");
			$this->query("DELETE FROM `". RL_DBPREFIX ."lang_keys` WHERE `Key` = 'blocks+name+polls_{$poll_id}' AND `Plugin` = 'polls'");
		}
		$_response->script("pollsGrid.init();");

		$notice = $GLOBALS['lang']['item_deleted'];

		$_response->assign('notice_block', 'innerHTML', $notice);
		$_response->script("$('#notice_obj').fadeIn('slow');");

		return $_response;
	}
}