<?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');
}

checkUserAndRedirectToLogin();

$cn = db_connect();
$url = getCurPageURL();
$usr_arr = GetUserIDs();
$contlngid = $_SESSION['user_idlanguagecontent'];
$lng_shot = db_getLanguageShortByID($cn, $contlngid);
$ismob = (isset($_COOKIE['mobilemode']) && $_COOKIE['mobilemode'] == 1);
$hideheader = (isset($_COOKIE['hideheader']) ?  $_COOKIE['hideheader'] : 0);

if ( getSetting('portal','useRights',0) == 0 || getSetting('portal','polls.createarchive',0) != 1){
 	$url = getCurPageURLWO()."/businessmodel.php";
	header("Location: ".$url); 
	ob_end_flush();
	exit;
} else {
	if( !IsUserLogin() ){
		header("Location: ".getCurPageURLWO()."/login.php?returl=adminpollobject.php");
		ob_end_flush();
		exit;
	}
	$cn = db_connect();
	if (!isUserAdmin() && !db_isUserAdminToPolls($cn, $usr_arr)){ 
		header("Location: ".getCurPageURLWO()."/personal.php");
		ob_end_flush();
		exit;
	}
}

if (!isset($_REQUEST['iduser']) || !is_numeric($_REQUEST['iduser']) ) {
	db_disconnect($cn);
	RedirectToPageNotFound();
}

if (!isset($_REQUEST['skpollingobject']) || !isset($_REQUEST['skpolltype']) || !is_numeric($_REQUEST['skpollingobject']) || !is_numeric($_REQUEST['skpolltype'])) {
	db_disconnect($cn);
	RedirectToPageNotFound();
}

$skpollingobject = $_REQUEST['skpollingobject'];
$skbranch = db_getSKBranchByUserAnswerValue($cn, $skpollingobject, $_REQUEST['skpolltype'], $_REQUEST['iduser'] );
if ($skbranch === NULL || $skbranch < 1) {
	db_disconnect($cn);
	RedirectToPageNotFound();
}


$onpage = getSetting('page', 'polls.pagesize', 20);

$default_order_column = "objectversion";
$default_order_val = "desc";

// url parse and build
$order_column = isset( $_GET[ "order_column" ] ) ? $_GET[ "order_column" ] : $default_order_column;
$order_val = isset( $_GET[ "order_val" ] ) ? $_GET[ "order_val" ] : $default_order_val;
$page = isset( $_GET[ "page" ] ) ? $_GET[ "page" ] : 1;

$url = getCurPageURL();
$sourceparams = db_getPollingObjectSource($cn, $skpollingobject);
$idpolltype = db_getIDPollTypeBySK($cn,$_REQUEST['skpolltype']);
$guids = db_getGuidsByPollingObject($cn, $skpollingobject);
$urlpoll = getCurPageURLWO().'/adminpollrespondents.php?idpolltype='.$idpolltype.(isset($guids[0]['skproject']) && $guids[0]['skproject'] > 0 ? '&skproject='.$guids[0]['skproject'] : '&skbranch='.$guids[0]['skbranch']);
$urlpollobject = getCurPageURLWO().'/adminpolbyrespondent.php?iduser='.$_REQUEST['iduser'].'&idpolltype='.$idpolltype.(isset($guids[0]['skproject']) && $guids[0]['skproject'] > 0 ? '&skproject='.$guids[0]['skproject'] : '&skbranch='.$guids[0]['skbranch']);
$objectfullname = db_getObjectName($cn, $guids[0]['o_guid'], $contlngid, $skbranch).' ('.db_getReportName($cn, $guids[0]['r_guid'], $contlngid, $skbranch).')';

