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

if ( GetSetting('portal','useRights',0) == 1 && !IsUserLogin()){
	ob_end_flush();
	exit;
}


$cn = db_connect();
$url = getCurPageURL('service/');
$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);	
}

$mainskbranch = db_getMainSKBranch($cn);

if (getCookieForPage('firstvisit') === NULL ) {
	setCookieForPage("firstvisit", TRUE);
	setCookieForPage('filter-active', TRUE);
	setCookieForPage('filter-stopped', TRUE);
	header("Location: ".getCurPageURL('service/'));
	ob_end_flush();
	exit;
}

$usr_arr = GetUserIDs();
$polltypes = db_getPollTypesList($cn, $_SESSION['user_idlanguagecontent'], $usr_arr[0]);

if(sizeof($_REQUEST) == 0) {
	$urlFromCookies = getCurPageURL('service/');
	if (getCookieForPage('filter-completed') === NULL && getCookieForPage('filter-uncompleted') === NULL ) {
		$urlFromCookies = urlReplaceParam($urlFromCookies,'filter-uncompleted', 'filter-uncompleted');
	}
	
	if (getCookieForPage('filter-completed') !== NULL ) {
		$urlFromCookies = urlReplaceParam($urlFromCookies,'filter-completed', 'filter-completed');
	}
	
	if (getCookieForPage('filter-uncompleted') !== NULL ) {
		$urlFromCookies = urlReplaceParam($urlFromCookies,'filter-uncompleted', 'filter-uncompleted');
	}

	if (getCookieForPage('filter-active') !== NULL ) {
		$urlFromCookies = urlReplaceParam($urlFromCookies,'filter-active', 'filter-active');
	}

	if (getCookieForPage('filter-stopped') !== NULL ) {
		$urlFromCookies = urlReplaceParam($urlFromCookies,'filter-stopped', 'filter-stopped');
	}

	if (getCookieForPage('filter-notactive') !== NULL ) {
		$urlFromCookies = urlReplaceParam($urlFromCookies,'filter-notactive', 'filter-notactive');
	}

	for($i=0; $i<sizeof($polltypes); $i++){
		$skpolltype = 'filter-skpolltype_'.$polltypes[$i]['skpolltype'];
		if (getCookieForPage($skpolltype) !== NULL ) {
			$urlFromCookies = urlReplaceParam($urlFromCookies,$skpolltype, $skpolltype);
		}
	}
	
	if( $urlFromCookies !== getCurPageURL('service/') ){
		header("Location: ".$urlFromCookies);
		ob_end_flush();
		exit;
	}
}

	// settings
	$onpage = getSetting('page', 'polls.pagesize', 20);
	$default_order_column = getCookieForPage('order_column','updatedate'); 
	$default_order_val = getCookieForPage('order_val','asc');
	// 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;
	setCookieForPage("order_column", $order_column);
	setCookieForPage("order_val", $order_val);

	$page = isset( $_GET[ "page" ] ) ? $_GET[ "page" ] : 1;
	$url = buildTableTitleURL( $order_column, $order_val, 'service/');

	db_getPollsList($cn, $usr_arr, $contlngid);

	$resarr = array();

	$q_st = "SELECT COUNT(0) as cnt FROM (SELECT distinct * FROM `pollsresult`) Q";
	$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 *, DATE_FORMAT(startdate, \'%d.%m.%Y\') as startdateformated, DATE_FORMAT(enddate, \'%d.%m.%Y\') as enddateformated,  DATE_FORMAT(from_unixtime(updatedate_tmst), "%d.%m.%Y") as updatedate FROM `pollsresult` ';
	$filter_skpolltype = ' 1 = 2 '; //Task 59710
	$filter_status = ' status = -1 ';
	$filter_percent = '';
	$filter = '';

	foreach ( $_REQUEST as $key => $value ) {
		$ind = stripos($key,'filter-skpolltype_');
		if ($ind !== false) {
			$filter_skpolltype .=  ($filter_skpolltype == '' ? '' : ' OR ' ).'skpolltype = '.substr($key, $ind + strlen('filter-skpolltype_'));
		}
	}

	$filter = ($filter_skpolltype == '' ? '' : ' WHERE ( '.$filter_skpolltype.')');

	setCookieForPage('filter-active', NULL);
	setCookieForPage('filter-stopped', NULL);
	setCookieForPage('filter-notactive', NULL);

	if (isset($_REQUEST['filter-active'])) {
		$filter_status .= ($filter_status == '' ? '' : ' OR ' ).' status = 1 ';
		setCookieForPage('filter-active', 'filter-active');
	}
	if (isset($_REQUEST['filter-stopped'])) {
		$filter_status .= ($filter_status == '' ? '' : ' OR ' ).' status = 0 ';
		setCookieForPage('filter-stopped', 'filter-stopped');
	}
	if (isset($_REQUEST['filter-notactive'])) {
		$filter_status .= ($filter_status == '' ? '' : ' OR ' ).' status = 2 ';
		setCookieForPage('filter-notactive', 'filter-notactive');
	}
	
	if ($filter === '' && $filter_status !== ''){
		$filter = ' WHERE ( '.$filter_status.')';
	} else if ($filter !== '' && $filter_status !== ''){
		$filter = $filter.' AND ( '.$filter_status.')';
	}

	setCookieForPage('filter-uncompleted', NULL);
	setCookieForPage('filter-completed', NULL);

	$filter_percent = ' progress_percent = -1 ';
	if (isset($_REQUEST['filter-completed']) && isset($_REQUEST['filter-uncompleted'])){
		setCookieForPage('filter-completed', 'filter-completed');
		setCookieForPage('filter-uncompleted', 'filter-uncompleted');
		$filter_percent = ' progress_percent != -1 ';
	} else if (isset($_REQUEST['filter-completed'])){
		$filter_percent = ' progress_percent = 100 ';
		setCookieForPage('filter-completed', 'filter-completed');
	} else if (isset($_REQUEST['filter-uncompleted'])){
		$filter_percent = ' progress_percent < 100 ';
		setCookieForPage('filter-uncompleted', 'filter-uncompleted');
	}

	if ($filter === '' && $filter_percent !==''){
		$filter = ' WHERE ( '.$filter_percent.')';
	} else if ($filter !== '' && $filter_percent !== ''){
		$filter = $filter.' AND ( '.$filter_percent.')';
	}

	$q_st.= $filter;

	if ($order_column != "") {
		$q_st.= " ORDER BY ".$order_column."  ".$order_val." ";
	}
	$q_st.= "LIMIT ".(($page - 1) * $onpage).",".$onpage.";";

	$resarr = db_runQueryAndReturnArray($cn,$q_st);
	$size=sizeof($resarr);

	if ($size < 1) {
		echo '<div id="nopollsmatchingfilter">'.getResourceByLang('message.nopollsmatchingfilter').'</div>';
	} else {
?>
<table class="tbldata" cellspacing="0">
  <tr>
    <th class="<? if( $order_column == "source_name" ) echo "tbldata-cell-sortable" ?> tblinput-cell-name">
      <? echo buildSortColumnTitle( getResourceByLang('field.polls.survey'), ( $order_column == "source_name" ? true : false ), "source_name", $order_val, 'service/' ) ?>
    </th>
    <th class="<? if( $order_column == "progress_percent" ) echo "tbldata-cell-sortable" ?> tblinput-cell-name">
      <? echo buildSortColumnTitle( getResourceByLang('field.polls.progress'), ( $order_column == "progress_percent" ? true : false ), "progress_percent", $order_val, 'service/' ) ?>
    </th>
    <th class="<? if( $order_column == "updatedate_tmst" ) echo "tbldata-cell-sortable" ?> tblinput-cell-name">
      <nobr>
        <? echo buildSortColumnTitle( getResourceByLang('field.polls.updatedate'), ( $order_column == "updatedate_tmst" ? true : false ), "updatedate_tmst", $order_val, 'service/' ) ?>
      </nobr>
    </th>
    <th class="tblinput-cell-name">
      <? echo getResourceByLang('field.polls.details'); ?>
    </th>
  </tr>
<?php	
	for($i=0; $i<$size; $i++){
		?>
  <tr>
    <td valign="top" class="clear-padding">
      <table class="in-row-table" cellspacing="0" cellpadding="0">
        <tr>
          <td valign="top" class="in-row-table-td">
            <? echo '<a href="poll.php?&idpolltype='.$resarr[ $i ][ "idpolltype" ]."&".($resarr[ $i ][ "skbranch" ] == 0 ? 'skproject='.$resarr[ $i ][ "skproject" ] : 'skbranch='.$resarr[ $i ][ "skbranch" ]).'">'.$resarr[ $i ][ "polltype_name" ].': '.$resarr[ $i ][ "source_name" ].'</a>'; ?>
          </td>
          <td valign="middle" class="in-row-table-td hright">
            <nobr>
                <i title="<? echo getResourceByLang('button.poll.instruction.hint') ?>" 
                  <? echo 'href="skpolltype-html'.$resarr[ $i ][ "skpolltype" ].'"'?> class="dialog-html-show-link fal fa-question-circle font-awesome-color font-awesome-size">
                </i>
            </nobr>
          </td>
        </tr>
      </table>
    </td>
    <td valign="top">
      <nobr>
        <? echo $resarr[ $i ][ "progress_percent" ]."% (".$resarr[ $i ][ "progress" ]." / ".$resarr[ $i ][ "progress_of"].")"; ?>
      </nobr>
    </td>
    <td valign="top">
      <? echo $resarr[ $i ][ "updatedate" ] ?>
    </td>
    <td valign="top" class="nowrap">
		<? $status = $resarr[ $i ][ "status" ]; 
					$prjlink = "";
					$finishdate = "";
					if ($resarr[ $i ][ "skbranch" ] == 0 ) {
						$prj = db_getProjectBySkProject($cn, $resarr[ $i ][ "skproject"]);
						if (is_array($prj) && sizeof($prj) > 0 && db_isObjectExits($cn, $prj[0]["idproject"], $mainskbranch) && db_getUserRightsToObject($cn, $usr_arr,  $prj[0]["idproject"])) {
							$prjlink = getCurPageURLWO('service')."businessmodel.php?oguid=".$prj[0]["idproject"]; 
						}
						$finishdate = db_getPollFinishDateBySkroject($cn, $resarr[ $i ][ "skpolltype"], $resarr[ $i ][ "skproject" ]);
					} else {
						$finishdate = db_getPollFinishDateBySkBranch($cn, $resarr[ $i ][ "skpolltype"], $resarr[ $i ][ "skbranch" ]);
					}
					echo '<table class="project-description" >';
					echo "<tr><td>".getResourceByLang("title.polls.status").":&nbsp;</td><td>".getResourceByLang("title.polls.status.".$status).'</td></tr>'
					.($finishdate != "" 
						? '<tr><td>'.getResourceByLang("title.poll.finishdate").':&nbsp;</td><td>'.$finishdate.'</td></tr>'
						: '')
					."<tr><td>".getResourceByLang("field.polls.source").":&nbsp;</td><td>"
						.($resarr[ $i ][ "skbranch" ] == 0 
						? ($prjlink == "" ? getResourceByLang("title.polls.source.project") : "<a href='".$prjlink."' target='_parent'>".getResourceByLang("title.polls.source.project")."</a>")
						: getResourceByLang("title.polls.source.branch") )
					.'</td></tr>'
					.'</table>'; 
			?>
	</td>
</tr>
<?php
		}
?>
</table>
<?php
	}
?>

<?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 }?>

