<?php
ob_start();
if(!(is_readable(realpath(dirname(__FILE__).'/../').'/include/includesroutines.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__).'/../').'/include/includesroutines.inc');
} else {
	include_once(realpath(dirname(__FILE__).'/../').'/include/includesroutines.inc');
}

if(!(is_readable(realpath(dirname(__FILE__).'/../').'/include/pagination.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__).'/../').'/include/pagination.inc');
} else {
	include_once(realpath(dirname(__FILE__).'/../').'/include/pagination.inc');
}
session_write_close();
checkUserAndRedirectToLogin();
checkLanguage();
$cn = db_connect();
$lng = ( isset($_REQUEST['lang']) ? 'lang='.$_REQUEST['lang'] : '');
$lngid = db_getLanguageID($cn, getLanguage());
$contlng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguagecontent']);
$contlngid = $_SESSION['user_idlanguagecontent'];
$onpage = getSetting('page', 'polls.pagesize', 20);
$default_order_column = getCookieForPage('order_column','user_name'); 
$default_order_val = getCookieForPage('order_val','asc');

$usr_arr = GetUserIDs();
if (!isUserAdmin() && !db_isUserAdminToPolls($cn, $usr_arr)){ 
	ob_end_flush();
	exit;
}

$order_column = isset( $_GET[ "order_column" ] ) ? $_GET[ "order_column" ] : $default_order_column;
$order_val = isset( $_GET[ "order_val" ] ) ? $_GET[ "order_val" ] : $default_order_val;
setCookieForPage("order_column", $order_column);
setCookieForPage("order_val", $order_val);
$page = isset( $_REQUEST[ "page" ] ) ? $_REQUEST[ "page" ] : 1;
$search = isset( $_REQUEST[ "search" ] ) ? $_REQUEST[ "search" ] : "";
$searchinobj = array();
$searchinobjlast = array();

$u_ids = GetUserIDs();
$url = getCurPageURL('service/');
$hideheader = (isset($_COOKIE['hideheader']) ?  $_COOKIE['hideheader'] : 0);
$urlWO = getCurPageURLWO('service/');
mb_internal_encoding('UTF-8');
$st = '';
if (isset($_REQUEST['search']) && strlen(trim($_REQUEST['search']))>0) {
	$st = mysqli_real_escape_string($cn, mysqli_real_escape_string($cn, trim( mb_strtolower($_REQUEST['search'],'UTF-8'))));
}

$uiid = (isset($_REQUEST['sessionhash']) ? $_REQUEST['sessionhash'] : "e").
(isset($_REQUEST['finished']) ? $_REQUEST['finished'] : "e").(isset($_REQUEST['search']) ? $_REQUEST['search'] : "e").
(isset($_REQUEST['order_column']) ? $_REQUEST['order_column'] : "e").(isset($_REQUEST['order_val']) ? $_REQUEST['order_val'] : "e").
(isset($_REQUEST['notfinished']) ? $_REQUEST['notfinished'] : "e" ).
(isset($_REQUEST['searchinobjlast']) ? md5(serialize($_REQUEST['searchinobjlast'])) : 'e').(isset($_REQUEST['searchinobj']) ? md5(serialize($_REQUEST['searchinobj'])) : 'e');

if (isset($_SESSION['adminpollrespondents_p_'.$uiid.$page]) 
	&& ($page == 1 || isset($_SESSION['adminpollrespondents_p_'.$uiid.($page-1)]))
	&& (isset($_SESSION['adminpollrespondents_total'.$uiid]) && $page+1 <= $_SESSION['adminpollrespondents_total'.$uiid] && isset($_SESSION['adminpollrespondents_p_'.$uiid.($page+1)]))){
	session_write_close();
	db_disconnect($cn);
	ob_end_flush();
	exit;
}
	$ids = implode(",", $u_ids);

	$finished = NULL;
	if (!isset($_REQUEST['finished']) && isset($_REQUEST['notfinished']))
		$finished = 'no';
	if (!isset($_REQUEST['notfinished']) && isset($_REQUEST['finished']))
		$finished = 'yes';
	db_getPollRespondetsListAdmin($cn, (isset($_REQUEST['idpolltype']) ? $_REQUEST['idpolltype'] : NULL), (isset($_REQUEST['skproject']) ? $_REQUEST['skproject'] : NULL),  (isset($_REQUEST['skbranch']) ? $_REQUEST['skbranch'] : NULL), $usr_arr, $contlngid, $finished );

	if (isset($_REQUEST['searchinobj'])) {
		$searchinobj = $_REQUEST['searchinobj'];
	}
	
	if (isset($_REQUEST['searchinobjlast'])) {
		$searchinobjlast = $_REQUEST['searchinobjlast'];
		$searchinobj = array_merge($searchinobj, $searchinobjlast);
	}	
	$size=sizeof($searchinobj);
	if ( $size > 0 ) {
		$q_st = " DROP TEMPORARY TABLE IF EXISTS `o_usein`;";
		db_runQuery($cn, $q_st);

		$q_st = " CREATE TEMPORARY TABLE `o_usein` (
					`idobject` BIGINT NOT NULL,
					`o_guid` VARCHAR(40) NOT NULL,
					`skbranch`  INT NOT NULL,
					PRIMARY KEY (`idobject`,`skbranch`)
				)ENGINE=MEMORY;";
		db_runQuery($cn, $q_st);
		$il = 0;
		$ir = 0;
		$size=sizeof($searchinobj);
		for($i=0; $i<$size; $i++){
			$q_st = "INSERT IGNORE INTO `o_usein` SELECT `idobject`, `o_guid`, `skbranch` FROM `objects` WHERE `idobject` in (".$searchinobj[$i].");";
			db_runQuery($cn, $q_st);
			$q_st = "INSERT IGNORE INTO `o_usein` SELECT obj1.`idobject`, obj1.`o_guid`, obj1.`skbranch` FROM `objects` as obj1,  `objects` as obj2
					WHERE  obj2.`idobject` = ".$searchinobj[$i]." AND obj1.`parent_idobject` =  obj2.`idobject` and obj2.`o_iright` AND (obj1.o_iright - obj1.o_ileft) = 1;";
			db_runQuery($cn, $q_st);
		}
		unset($searchinobj);

		$q_st = "DELETE FROM `poll` WHERE `iduser` NOT IN (SELECT `iduser` FROM `userpositions` as u INNER JOIN `o_usein` as o ON u.o_guid = o.o_guid);";
		db_runQuery($cn, $q_st);
	} 

	$search = (( isset($_REQUEST['search']) && strlen(trim($_REQUEST['search']))>0 ) ? trim($_REQUEST['search']) : "");
	if ($search != ""){
		$q_st = "DELETE FROM `poll` WHERE user_name NOT LIKE '%".$search."%' AND positions NOT LIKE '%".$search."%' ;";
		db_runQuery($cn, $q_st);
	}

	$resarr = array();
	$q_st = "SELECT COUNT(0) as cnt FROM `poll` ";
	$resarr = db_runQueryAndReturnArray($cn,$q_st);
	$total = $resarr[0]['cnt'];
	$total = ceil($total/$onpage); 
	$total = $total == 0 ? 1 : $total;
	$page = (($page > $total) ? $total : $page);

	db_setTimeZone($cn);

	$q_st = 'SELECT distinct `poll`.*
			FROM `poll`  ';

	if ($order_column != "") {
		$q_st.= " ORDER BY ".$order_column."  ".$order_val." ";
	}
	
	session_start();
	if ($page == 1) {
		$page = 2;
		$q_st.= "LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
		if (!isset($_SESSION['adminpollrespondents_p_'.$uiid.$page])){
			$_SESSION['adminpollrespondents_p_'.$uiid.$page] = db_runQueryAndReturnArray($cn,$q_st);
		}
	} else if ($page == $total) {
		$page = $total - 1;
		$q_st.= "LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
		if (!isset($_SESSION['adminpollrespondents_p_'.$uiid.$page])){
			$_SESSION['adminpollrespondents_p_'.$uiid.$page] = db_runQueryAndReturnArray($cn,$q_st);
		}
	} else {
		$page = $page - 1;
		if (!isset($_SESSION['adminpollrespondents_p_'.$uiid.$page])){
			$_SESSION['adminpollrespondents_p_'.$uiid.$page] = db_runQueryAndReturnArray($cn, $q_st." LIMIT ".(($page - 1) * $onpage).",".$onpage.";");
		}
		$page = $page + 2;
		if (!isset($_SESSION['adminpollrespondents_p_'.$uiid.$page])){
			$_SESSION['adminpollrespondents_p_'.$uiid.$page] = db_runQueryAndReturnArray($cn, $q_st." LIMIT ".(($page - 1) * $onpage).",".$onpage.";");
		}
	}
	$_SESSION['adminpollrespondents_total'.$uiid] = $total;
	session_write_close();
	

db_disconnect($cn);
ob_end_flush();
?>