<?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'; }
$ids = implode(",", $u_ids);
?>
<div class="tbldata-wide"> 
<table class="tbldata" cellspacing="0">
					<tr>
						<th class="tblinput-cell-name" style="width:35%"><? echo getResourceByLang('field.poll.object'); ?></th>
						<th class="tblinput-cell-name" style="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.polls.progress'); ?></th>
						<th class="tblinput-cell-name" style="width:15%"><? echo getResourceByLang('field.poll.answers'); ?></th>
					</tr>
<?php
	$answers = NULL;
	if (!isset($_REQUEST['answers-has']) && isset($_REQUEST['answers-hasnot']))
		$answers = 'hasnot';
	if (!isset($_REQUEST['answers-hasnot']) && isset($_REQUEST['answers-has']))
		$answers = 'has';
	
	$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])) {
		$resarr = $_SESSION['adminpoll_p_'.$uiid.$page];
		$total = $_SESSION['adminpoll_total'.$uiid];
		$size=sizeof($resarr);
	} else {
		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 ';
		}		
	
		if (isset($_REQUEST['detail']) && isset($_REQUEST['skpollingobject']) && isset($_REQUEST['skpolltype'])) {
			$resarr = db_runQueryAndReturnArray($cn, $q_st);
			$size=sizeof($resarr);
			for($i=0; $i< $size; $i++){
				if ($_REQUEST['skpollingobject'] == $resarr[$i]['skpollingobject'] && $_REQUEST['skpolltype'] == $resarr[$i]['skpolltype']){
					$page = (ceil(($i+1) / $onpage) < 1 ? 1 : ceil(($i+1) / $onpage));
					break;
				}
			}
		}
	
		$q_st.= "LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
		$resarr = db_runQueryAndReturnArray($cn,$q_st);
		session_start();
		$_SESSION['adminpoll_p_'.$uiid.$page] = $resarr;
		$_SESSION['adminpoll_total'.$uiid] = $total;
		session_write_close();
		$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" ]);
		}
		?>
			<tr>
				<td class="<?php echo $borderclass;?>" valign="top"><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" ].'&idpolltype='.$resarr[ $i ][ "idpolltype" ]/* Task 63881 открывать с рецензией */.'&skbranch='.$resarr[ $i ][ "skbranch" ].'&oguid='.$resarr[ $i ][ "o_guid" ].'&rguid='.$resarr[ $i ][ "r_guid" ].(isset($_REQUEST['skproject']) ? '&skproject='.$_REQUEST['skproject'] : '').'">'.$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" ]) || 
						($i < $size -1 && $resarr[ $i+1 ][ "skbranch" ] != $resarr[ $i ][ "skbranch" ] && $resarr[ $i+1 ][ "o_guid" ] == $resarr[ $i ][ "o_guid" ])
						) {
							echo '<nobr>';
							getResource("title.polls.objectfromaltbranch"); 
							echo '</nobr>';
							echo ': <br>'.db_getBranchName($cn, $resarr[ $i ][ "skbranch" ], $contlngid);
 					}
					?>
				</td>
				<td class="<?php echo $borderclass;?>" valign="top"> 
				<nobr><? echo $resarr[ $i ][ "progress_percent" ]."% (".$resarr[ $i ][ "progress" ]." / ".$resarr[ $i ][ "progress_of"].")"; ?></nobr>
				</td>
				
				<td class="<?php echo $borderclass;?> load-answers-section" valign="top" <?php echo "skpollingobject='".$resarr[ $i ][ "skpollingobject" ]."' skpolltype='".$resarr[ $i ][ "skpolltype" ]."'"?>>
					<?php
					echo "<div style='margin-top: 0px;' href='dialog-thorough-form' class='dialog-thorough dialog-html-show-link admin-pollingobject-answerdetails-link' title='";
					getResource("title.thorough");
					echo "' dialogbuttons='visible' dialoghref='pollobjectanswersbyuserdetails.php?skpollingobject=".$resarr[ $i ][ "skpollingobject"].'&skpolltype='.$resarr[ $i ][ "skpolltype"]."' >";
					getResource("title.thorough");					
					echo "</div><br/>";
					?>
				</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, true);?>
				</section>
<?php }?>
		</div>


	<?php 
	//69265
	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 }?>

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