<?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();

if(!(is_readable(realpath(dirname(__FILE__)).'/include/bsservice.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/include/bsservice.inc');
} else {
	include_once(realpath(dirname(__FILE__)).'/include/bsservice.inc');
}
$cn = db_connect();
$url = getCurPageURL();
$contlngid = $_SESSION['user_idlanguagecontent'];
$lng_shot = db_getLanguageShortByID($cn, $contlngid);
if (isset($_REQUEST['idbranch'])) {
	$idbranch = $_REQUEST['idbranch'];
	$skbranch = db_getSKBranch($cn,$idbranch);	
} else {
	$skbranch = db_getMainSKBranch($cn);
	$idbranch = db_getMainIDBranch($cn);	
}

if ((!isset($_REQUEST['idpolltype'])) || ((!isset($_REQUEST['skproject']) || !is_numeric($_REQUEST['skproject'])) && (!isset($_REQUEST['skbranch']) || !is_numeric($_REQUEST['skbranch'])))) {
	RedirectToPageNotFound();
}

if (isset($_REQUEST['skbranch']) && !db_isBrancheComplite($cn, $_REQUEST['skbranch']) ) {
	RedirectToPageNotFound();
}

if (isset($_REQUEST['skproject']) && !db_isProjectComplite($cn, $_REQUEST['skproject']) ) {
	RedirectToPageNotFound();
}

$usr_arr = GetUserIDs();
if (!db_isPollType($cn, $_REQUEST['idpolltype'], $usr_arr)){
	db_disconnect($cn);
	RedirectToPageNotFound();
}

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

$default_order_column = getCookieForPage('order_column','updatedate'); 
$default_order_val = getCookieForPage('order_val','asc');

$urlFromCookies = getCurPageURL();
if (getCookieForPage('foldergroup') !== NULL && !isset($_REQUEST['foldergroup'])) {
	$urlFromCookies = urlReplaceParam($urlFromCookies,'foldergroup', getCookieForPage('foldergroup'));
}

if (!isset($_REQUEST['answers-has']) && !isset($_REQUEST['answers-hasnot'])) {
	if (getCookieForPage('answers-hasnot') !== NULL)
		$urlFromCookies = urlReplaceParam($urlFromCookies,'answers-hasnot', '');
	if (getCookieForPage('answers-has') !== NULL)
		$urlFromCookies = urlReplaceParam($urlFromCookies,'answers-has', '');
	if (getCookieForPage('answers-has') === NULL && getCookieForPage('answers-hasnot') === NULL) {
		$urlFromCookies = urlReplaceParam($urlFromCookies,'answers-hasnot', '');
		$urlFromCookies = urlReplaceParam($urlFromCookies,'answers-has', '');
	}
	if( $urlFromCookies !== getCurPageURL() ){
		header("Location: ".$urlFromCookies);
		ob_end_flush();
		exit;
	}
}

function buildFilterButton( $name, $param, $value, $is_active, $page, $forGroup = FALSE ) {
	$url = getCurPageURL();
	return (!$forGroup ? "<span class='btn-span-separator'>" : "" )."<a href='".buildURL(urlReplaceParam($url, $param, (!$is_active ? $value : NULL )), $page )."' class='btn-top btn-top-text ".( $is_active ? "btn-top-active" : "" )."' title='".$name."'><span>".$name."</span></a>".(!$forGroup ? "</span>" : "" );
}

function buildURL( $url, $page ) {
	$url = urlReplaceParam($url,'page', $page);
	return  $url;
}


// url parse and build
$page = isset( $_GET[ "page" ] ) ? $_GET[ "page" ] : 1;
$url = getCurPageURL();
?>
<!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">
			<div class="bread-crumbs" style="padding-bottom: 10px;"> 
				<a href="polls.php"><?php getResource("title.polls");?></a> \ <?php echo db_getPolltypeName ($cn, $_REQUEST['idpolltype'], $contlngid).': '; if (isset($_REQUEST['skproject'])) { echo db_getProjectName($cn, $_REQUEST['skproject'], $contlngid);} else if (isset($_REQUEST['skbranch'])) { echo db_getBranchName($cn, $_REQUEST['skbranch'], $contlngid);}  ?> 
			</div>

			<section id="box-input" class="clearfix">
			<div id="box-input-container">
				<div class="box-period">
					<div class="box-period-caption"><?php getResource("title.poll.filter.answers");?></div>
					<span>
						<?php 
							echo buildFilterButton(getResourceByLang("title.poll.filter.answers.has"), 'answers-has', '', isset($_REQUEST['answers-has']),  $page );
							echo buildFilterButton(getResourceByLang("title.poll.filter.answers.hasnot"), 'answers-hasnot', '', isset($_REQUEST['answers-hasnot']),  $page );
						?>
				</span>
					<div class="box-group-caption">
          				<?php getResource("title.Group"); /*STU Change resource*/?>&nbsp;
						<span>
							<?php 
								echo buildFilterButton(getResourceByLang("button.yes"), 'foldergroup', 'on', (!isset($_REQUEST['foldergroup']) || $_REQUEST['foldergroup'] == 'on'),  $page, TRUE);
								echo buildFilterButton(getResourceByLang("button.no"), 'foldergroup', 'off', (isset($_REQUEST['foldergroup']) && $_REQUEST['foldergroup'] == 'off'),  $page, TRUE );
							?>
						</span>
					</div>
					<div class="" style="height: 5px;"></div>
				</div>



				<table class="tbldata" cellspacing="0">
					<tr>
						<th class="tblinput-cell-name" style="width:70%"><? echo getResourceByLang('field.poll.object'); ?></th>
						<th class="tblinput-cell-name" style="width:15%; max-width:15%"><? echo getResourceByLang('field.poll.objectversion'); ?></th>
						<th class="tblinput-cell-name poll-extra" style="width:30%; display:none;"><? echo getResourceByLang('field.poll.extra'); ?></th>
						<th class="tblinput-cell-name" style="width:15%"><? echo getResourceByLang('field.poll.answer'); ?></th>
					</tr>
<?php

	setCookieForPage('foldergroup', (isset($_REQUEST['foldergroup']) ? $_REQUEST['foldergroup'] : NULL));
	setCookieForPage('answers-has', (isset($_REQUEST['answers-has']) ? 'true' : NULL));
	setCookieForPage('answers-hasnot', (isset($_REQUEST['answers-hasnot']) ? 'true'  : NULL));
	$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_getPollObjetcList($cn, (isset($_REQUEST['idpolltype']) ? $_REQUEST['idpolltype'] : NULL), (isset($_REQUEST['skproject']) ? $_REQUEST['skproject'] : NULL),  (isset($_REQUEST['skbranch']) ? $_REQUEST['skbranch'] : NULL), $contlngid, $usr_arr, $answers  );
	$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 = '
		FROM `poll` 
		LEFT JOIN `fullfolders` ON `poll`.`idobject` = `fullfolders`.`idobject` AND  `poll`.`skbranch` = `fullfolders`.`skbranch` AND `fullfolders`.idlanguage = '.$contlngid.'
		LEFT JOIN `resourcefromtables` res_r ON `poll`.`idreport` = res_r.`idrecord` AND res_r.`idtable` = 1102 AND res_r.idlanguage = '.$contlngid.'
		INNER JOIN `pollingobjects` po ON `poll`.`skpollingobject` = po.`skpollingobject` 
			ORDER BY `folder`, `poll`.o_name ';
	} else {
		$q_st = '
		FROM `poll` 
		LEFT JOIN `resourcefromtables` res_r ON `poll`.`idreport` = res_r.`idrecord` AND res_r.`idtable` = 1102 AND res_r.idlanguage = '.$contlngid.'
		INNER JOIN `pollingobjects` po ON `poll`.`skpollingobject` = po.`skpollingobject` 
			ORDER BY `poll`.o_name ';
	}
	
	$q_filter = 'SELECT po.`skpollingobject`, `skpolltype` , po.`skbranch` , po.`o_guid` , po.`r_guid` , po.`idobject` , `idreport` '.$q_st." ;";
	$uniqid = md5((isset($_REQUEST['idpolltype']) ? $_REQUEST['idpolltype'] : '').(isset($_REQUEST['skproject']) ? $_REQUEST['skproject'] : "").(isset($_REQUEST['skbranch']) ? $_REQUEST['skbranch'] : ""));
	$_SESSION['pollsfilteredlist'.$uniqid] = db_runQueryAndReturnArray($cn, $q_filter);
	
	$q_st = 'SELECT distinct `poll`.*,'
		.(!isset($_REQUEST['foldergroup']) || $_REQUEST['foldergroup'] == 'on' ? '`folder`' : ' \'\' as `folder`')
		.', DATE_FORMAT(from_unixtime(`poll`.objectversiondate_tmst), "%d.%m.%Y %H:%i") as objectversiondate, 
		po.objectversion, po.reportversion,  
		res_r.rft_columnname_long as reportversiondescription '
		.$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++){
		if ($folder != $resarr[ $i ][ "folder" ]) {
			$folder = $resarr[ $i ][ "folder" ]; ?>
			<tr>
				<td class="td-border-bottom" colspan="5"><b><? echo $resarr[ $i ][ "folder" ];?></b></td>
			</tr>
		<?php }
		$isaltver = false;
		$borderclass = "td-border-bottom";
		if ($i < $size - 1 && $resarr[ $i+1 ][ "skbranch" ] != $resarr[ $i ][ "skbranch" ]  && $resarr[ $i+1 ][ "o_guid" ] == $resarr[ $i ][ "o_guid" ] && $resarr[ $i+1 ][ "r_guid" ] == $resarr[ $i ][ "r_guid" ] && $folder == $resarr[ $i + 1 ][ "folder" ]  ){
			$borderclass = "td-border-bottom-dotted";
			$isaltver = true;
		}
		if ($i == $size - 1) {
			$borderclass = "td-border-bottom-none";
		}
		if ($allowComment === NULL) {
			$allowComment = db_getPollTypeAllowComment($cn, $resarr[ $i ][ "skpolltype" ]);
		}
		$question = db_getPolltypeQuestion($cn, $resarr[ $i ][ "skpollingobject" ], $resarr[ $i ][ "skpolltype" ], $usr_arr[0], $contlngid );
		if ($resarr[ $i ][ "hasanswer" ] == 1) {
			$answer = db_getPolltypeQuestionAnswer($cn, $resarr[ $i ][ "skpollingobject" ], $resarr[ $i ][ "skpolltype" ], $usr_arr[0] );
		} else {
			$answer = array();
		}
		$hashistory = db_hasPolltypeObjectHistory($cn, $resarr[ $i ][ "skpollingobject" ] );
		$ansval = '';
		if ($question[0]['idpolltypequestiontype'] == 1){
			$ansval = $question[0]['rft_columnname_text'];
		} else if ($question[0]['idpolltypequestiontype'] == 2 && is_array($answer) && sizeof($answer) > 0 && sizeof($answer[0]) > 0 && $answer[0]['uav_value'] !== NULL && $answer[0]['uav_value'] > 0  ){
			$ansval = db_getQuestionSelectValueByID($cn, $question[0]['skpolltypequestion'], $answer[0]['uav_value'], $contlngid );
		}
		?>
			<tr>
				<td class="<?php echo $borderclass;?>" valign="top" style="width:40%"><nobr><? echo '<a class="link-fav-in-table" style="background-position-y: 0; background-image: url( '.getImgIcon($resarr[$i]['o_icon']).' );" href="pollobject.php?skpollingobject='.$resarr[ $i ][ "skpollingobject" ].'&skpolltype='.$resarr[ $i ][ "skpolltype" ].'&skbranch='.$resarr[ $i ][ "skbranch" ].'&oguid='.$resarr[ $i ][ "o_guid" ].'&rguid='.$resarr[ $i ][ "r_guid" ].(isset($_REQUEST['idpolltype']) ? '&idpolltype='.$_REQUEST['idpolltype'] : '').(isset($_REQUEST['skproject']) ? '&skproject='.$_REQUEST['skproject'] : '').(isset($uniqid) ? "&filteruniqid=".$uniqid : "").'">'.$resarr[ $i ][ "o_name" ].' ('.$resarr[ $i ][ "r_name" ].')</a>'; ?> </nobr></td>
				<td class="<?php echo $borderclass;?>" valign="top" style="width:20%"><nobr><div style="padding-left: 0px;padding-top: 2px;" class="link-fav-in-table dialog-html-show-link" title="<?php getResource("title.poll.objectversion");?>" href="pollingobject-description-html<?php echo $resarr[ $i ][ "skpollingobject" ];?>"><?php echo $resarr[ $i ][ "objectversion" ].', '.$resarr[ $i ][ "objectversiondate" ];?></div></nobr></td>
				<td class="<?php echo $borderclass;?> poll-extra poll-extra-content" valign="top" style="width:20%; display:none;" >
					<?php
					if (($i > 0 && $resarr[ $i-1 ][ "skbranch" ] != $resarr[ $i ][ "skbranch" ] && $resarr[ $i-1 ][ "o_guid" ] == $resarr[ $i ][ "o_guid" ] && $resarr[ $i-1 ][ "r_guid" ] == $resarr[ $i ][ "r_guid" ]) || 
						($i < $size -1 && $resarr[ $i+1 ][ "skbranch" ] != $resarr[ $i ][ "skbranch" ] && $resarr[ $i+1 ][ "o_guid" ] == $resarr[ $i ][ "o_guid" ] && $resarr[ $i+1 ][ "r_guid" ] == $resarr[ $i ][ "r_guid" ])
						) {
							echo '<div style="padding-left: 0px;padding-top: 2px;"><nobr>';
							getResource("title.polls.objectfromaltbranch"); 
							echo '</nobr>';
							echo ': <br>'.db_getBranchName($cn, $resarr[ $i ][ "skbranch" ], $contlngid).'</div>';
 					}
					?>
				</td>
				
				<td  <?php if (!$allowComment) { echo 'style="border-right: 1px solid #bac4bc; padding-top: 0px; width:10%"';} else {echo 'style="padding-top: 0px; width:10%"';}?> class="<?php echo $borderclass;?>" valign="top" > 
					<?php 
						//61844
						$showArc = ( getSetting('portal','polls.createarchive',0) == 1 && db_getPollingObjectsArchiveCount($cn, $resarr[$i][ "skpollingobject" ], $usr_arr[0]) > 0); 
						if ((is_array($answer) && sizeof($answer)>0) || $showArc) {?>				
						<table style="border: none !important;width: 100%;"> 
							<tr style="border: none !important;">
								<td class="poll-answerdetails-firstrow" style="<?php echo(!$showArc && !$allowComment ? 'padding-right: 0px;' : '');?>" width="99%"><?php if (is_array($answer) && sizeof($answer)>0 && sizeof($answer[0])>0 && $answer[0]['uav_value']>0 ) { echo '<nobr>'.$ansval.'</nobr>';}?>&nbsp;</td>
								<?php if ($showArc || $allowComment) { ?>
									<td rowspan="2" class="poll-answerdetails-rowspan" align="middle" valign="center">
										<nobr>
										<?php if ($allowComment && is_array($answer) && sizeof($answer) > 0 && sizeof($answer[0]) > 0) { echo '<div style="display:inline-block;" href="pollingobject-comment-dialog" title="'.getResourceByLang('title.comment.hint').'" dialoghref="'.getCurPageURLWO().'/pollobjectcomment.php?skpollingobject='.$resarr[ $i ][ "skpollingobject" ].'&skpolltype='.$resarr[ $i ][ "skpolltype" ].'" class="dialog-comment dialog-html-show-link" ><i class="fal '.(is_array($answer) && sizeof($answer) > 0 && sizeof($answer[0]) > 0 && strlen($answer[0]['uav_body']) > 0 ? 'fa-file-alt' : 'fa-file' ).' font-awesome-color font-awesome-size " aria-hidden="true" style="margin-right: 7px;"></i></div>'; }?>
											<?php if ($showArc) {
												echo '<a style="display:inline-block;" target="_parent" href="'.getCurPageURLWO().'/pollingobjectsarchive.php?skpollingobject='.$resarr[$i][ "skpollingobject" ].'&skpolltype='.$resarr[$i][ "skpolltype" ].'" title="'; 
												getResource("title.archive.hint"); 
												echo '">'; 
												echo '<i class="fal fa-history font-awesome-color font-awesome-size "></i>';
												echo '</a>';
											} else {
												//62065
												echo '<a style="visibility: hidden;display:inline-block;" target="_parent" href="#" title="'; 
												echo '">'; 
												echo '<i class="fal fa-history font-awesome-color font-awesome-size" style="visibility: hidden;"></i>';
												echo '</a>';
											}?>
										</nobr>
								</td> 
								<?php }?>
							</tr>
							<tr>
								<td class="poll-answerdetails-secondrow" style="<?php echo(!$showArc && !$allowComment ? 'padding-right: 0px;' : '');?>"><?php if (is_array($answer) && sizeof($answer)>0 && sizeof($answer[0])>0 && $answer[0]['uav_value']>0 ) { echo '<nobr>'.$answer[0]['uav_tmst'].'</nobr>';}?>&nbsp;</td>
							</tr>
						</table>  
					<? } ?>
				</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 }?>
		</div>

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