if (!db_isUserAdminToPoll($cn, $usr_arr, $_REQUEST['skpolltype'], (isset($guids[0]['skproject']) && $guids[0]['skproject'] > 0 ? $guids[0]['skproject'] : NULL ), (isset($guids[0]['skproject']) && $guids[0]['skproject'] > 0 ? NULL : $guids[0]['skbranch'] ))){
	db_disconnect($cn);
	RedirectToPageNotFound();
}
?>
<!doctype html> 
<html>
<head>
	<title><?php echo renderTitle();?></title>
	<? 
	renderCommonMeta(renderTitle()); 
	renderCommonCSS(); 
	?>
	<link rel="stylesheet" href="css/zDater.css">
</head>
<body>
	<?php renderModalHourGlassDiv();?>
	<div id="container">
	<?php renderLoginBlock(); ?>
	<div id="main" role="main" class="ui-layout-center">
		<?php renderMainMenu(); ?>
		<div id="content" class="ui-layout-center">

		<section class="bread-crumbs" style="padding-bottom: 10px;">
				<div class="inline-float-left">
					<div id="box-poll-bread-crumbs-text" >
						<a href="adminpollobject.php"><?php getResource("title.polls");?></a> \ <a href="<?php echo $urlpoll;?>"><?php echo db_getPolltypeName($cn, $idpolltype, $contlngid).': '; if ($sourceparams[0]['source'] === 'skproject') { echo db_getProjectName($cn, $sourceparams[0]['id'], $contlngid);} else { echo db_getBranchName($cn, $sourceparams[0]['id'], $contlngid);}  ?> </a> \ <a href="<?php echo $urlpollobject;?>"> <?php echo db_getUserNameByID($cn, $_REQUEST['iduser'], $contlngid);  ?> : <?php echo $objectfullname;?>  </a>
					</div>
				</div>
		</section>


			<section id="box-input" class="clearfix">
				<h3 style="margin-bottom: 15px;"><?php getResource("title.archive.hint");?></h3> <!--62823-->
				<table class="tbldata" cellspacing="0">
					<tr>
						<th style="width:30%" class="<? if( $order_column == "objectversion" ) echo "tbldata-cell-sortable" ?> tblinput-cell-name"><? echo buildSortColumnTitle( getResourceByLang('field.poll.objectversion'), ( $order_column == "objectversion" ? true : false ), "objectversion", $order_val ) ?></th>
						<th style="width:15%"><? echo getResourceByLang('field.poll.answer'); ?></th>
						<th style="width:15%"><? echo getResourceByLang('field.poll.comment'); ?></th>
						<th style="width:50%"><? echo getResourceByLang('field.poll.report'); ?></th>
					</tr>
