<?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','updatedate'); 
$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();

if (isset($_REQUEST['searchinobj'])) {
	$searchinobj = $_REQUEST['searchinobj'];
}

if (isset($_REQUEST['searchinobjlast'])) {
	$searchinobjlast = $_REQUEST['searchinobjlast'];
	$searchinobj = array_merge($searchinobj, $searchinobjlast);
}
$u_ids = GetUserIDs();
$url = getCurPageURL('service/');
$hideheader = (isset($_COOKIE['hideheader']) ?  $_COOKIE['hideheader'] : 0);
$urlWO = getCurPageURLWO('service');
$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'))));
}
if (!isset($_REQUEST['searchin'])) { $_REQUEST['searchin'] = 's_all'; }

$uiid = (isset($_REQUEST['sessionhash']) ? $_REQUEST['sessionhash'] : "e").
(isset($_REQUEST['foldergroup']) ? $_REQUEST['foldergroup'] : "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['answers-hasnot']) ? $_REQUEST['answers-hasnot'] : "e" ).(isset($_REQUEST['answers-has']) ? $_REQUEST['answers-has'] : "e" ).
(isset($_REQUEST['searchinobjlast']) ? md5(serialize($_REQUEST['searchinobjlast'])) : 'e').(isset($_REQUEST['searchinobj']) ? md5(serialize($_REQUEST['searchinobj'])) : 'e');

if (isset($_SESSION['adminpoll_p_'.$uiid.$page]) 
	&& ($page == 1 || isset($_SESSION['adminpoll_p_'.$uiid.($page-1)]))
	&& (isset($_SESSION['adminpoll_total'.$uiid]) && $page+1 <= $_SESSION['adminpoll_total'.$uiid] && isset($_SESSION['adminpoll_p_'.$uiid.($page+1)]))){
	session_write_close();
	db_disconnect($cn);
	ob_end_flush();
	exit;
}

$ids = implode(",", $u_ids);

	$answers = NULL;
	if (!isset($_REQUEST['answers-has']) && isset($_REQUEST['answers-hasnot']))
		$answers = 'hasnot';
	if (!isset($_REQUEST['answers-hasnot']) && isset($_REQUEST['answers-has']))
		$answers = 'has';
	db_getPollObjetcListAdmin($cn, (isset($_REQUEST['idpolltype']) ? $_REQUEST['idpolltype'] : NULL), (isset($_REQUEST['skproject']) ? $_REQUEST['skproject'] : NULL),  (isset($_REQUEST['skbranch']) ? $_REQUEST['skbranch'] : NULL), $contlngid, $usr_arr, TRUE, $answers, TRUE );
	$searchinobj = array();
	$searchinobjlast = array();
	
	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,
					`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`, `skbranch` FROM `objects` WHERE `idobject` in (".$searchinobj[$i].");";
			db_runQuery($cn, $q_st);
			$q_st = "INSERT IGNORE INTO `o_usein` SELECT obj1.`idobject`, 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 `idobject` NOT IN (SELECT `idobject` FROM `o_usein`);";
		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 o_name NOT LIKE '%".$search."%' AND r_name NOT LIKE '%".$search."%' AND  branch_name 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);

	if (!isset($_REQUEST['foldergroup']) || $_REQUEST['foldergroup'] == 'on') {
		$q_st = 'SELECT distinct `poll`.*,`folder`, po.objectversion, po.reportversion,  
		res_o.rft_columnname_long as objectversiondescription, 
		DATE_FORMAT(from_unixtime(`poll`.objectversiondate_tmst), "%d.%m.%Y %H:%i") as objectversiondate 
		FROM `poll` 
		LEFT JOIN fullfolders ON `poll`.`idobject` = `fullfolders`.`idobject` AND  `poll`.`skbranch` = `fullfolders`.`skbranch` AND `fullfolders`.idlanguage = '.$contlngid.' 
		LEFT JOIN `resourcefromtables` res_o ON `poll`.`idobject` = res_o.`idrecord` AND res_o.`idtable` = 1101 AND res_o.idlanguage = '.$contlngid.'
		INNER JOIN `pollingobjects` po ON `poll`.`skpollingobject` = po.`skpollingobject` 
		ORDER BY `folder`, `poll`.o_name ';
	} else {
		$q_st = 'SELECT distinct `poll`.*, \'\' as `folder`, po.objectversion, po.reportversion,  
		res_o.rft_columnname_long as objectversiondescription, 
		DATE_FORMAT(from_unixtime(`poll`.objectversiondate_tmst), "%d.%m.%Y %H:%i") as objectversiondate 
		FROM `poll` 
		LEFT JOIN `resourcefromtables` res_o ON `poll`.`idobject` = res_o.`idrecord` AND res_o.`idtable` = 1101 AND res_o.idlanguage = '.$contlngid.'
		INNER JOIN `pollingobjects` po ON `poll`.`skpollingobject` = po.`skpollingobject` 
		ORDER BY `poll`.o_name ';
	}		

	session_start();
	if ($page == 1) {
		$page = 2;
		$q_st.= "LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
		if (!isset($_SESSION['adminpoll_p_'.$uiid.$page])){
			$_SESSION['adminpoll_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['adminpoll_p_'.$uiid.$page])){
			$_SESSION['adminpoll_p_'.$uiid.$page] = db_runQueryAndReturnArray($cn,$q_st);
		}
	} else {
		$page = $page - 1;
		if (!isset($_SESSION['adminpoll_p_'.$uiid.$page])){
			$_SESSION['adminpoll_p_'.$uiid.$page] = db_runQueryAndReturnArray($cn, $q_st." LIMIT ".(($page - 1) * $onpage).",".$onpage.";");
		}
		$page = $page + 2;
		if (!isset($_SESSION['adminpoll_p_'.$uiid.$page])){
			$_SESSION['adminpoll_p_'.$uiid.$page] = db_runQueryAndReturnArray($cn, $q_st." LIMIT ".(($page - 1) * $onpage).",".$onpage.";");
		}
	}
	$_SESSION['adminpoll_total'.$uiid] = $total;
	session_write_close();

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