<?php
	$q_st = 'SELECT DISTINCT `polls`.skpolltype, res_pt.rft_columnname_long as polltype_description     
		     FROM `polls` INNER JOIN  `resourcefromtables` res_pt ON `skpolltype` = res_pt.`idrecord` AND res_pt.`idtable` = 801 AND res_pt.idlanguage = '.$contlngid.' ; ';
	$resarr = db_runQueryAndReturnArray($cn,$q_st);
	$size=sizeof($resarr);
	for($i=0; $i<$size; $i++){
		?>
  <div id="skpolltype-html<? echo $resarr[ $i ][ "skpolltype" ]?>" class="dialog" style="min-width:50%; min-height:80%;">
			
  <div id="dialog-titlebar" class="titlebar"></div>
  <div class="content">
    <? echo $resarr[ $i ][ "polltype_description" ]?>
			
  </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 `polls`.skproject, res_prj.rft_columnname_long as project_description     
	FROM `polls` INNER JOIN  `resourcefromtables` res_prj ON `skproject` = res_prj.`idrecord` AND res_prj.`idtable` = 1001 AND res_prj.idlanguage = '.$contlngid.'
	WHERE skproject IS NOT NULL ;';
	
	$resarr = db_runQueryAndReturnArray($cn,$q_st);
	$size=sizeof($resarr);

	for($i=0; $i<$size; $i++){
		?>

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