<?php
	$query = "SET SQL_BIG_SELECTS=1;";
	db_runQuery($cn, $query);
	$q_st = "set @@tmp_table_size=2147483648;";
	db_runQuery($cn, $q_st);
	$q_st = "set @@max_heap_table_size=2147483648;";
	db_runQuery($cn, $q_st);

	$q_st = "DROP TEMPORARY TABLE IF EXISTS `archive` ;";
	db_runQuery($cn, $q_st);
	
	$q_st = "    CREATE TEMPORARY TABLE `archive` (
		`o_guid` varchar(40) NULL,
		`r_guid` varchar(40) NULL,
		`idpollingobjectarchive` INT NOT NULL,
		`skpolltype` INT NOT NULL,
		`objectversionhash` varchar(128) NOT NULL,
		`reportversion` varchar(1100) NOT NULL,
		`objectversion` varchar(1100) NOT NULL,
		`objectversiondate_tmst` INT NOT NULL,
		`hascomment` TINYINT,
		`hasfile` TINYINT,
		`answer` varchar(2500) NULL,
		`uav_tmst` INT NULL,
		`uav_body` LONGTEXT NULL,
		`o_name` varchar(1100) NULL,
		`r_name` varchar(1100) NULL
		);";
	db_runQuery($cn, $q_st);
	
	$q_st = "INSERT IGNORE INTO `archive`
		SELECT poa.o_guid, poa.r_guid, poa.idpollingobjectarchive, uava.skpolltype, poa.objectversionhash, rfta_ver_r.rft_columnname_text as reportversion, rfta_ver.rft_columnname_text as objectversion, poa.objectversiondate_tmst, IF( LENGTH(TRIM(IFNULL(uava.uav_body,''))) > 0, 1, 0) as hascomment, isfileswassave as hasfile, uavat.text, uava.uav_tmst, uava.uav_body, rfta_o.rft_columnname_text, rfta_r.rft_columnname_text
  		  FROM `pollingobjectsarchive` poa 
		 INNER JOIN `pollingobjects` po ON po.skpollingobject = poa.skpollingobject
		 INNER JOIN `useranswers` ua ON po.`idpollingobject` = ua.`idpollingobject`  
		 INNER JOIN `users` u ON ua.`user_hash` = u.`user_hash` 
		 INNER JOIN `polltypes` pt ON ua.`idpolltype` = pt.`idpolltype`
		  LEFT JOIN `useranswersvaluesarchive` uava ON uava.`idpollingobjectarchive` = poa.`idpollingobjectarchive`  AND u.`iduser` = uava.`iduser`
		  LEFT JOIN `useranswersvaluesarchivetext` uavat ON uavat.`idpollingobjectarchive` = poa.`idpollingobjectarchive` AND u.`iduser` = uavat.`iduser` AND uavat.idlanguage = ".$contlngid."
		  LEFT JOIN `resourcefromtablespollarchive` rfta_o ON poa.idpollingobjectarchive = rfta_o.idpollingobjectarchive AND poa.o_guid = rfta_o.guidrecord AND rfta_o.idtable = 1 AND rfta_o.idlanguage = ".$contlngid."
		  LEFT JOIN `resourcefromtablespollarchive` rfta_r ON poa.idpollingobjectarchive = rfta_r.idpollingobjectarchive AND poa.r_guid = rfta_r.guidrecord AND rfta_r.idtable = 2 AND rfta_r.idlanguage = ".$contlngid."
		  LEFT JOIN `resourcefromtablespollarchive` rfta_ver ON poa.idpollingobjectarchive = rfta_ver.idpollingobjectarchive AND poa.o_guid = rfta_ver.guidrecord AND rfta_ver.idtable = 1111 AND rfta_ver.idlanguage = ".$contlngid."
		  LEFT JOIN `resourcefromtablespollarchive` rfta_ver_r ON poa.idpollingobjectarchive = rfta_ver_r.idpollingobjectarchive AND poa.r_guid = rfta_ver_r.guidrecord AND rfta_ver.idtable = 2111 AND rfta_ver.idlanguage = ".$contlngid."
		WHERE uava.uav_value > 0 AND u.`iduser` = ".$usr_arr[0]." AND u.user_isactive = 1 
		AND pt.skpolltype = ".mysqli_real_escape_string($cn,$_REQUEST['skpolltype'])."
		AND poa.skpollingobject = ".mysqli_real_escape_string($cn,$_REQUEST['skpollingobject']).";";
	db_runQuery($cn, $q_st);
	$q_st = "SELECT COUNT(0) as cnt FROM `archive` ";
	$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 `archive`.*, DATE_FORMAT(from_unixtime(objectversiondate_tmst), "%d.%m.%Y %H:%i") as objectversiondate, DATE_FORMAT(from_unixtime(uav_tmst), "%d.%m.%Y %H:%i") as answertime FROM `archive`  ORDER BY '.$order_column.' '.$order_val.' ';
	$q_st.= "LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
	
	$resarr = db_runQueryAndReturnArray($cn,$q_st);
	$size = (is_array($resarr) ? sizeof($resarr) : 0 );
	$allowComment = NULL;
	$folder = "";
	for($i=0; $i<$size; $i++){
		?>
			<tr>
				<td valign="top"><a class="dialog-html-show-link" title="<?php getResource("title.poll.objectversion");?>" href="pollingobjectarchive-description-html<?php echo $resarr[ $i ][ "idpollingobjectarchive" ];?>"><?php echo $resarr[ $i ][ "objectversion" ].', '.$resarr[ $i ][ "objectversiondate" ];?></a></td>
				<td valign="top"><?php if ( strlen($resarr[ $i ][ "answer" ]) > 0 ) { echo $resarr[ $i ][ "answer" ].' '.$resarr[ $i ][ "answertime" ];}?></td>
				<td valign="top" align="center"><?php if (sizeof($resarr[ $i ]) > 0 && strlen($resarr[ $i ]['uav_body']) > 0) {?><a class="dialog-html-show-link" title="<? echo getResourceByLang('field.poll.comment'); ?>" href="pollingobjectarchive-comment-html<?php echo $resarr[ $i ][ "idpollingobjectarchive" ];?>"><i class="fal <?php echo (sizeof($resarr[ $i ]) > 0 && strlen($resarr[ $i ]['uav_body']) > 0 ? 'fa-file-alt' : 'fa-file' ); ?> font-awesome-color font-awesome-size " aria-hidden="true"></i></a><?php }?></td>
				<td valign="top"><?php if ($resarr[ $i ][ "hasfile" ]>0 ) { echo '<a target="_blank" href="'.getCurPageURLWO().'/reportarchive.php?idpollingobjectarchive='.$resarr[ $i ][ "idpollingobjectarchive" ].'&skpolltype='.$resarr[ $i ][ "skpolltype" ].'">'.$resarr[ $i ][ "o_name" ].'('.$resarr[ $i ][ "r_name" ].')</a>'; }?></td>
			</tr>
		<?php } ?>
	</table>