<?php
	for($i=0; $i<$size; $i++){
		//61426
		$version = db_getObjectFullVersion($cn, $resarr[ $i ]['o_guid'], $resarr[ $i ]['skbranch'], $contlngid);
		$versiondescription = db_getObjectVersionDescription($cn, $resarr[ $i ]['o_guid'], $resarr[ $i ]['skbranch'], $contlngid);
		$reportversion = db_getReportFullVersion($cn, $resarr[ $i ]['r_guid'], $resarr[ $i ]['skbranch'], $contlngid);
		?>

	<div id="pollingobject-description-html<? echo $resarr[ $i ][ "skpollingobject" ]?>" class="dialog" style="min-width:50%; min-height:80%;">
		<div id="dialog-titlebar" class="titlebar"></div>
		<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").': '.*/$version;?> </p>
			<p class="dialog-p"><?php echo getResource("title.poll.dialog.description").': ';?> <br/>
			<?php echo $versiondescription;?> </p>
			<?php if ((isset($reportversion) && strlen($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($reportversion)  && strlen($reportversion) > 0 ) { ?>
					<p class="dialog-p"><?php echo /*62290 getResource("title.poll.dialog.version").': '.*/$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.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 }?>

<div id="pollingobject-comment-dialog" class="dialog" style="min-width:600px; min-height:410px;">
	<div id="dialog-titlebar" class="titlebar"></div>
	<button class="dialog-close-button" name="close" style="visibility:hidden"></button>
	<div class="content-scroll-hide">
		<iframe id="pollingobject-comment-frame" name="pollingobject-comment-frame" src="" width="100%" height="100%"><?php getResource("message.notSupportFrames"); ?></iframe>			
	</div>
</div>
<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>
<script src="js/poll-extra-content-column.js"></script>
<script src="js/box-caption-processor.js"></script>
<script>
	window.addEventListener( "pageshow", function ( event ) {
		var historyTraversal = event.persisted || ( typeof window.performance != "undefined" && window.performance.navigation.type === 2 );
		if ( historyTraversal ) {
			window.location.reload();
		}
	});
</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();
?>
