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

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);	
}
$usr_arr = GetUserIDs();
if ( GetSetting('portal','useRights',0) == 0 ){
	if( !IsUserLogin() ){
		header("Location: ".getCurPageURLWO()."/businessmodel.php");
		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']) || !db_isUserAssignedToPolls($cn, $_REQUEST['iduser']) ) {
	db_disconnect($cn);
	header("Location: ".getCurPageURLWO()."/pagenotfound.php?url=".getCurPageWithEncodeParams());
	ob_end_flush();
	exit;
}

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

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

$order_column = isset( $_GET[ "order_column" ] ) ? $_GET[ "order_column" ] : $default_order_column;
$order_val = isset( $_GET[ "order_val" ] ) ? $_GET[ "order_val" ] : $default_order_val;


$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(); 
	?>
</head>
<body>
<?php renderModalHourGlassDiv();?>
	<div id="container" style="overflow: hidden;">
		<div id="box-input-container" style="margin-bottom: 10px;">
			<div id="box-input-container" >		
					<div class="box-period-caption" style="margin-top: 9px;margin-bottom: 10px;">
						<?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);}  ?> \ <?php echo db_getUserNameByID($cn, $_REQUEST['iduser'], $contlngid); ?>
					</div>
			</div>
			<div id="box-input-container" >		
				<div class="box-period-caption" style="margin-top: 9px;margin-bottom: 10px;"><?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" style="margin-top: 5px;margin-bottom: 10px;"><?php getResource("title.Group");?>&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>
		</div>
		<div style="overflow: auto;height: calc(100% - 85px);"> <!--63840-->
			<table class="tbldata" cellspacing="0">
				<tr>
					<th style="width: 35%;" class="<? if( $order_column == "o_name" ) echo "tbldata-cell-sortable" ?> tblinput-cell-name"><? echo buildSortColumnTitle( getResourceByLang('field.poll.object'), ( $order_column == "o_name" ? true : false ), "o_name", $order_val, '' ) ?></th>
					<th class="tblinput-cell-name poll-extra" style="width:30%; display:none;"><? echo getResourceByLang('field.poll.extra'); ?></th>
					<th style="width: 15%;" class="<? if( $order_column == "answer_value" ) echo "tbldata-cell-sortable" ?> tblinput-cell-name"><? echo buildSortColumnTitle( getResourceByLang('field.poll.answer'), ( $order_column == "answer_value" ? true : false ), "answer_value", $order_val, '' ) ?></th>
					<th style="width: 50%;" class="tblinput-cell-name" ><? echo getResourceByLang('field.poll.comment'); ?></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_getPollsAnswerByRespondentForDetailsAdmin($cn, $usr_arr, $_REQUEST['iduser'], $contlngid, (isset($_REQUEST['idpolltype']) ? $_REQUEST['idpolltype'] : NULL), (isset($_REQUEST['skproject']) ? $_REQUEST['skproject'] : NULL),  (isset($_REQUEST['skbranch']) ? $_REQUEST['skbranch'] : NULL), $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 = "SELECT distinct `poll`.*,`folder`,   
		uav.uav_value, uav.uav_body, CASE WHEN ua_w.`hasanswer` = 1 THEN CASE WHEN pq.idpolltypequestiontype = 1 THEN res_pq.rft_columnname_text ELSE res_qsv.rft_columnname_text END ELSE '' END as answer_value, DATE_FORMAT(from_unixtime(uav_tmst),'%d.%m.%Y %H:%i') as uav_tmst
		FROM `poll` 
		LEFT JOIN fullfolders ON `poll`.`idobject` = `fullfolders`.`idobject` AND `fullfolders`.idlanguage = ".$contlngid." 
		INNER JOIN useranswers as ua_w ON `poll`.`skpollingobject` = ua_w.`skpollingobject` AND ua_w.iduser = ".$_REQUEST['iduser']."
		LEFT JOIN useranswersvalues as uav ON ua_w.iduser = uav.iduser AND ua_w.skpolltype = uav.skpolltype AND ua_w.skpollingobject = uav.skpollingobject 
		INNER JOIN `polltypequestions` as pq ON pq.skpolltype = ua_w.skpolltype 
		INNER JOIN `resourcefromtables` as res_pq ON res_pq.idrecord = pq.skpolltypequestion AND res_pq.idtable = 9 AND res_pq.idlanguage = ".$contlngid."
		INNER JOIN resourcefromtables rft ON rft.idtable = 6 AND rft.idrecord = ua_w.iduser AND rft.idlanguage = ".$contlngid."
		LEFT JOIN `polltypequestionselectvalues` as qsv ON qsv.skpolltypequestion = pq.skpolltypequestion AND qsv.skpolltypequestionselectvalue = uav.uav_value 
		LEFT JOIN `resourcefromtables` as res_qsv ON res_qsv.idrecord = qsv.skpolltypequestionselectvalue AND res_qsv.idtable = 90 AND res_qsv.idlanguage = ".$contlngid."
		ORDER BY `folder`, ".((isset($order_column) && mb_strlen($order_column) > 0) ? " ".$order_column." ".$order_val." " : " ");
	} else {
		$q_st = "SELECT distinct `poll`.*, '' as `folder`,
		uav.uav_value, uav.uav_body, CASE WHEN ua_w.`hasanswer` = 1 THEN CASE WHEN pq.idpolltypequestiontype = 1 THEN res_pq.rft_columnname_text ELSE res_qsv.rft_columnname_text END ELSE '' END as answer_value, DATE_FORMAT(from_unixtime(uav_tmst),'%d.%m.%Y %H:%i') as uav_tmst
		FROM `poll` 
		INNER JOIN useranswers as ua_w ON `poll`.`skpollingobject` = ua_w.`skpollingobject` AND ua_w.iduser = ".$_REQUEST['iduser']."
		LEFT JOIN useranswersvalues as uav ON ua_w.iduser = uav.iduser AND ua_w.skpolltype = uav.skpolltype AND ua_w.skpollingobject = uav.skpollingobject 
		INNER JOIN `polltypequestions` as pq ON pq.skpolltype = ua_w.skpolltype 
		INNER JOIN `resourcefromtables` as res_pq ON res_pq.idrecord = pq.skpolltypequestion AND res_pq.idtable = 9 AND res_pq.idlanguage = ".$contlngid."
		INNER JOIN resourcefromtables rft ON rft.idtable = 6 AND rft.idrecord = ua_w.iduser AND rft.idlanguage = ".$contlngid."
		LEFT JOIN `polltypequestionselectvalues` as qsv ON qsv.skpolltypequestion = pq.skpolltypequestion AND qsv.skpolltypequestionselectvalue = uav.uav_value 
		LEFT JOIN `resourcefromtables` as res_qsv ON res_qsv.idrecord = qsv.skpolltypequestionselectvalue AND res_qsv.idtable = 90 AND res_qsv.idlanguage = ".$contlngid.
			((isset($order_column) && mb_strlen($order_column) > 0) ? " ORDER BY ".$order_column." ".$order_val." " : " ");
	}		
	$q_st.= "LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
	$resarr = db_runQueryAndReturnArray($cn,$q_st);
	$size=sizeof($resarr);
	$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" ] && $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" ], $_REQUEST['iduser'], $contlngid );
		$answer = db_getPolltypeQuestionAnswer($cn, $resarr[ $i ][ "skpollingobject" ], $resarr[ $i ][ "skpolltype" ], $_REQUEST['iduser'] );
		$hashistory = db_hasPolltypeObjectHistory($cn, $resarr[ $i ][ "skpollingobject" ] );
		$ansval = '';
		if (is_array($question) && sizeof($question) > 0 && $question[0]['idpolltypequestiontype'] == 1){
			$ansval = $question[0]['rft_columnname_text'];
		} else if (is_array($question) && sizeof($question) > 0 && $question[0]['idpolltypequestiontype'] == 2 && is_array($answer) && sizeof($answer) > 0 && is_array($answer[0]) && sizeof($answer[0]) > 0 && isset( $answer[0]['uav_value']) && $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 target="_top" 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" ]./* Task 63995 (isset($_REQUEST['idpolltype']) ? '&idpolltype='.$_REQUEST['idpolltype'] : '').*/(isset($_REQUEST['skproject']) ? '&skproject='.$_REQUEST['skproject'] : '').'">'.$resarr[ $i ][ "o_name" ].' ('.$resarr[ $i ][ "r_name" ].')</a>'; ?> </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" ]) || 
						($i < $size -1 && $resarr[ $i+1 ][ "skbranch" ] != $resarr[ $i ][ "skbranch" ] && $resarr[ $i+1 ][ "o_guid" ] == $resarr[ $i ][ "o_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 
						$showArc = (isset($resarr[ $i ]['answer_value']) && isset($resarr[ $i ]['uav_value']) && $resarr[$i]['uav_value']>0 && getSetting('portal','polls.createarchive',0) == 1 && db_getPollingObjectsArchiveCount($cn, $resarr[ $i ][ "skpollingobject" ]) > 1); 
						if (isset($resarr[ $i ]['answer_value'])) {?>				
						<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="90%"><?php if (isset($resarr[ $i ]['answer_value']) ) { echo '<nobr>'.$resarr[ $i ]['answer_value'].'</nobr>';}?></td>
							</tr>
							<tr>
								<td class="poll-answerdetails-secondrow" style="<?php echo(!$showArc && !$allowComment ? 'padding-right: 0px;' : '');?>"><?php if (isset($resarr[ $i ]['answer_value'])) { echo '<nobr>'.$resarr[ $i ]['uav_tmst'].'</nobr>';}?></td>
							</tr>
						</table>  
					<? } ?>					
				</td>
				<td class="<?php echo $borderclass;?>" valign="top" style="width:40%">
					<?php echo $resarr[ $i ]['uav_body'];?>
				</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>

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