<?php if (!(null === $total || $total == 0) && $total > 1) {?>
				<section id="box-paginator" class="box-paginator-table">
				<?php echo_panel_page($total, $page, $url);?>
				</section>
<?php }?>

			</section>
		</div>
	</div>
</div>

<?php for($i=0; $i<$size; $i++){
// 61409
?>
		<div id="pollingobjectarchive-comment-html<? echo $resarr[ $i ][ "idpollingobjectarchive" ]?>" class="dialog" style="min-width:50%; min-height:80%;">
		<div id="dialog-titlebar" class="titlebar"></div>
		<button name="close"></button>
		<div class="content">
			<?php echo $resarr[ $i ][ "uav_body" ];?>
		</div>
		<div class="buttonpane">
			<div class="buttonset">
			<button id="dialog-box-button-cancel" class="btn-top btn-top-text" title="<?php getResource("button.close.hint");?>"><span><?php getResource("button.close");?></span></button>
			</div>
		</div>
	</div>			
<?php } ?>

<?php
	$q_st = 'SELECT DISTINCT p.idpollingobjectarchive, p.objectversion, p.reportversion,  res_o.rft_columnname_long as objectversiondescription, res_r.rft_columnname_long as reportversiondescription, res_uo.rft_columnname_text as userobject, res_ur.rft_columnname_text as userreport        
	FROM `archive` p 
	LEFT JOIN `resourcefromtablespollarchive` res_o ON p.`idpollingobjectarchive` = res_o.`idpollingobjectarchive` AND res_o.`guidrecord` = p.`o_guid` AND res_o.`idtable` = 1101 AND res_o.idlanguage = '.$contlngid.'
	LEFT JOIN `resourcefromtablespollarchive` res_r ON p.`idpollingobjectarchive` = res_r.`idpollingobjectarchive` AND res_r.`guidrecord` = p.`r_guid` AND res_r.`idtable` = 1102 AND res_r.idlanguage = '.$contlngid.'
	LEFT JOIN `pollingobjectsarchive` po ON p.`idpollingobjectarchive` = po.`idpollingobjectarchive` 
	LEFT JOIN `users` uo ON uo.`user_hash` = po.`objectversionuhash` 
	LEFT JOIN `resourcefromtables` res_uo ON uo.`iduser` = res_uo.`idrecord` AND res_uo.`idtable` = 6 AND res_uo.idlanguage = '.$contlngid.'
	LEFT JOIN `users` ur ON ur.`user_hash` = po.`reportversionuhash` 
	LEFT JOIN `resourcefromtables` res_ur ON ur.`iduser` = res_ur.`idrecord` AND res_ur.`idtable` = 6 AND res_ur.idlanguage = '.$contlngid.'
	;';
	$resarr = db_runQueryAndReturnArray($cn,$q_st);
	$size = (is_array($resarr) ? sizeof($resarr) : 0 );
	for($i=0; $i<$size; $i++){
		?>

	<div id="pollingobjectarchive-description-html<? echo $resarr[ $i ][ "idpollingobjectarchive" ]?>" class="dialog" style="min-width:50%; min-height:80%;">
		<div id="dialog-titlebar" class="titlebar"></div>
		<button name="close"></button>
		<div class="content">
			<p class="dialog-title-h2"><?php getResource("title.poll.object");?></p>
			<p class="dialog-p"><?php echo /*62290 getResource("title.poll.dialog.version").': '.*/$resarr[ $i ][ "objectversion" ];?> </p>
			<p class="dialog-p"><?php echo getResource("title.poll.dialog.author").': '.$resarr[ $i ][ "userobject" ];?></p>
			<p class="dialog-p"><?php echo getResource("title.poll.dialog.description").': ';?> <br/>
			<?php echo $resarr[ $i ][ "objectversiondescription" ]?> </p>
			<?php if ((isset ($resarr[ $i ][ "reportversion" ]) && strlen(trim($resarr[ $i ][ "reportversion" ])) > 0) || (isset ($resarr[ $i ][ "reportversiondescription" ]) && strlen(trim($resarr[ $i ][ "reportversiondescription" ])) > 0)) { ?> 
				<p class="dialog-title-h2">&nbsp;<br/></p>
				<p class="dialog-title-h2"><?php getResource("title.poll.report");?></p>
				<?php if ((isset ($resarr[ $i ][ "reportversion" ]) && strlen(trim($resarr[ $i ][ "reportversion" ])) > 0)) { ?> 
					<p class="dialog-p"><?php echo /*62290 getResource("title.poll.dialog.version").': '.*/$resarr[ $i ][ "reportversion" ];?> </p>
				<?php }?>		
				<?php if ((isset ($resarr[ $i ][ "reportversiondescription" ]) && strlen(trim($resarr[ $i ][ "reportversiondescription" ])) > 0)) { ?> 
					<p class="dialog-p"><?php echo getResource("title.poll.dialog.author").': '.$resarr[ $i ][ "userreport" ];?></p>
					<p class="dialog-p"><?php echo getResource("title.poll.dialog.description").': ';?> <br/>
					<?php echo $resarr[ $i ][ "reportversiondescription" ]?> </p>
				<?php }?>		
			<?php }?>		
		</div>
		<div class="buttonpane">
			<div class="buttonset">
			<button id="dialog-box-button-cancel" class="btn-top btn-top-text" title="<?php getResource("button.close.hint");?>"><span><?php getResource("button.close");?></span></button>
			</div>
		</div>
	</div>
<?php }?>
<script src="js/libs/jquery.js"></script>
<script src="js/libs/jquery.cookie.js"></script>
<script src="js/script.js"></script>
<script src="js/libs/drDialog/drdialog.js"></script>
<link rel="stylesheet" href='js/libs/drDialog/drdialog.css' />
<script src="js/dialoglinks.js"></script>
<script src="js/poll.js"></script>
<?php
	if(!(is_readable(realpath(dirname(__FILE__)).'/templates/languagesbox.template'))) {
		die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/templates/languagesbox.template');
	} else {
		include_once(realpath(dirname(__FILE__)).'/templates/languagesbox.template');
	}
?>

<?php renderFooterTemplate(); ?>

</body>
</html>

<?php
unset($trSt);
db_disconnect($cn);
ob_end_flush();
?>
