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

$contlng = null;
$contlngid = null;

if (getSetting('portal','useRights',0) == 1){
	$contlng = 'lang='.db_getLanguageShortByID($cn, $_SESSION['user_idlanguagecontent']);
	$contlngid = $_SESSION['user_idlanguagecontent'];
}

$hideheader = (isset($_COOKIE['mobilemode']) ?  $_COOKIE['mobilemode'] : 0);

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=admin.php");
		ob_end_flush();
		exit;
	}

	if (!isUserAdmin()) {
		header("Location: ".getCurPageURLWO()."/personal.php");
		ob_end_flush();
		exit;
	}

	$oguid = null;
	$rguid = null;
	$oid = null;

	if (isset($_REQUEST['oid'])){
		$oid = $_REQUEST['oid'];
	} else {
		header("Location: ".getCurPageURLWO()."/service/empty.php");
		ob_end_flush();
		exit;
	}

	$cdepth = 0;
	$mdepth = 0;
	$obj = db_getObjectDataById($cn, $oid);
	$oguid = $obj["o_guid"];
	$cdepth = $obj["o_depth"];
	$skbranch = $obj["skbranch"];

	$trSt = db_getReportsToObjectAdmin($cn, $oguid, $contlngid, $skbranch);
	if (isset($_REQUEST['rguid'])){
		$rguid = $_REQUEST['rguid'];
	} else if (sizeof($trSt) > 0) {
		$rguid = $trSt[0]['r_guid'];
	}

	$mdepth = db_getMaxObjectDepthFromParetn($cn, $obj["o_ileft"], $obj["o_iright"]);

	if ( isset($_REQUEST['selobjects']) && $_REQUEST['selobjects'] != ''){
	    $selobjects = explode(",",$_REQUEST['selobjects']);
	} else {
	    $selobjects = array();
	}
	$selobjects = array_diff($selobjects, array(''));
   	$sall = ( isset($_REQUEST['sall']) && $_REQUEST['sall'] == 1) ? 1 : 0 ;
}
?>
<!doctype html>
<html>
<head>
	<title><?php echo renderTitle();?></title>
	<? 
	renderCommonMeta(renderTitle()); 
	?>
	<link rel="stylesheet" href="css/reset.css">
	<link rel="stylesheet" href="css/style.css">
</head>
<body id="page-administration-internal">
	<?php renderModalHourGlassDiv();?>
	<section id="box-administration" class="clearfix">
				<form id="refresh" name="refresh" action="" method="post">
				<div id="box-filter-form">
					<label><?php getResource("field.Levels");?>:</label>
					<select id="dlevel" name="dlevel" >
					<?php
					$lst_i = $mdepth - $cdepth;
					for($i=1; $i<$lst_i + 1; $i++){
						echo '<option value="'.$i.'" ';
						if (isset($_REQUEST['dlevel']) && $i == $_REQUEST['dlevel'] ) {
							echo ' selected="selected">';
						} else {
							echo " >";
						}
						echo $i.'</option> ';
					}
					?>
					</select>
					<label style="margin-left: 20px;"><?php getResource("field.Report");?></label>
					<select id="rguid" name="rguid" >
					<?php
						$size=sizeof($trSt);
						$sl = (!($rguid === null )) ? $rguid : '' ;
						for($i=0; $i<$size; $i++){
							if ($sl == $trSt[$i]['r_guid'] ) {
								echo '<option value="'.$trSt[$i]['r_guid'].'" selected="selected">';
							} else {
								echo '<option value="'.$trSt[$i]['r_guid'].'">';
							}
								echo $trSt[$i]['r_name'];
							echo '</option> ';
						}
						unset($trSt);
					?>
					</select>
            		<span style="margin-left: 20px;"><button class="btn-top btn-top-text" title="<?php getResource("button.refreshReport");?>"><span><?php getResource("button.refreshReport");?></span></button></span>
					<input type="hidden" name="oid" value="<?php echo $oid;?>"/>
					<input type="hidden" name="page" value="1"/>
					<input type="hidden" name="update" value="true"/>
					<input type="hidden" name="selobjects" value=""/>
					<input type="hidden" id="_sall" name="sall" value="0"/>
					<input type="hidden" id="_sobject" name="sobject" value=""/>
				</div>
				</form>


						<?php
						$order = '';
						$depth = $cdepth;
						if (isset($_REQUEST['dlevel'])) {
							$depth = $depth + $_REQUEST['dlevel'];
						} else {
							$depth = $depth + 1;
						}
						if (isset($_REQUEST['clearrat'])) {
							db_clearReportDataRatingforObjects($cn, $selobjects, $rguid, $skbranch);
						} else if (isset($_REQUEST['clearcnt'])) {
							db_clearReportDataViewCountforObjects($cn, $selobjects, $rguid, $skbranch);
						} else if (isset($_REQUEST['clearmsg'])) {
							db_clearForumMessagesforObjects($cn, $selobjects, $skbranch);
						}

						db_setTimeZone($cn);
						$query = " CALL load_objects_admin( ".$oid.", ".($depth + 1).", '".$rguid."', ".$skbranch." );";
						db_runQuery($cn, $query);
						$oarr = array();

						$q_st = "SELECT COUNT(*) as cnt FROM admin_temp;";
						$result = $cn->query($q_st);
						if ($result) {
							$row = null;
							while ($row = $result->fetch_assoc()) {
								array_push($oarr, $row);
							}
						}
						$total = $oarr[0]['cnt'];

						$onpage = 20;
						$total = ceil($total/$onpage); //Также вычисляем сколько у нас будет ссылок
						$total = $total == 0 ? 1 : $total;
						$page = (isset($_REQUEST['page']) ? $_REQUEST['page'] : 1 );
						$page = (($page > $total) ? $total : $page);

						if ($sall == 1) {
							$selobjects = array();
							$q_st = "SELECT idobject FROM admin_temp;";
							$result = $cn->query($q_st);
							if ($result) {
								$row = null;
								while ($row = $result->fetch_assoc()) {
									array_push($selobjects, $row['idobject']);
								}
							}

						}


						$url = getCurPageURL();
?>
				<form action="" method="post" id="form_chk" name="form_chk">
				<input type="hidden" id="selobjects" name="selobjects" value="<?php echo implode(",", $selobjects);?>"/>
				<input type="hidden" id="rguid" name="rguid" value="<?php echo $rguid; ?>"/>
				<input type="hidden" id="sall" name="sall" value="<?php echo $sall; ?>"/>
				<input type="hidden" id="sobject" name="sobject" value=""/>
				<input type="hidden" id="page" name="page" value="<?php ( (!isset($_REQUEST['page'])) ? print('1') : print($_REQUEST['page']));?>"/>
				<input type="hidden" id="dlevel" name="dlevel" value="<?php ( (!isset($_REQUEST['dlevel'])) ? print('1') : print($_REQUEST['dlevel'])); ?>"/>
  		        <input type="hidden" id="lang" name="lang" value="<?php echo getLanguage()?>"/>
				<table class="tbldata tbldata-admin" cellspacing="0">
					<tr >
						<th class="tblinput-cell-checkbox"><input type="checkbox" name="CheckBoxAll" id="CheckBoxAll" onclick="mySubmitSAll(<?php (($sall == 1 ) ? print('0') : print('1')); ?>)" <?php if ( $sall == 1 ) { print('checked'); }; ?>/></th>
						<th class="tblinput-cell-name"><nobr><a style="color: #FFFFFF; text-decoration: none;" href="<?php echo urlReplaceParam(urlReplaceParam($url,'sort', null),'order', null); ?>"><?php getResource("field.statistic.elenents");?></a></nobr></th>
						<?php if (isset($_REQUEST['order']) && $_REQUEST['order'] == 'at_rating' ) { ?>
						<th class="tbldata-cell-sortable tblinput-cell-name"><nobr><a style="color: #FFFFFF; text-decoration: none;" href="<?php echo urlReplaceParam(urlReplaceParam($url,'sort', (isset($_REQUEST['sort']) && $_REQUEST['sort'] == 'asc' ? 'desc' : 'asc')),'order', 'at_rating'); ?>"><?php if (isset($_REQUEST['sort']) && $_REQUEST['sort'] == 'desc') { print('<button class="btn-sort btn-sort-desc" title="&uarr;">&uarr;</button>'); } else { print('<button class="btn-sort btn-sort-asc" title="&darr;">&darr;</button>');}?> <?php getResource("field.statistic.avg");?></a></nobr></th>
						<?php } else { ?>
						<th class="tblinput-cell-input"><nobr><a style="color: #FFFFFF; text-decoration: none;" href="<?php echo urlReplaceParam(urlReplaceParam($url,'sort','asc'),'order', 'at_rating'); ?>"><?php getResource("field.statistic.avg");?></a></nobr></th>
						<?php } ?>


						<?php if (isset($_REQUEST['order']) && $_REQUEST['order'] == 'at_viewcount' ) { ?>
						<th class="tbldata-cell-sortable tblinput-cell-name"><nobr><a style="color: #FFFFFF; text-decoration: none;" href="<?php echo urlReplaceParam(urlReplaceParam($url,'sort', (isset($_REQUEST['sort']) && $_REQUEST['sort'] == 'asc' ? 'desc' : 'asc')),'order', 'at_viewcount'); ?>"><?php if (isset($_REQUEST['sort']) && $_REQUEST['sort'] == 'desc') { print('<button class="btn-sort btn-sort-desc" title="&uarr;">&uarr;</button>'); } else { print('<button class="btn-sort btn-sort-asc" title="&darr;">&darr;</button>');}?> <?php getResource("field.statistic.views");?></a></nobr></th>
						<?php } else { ?>
						<th class="tblinput-cell-input"><nobr><a style="color: #FFFFFF; text-decoration: none;" href="<?php echo urlReplaceParam(urlReplaceParam($url,'sort', 'asc'),'order', 'at_viewcount'); ?>"><?php getResource("field.statistic.views");?></a></nobr></th>
						<?php } ?>

						<?php if (isset($_REQUEST['order']) && $_REQUEST['order'] == 'at_msgcnt' ) { ?>
						<th class="tbldata-cell-sortable tblinput-cell-name"><nobr><a style="color: #FFFFFF; text-decoration: none;" href="<?php echo urlReplaceParam(urlReplaceParam($url,'sort', (isset($_REQUEST['sort']) && $_REQUEST['sort'] == 'asc' ? 'desc' : 'asc')),'order', 'at_msgcnt'); ?>"><?php if (isset($_REQUEST['sort']) && $_REQUEST['sort'] == 'desc') { print('<button class="btn-sort btn-sort-desc" title="&uarr;">&uarr;</button>'); } else { print('<button class="btn-sort btn-sort-asc" title="&darr;">&darr;</button>');}?> <?php getResource("field.statistic.messages");?></a></nobr></th>
						<?php } else { ?>
						<th class="tblinput-cell-input"><nobr><a style="color: #FFFFFF; text-decoration: none;" href="<?php echo urlReplaceParam(urlReplaceParam($url,'sort', 'asc'),'order', 'at_msgcnt'); ?>"><?php getResource("field.statistic.messages");?></a></nobr></th>
						<?php } ?>

						<?php if (isset($_REQUEST['order']) && $_REQUEST['order'] == 'at_msglastdate' ) { ?>
						<th class="tbldata-cell-sortable tblinput-cell-name"><nobr><a style="color: #FFFFFF; text-decoration: none;" href="<?php echo urlReplaceParam(urlReplaceParam($url,'sort', (isset($_REQUEST['sort']) && $_REQUEST['sort'] == 'asc' ? 'desc' : 'asc')),'order', 'at_msglastdate'); ?>"><?php if (isset($_REQUEST['sort']) && $_REQUEST['sort'] == 'desc') { print('<button class="btn-sort btn-sort-desc" title="&uarr;">&uarr;</button>'); } else { print('<button class="btn-sort btn-sort-asc" title="&darr;">&darr;</button>');}?> <?php getResource("field.statistic.messagelastdate");?></a></nobr></th>
						<?php } else { ?>
						<th class="tblinput-cell-input"><nobr><a style="color: #FFFFFF; text-decoration: none;" href="<?php echo urlReplaceParam(urlReplaceParam($url,'sort', 'asc'),'order', 'at_msglastdate'); ?>"><?php getResource("field.statistic.messagelastdate");?></a></nobr></th>
						<?php } ?>

					</tr>
<?php
						$sort = (isset($_REQUEST['sort']) ? $_REQUEST['sort'] : 'asc');
						$query = "SELECT res.rft_columnname_text as o_name, obj.idobject, obj.parent_idobject, obj.o_ileft, obj.o_iright, obj.o_depth, obj.o_guid, obj.o_icon, obj.o_datechange, CASE `at_rating` WHEN 0 THEN NULL ELSE `at_rating` END as `at_rating`, `at_viewcount`, `at_msgcnt`, `at_msglastdate`, obj.o_hasreports, obj.o_useinsearch 
						     FROM objects as obj INNER JOIN admin_temp as oto ON obj.idobject = oto.idobject  
							 INNER JOIN resourcefromtables as res ON obj.idobject = res.idrecord
							WHERE res.idlanguage = ".$contlngid."
							  AND res.skbranch = ".$skbranch."
							  AND obj.skbranch = ".$skbranch."
							  AND res.idtable = 1
							ORDER BY ".(isset($_REQUEST['order']) ? $_REQUEST['order'].' '.$sort.' ' : 'o_ileft')."
						 LIMIT ".(($page - 1) * $onpage).",".$onpage.";";
						 $oarr = array();
                        /* execute multi query */
						if ($cn->multi_query($query)) {
						$result = $cn->store_result();
							if ($result) {
								$row = null;
								while ($row = $result->fetch_assoc()) {
									array_push($oarr, $row);
								}
								$result->close();
							}
						}

						$size=sizeof($oarr);
						$mainSKBranch = db_getMainSKBranch($cn);
						for($i=0; $i<$size; $i++){
							echo '<tr>';
							echo '<td class="tblinput-cell-checkbox"><input class="checkbox_for_report" type="checkbox" onclick="CheckChange(this.id);" id="'.$oarr[$i]['idobject'].'"';
							if ( in_array($oarr[$i]['idobject'], $selobjects )){
	                            echo ' checked ';
							}
							echo '/></td>';

							echo '<td>';
							for($d=$cdepth; $d<$oarr[$i]['o_depth']; $d++){
								echo "&nbsp&nbsp";
							}

							$linkprepare = ($mainSKBranch == $skbranch ? "/businessmodel.php?" : "/pollobject.php?skbranch=".$skbranch."&");

							echo '&nbsp;<img src="'.getCurPageSubFolders().'/'.getImgIcon($oarr[$i]['o_icon']).'" />&nbsp;&nbsp;<a target="_parent" href="'.getCurPageSubFolders().$linkprepare.'oguid='.$oarr[$i]['o_guid'].'">'.$oarr[$i]['o_name'].'</a>'.
								'</td><td>'.($oarr[$i]['at_rating'] ? round($oarr[$i]['at_rating']) : '').'</td><td>'.$oarr[$i]['at_viewcount'].
								'</td><td>'.$oarr[$i]['at_msgcnt'].'</td><td>'.$oarr[$i]['at_msglastdate'];

							echo '</td>';
							echo '</tr>';

						}
						unset($oarr);
						?>
				</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 } ?>
	</section>

<?php    if (is_array($selobjects) && count($selobjects) > 0) { ?>
	<section id="box-buttons">
		<span><button class="btn-top btn-top-text btn-top-w170" id="clearrat" name="clearrat" onclick="form_confirm('<?php getResource("confirm.clearrat");?>');" title="<?php getResource("button.clearrat.hint");?>"><span><?php getResource("button.clearrat");?></span></button></span>&nbsp;&nbsp;&nbsp;&nbsp;<br /><br />
		<span><button class="btn-top btn-top-text btn-top-w170" id="clearcnt" name="clearcnt" onclick="form_confirm('<?php getResource("confirm.clearcnt");?>');" title="<?php getResource("button.clearcnt.hint");?>"><span><?php getResource("button.clearcnt");?></span></button></span>&nbsp;&nbsp;&nbsp;&nbsp;<br /><br />
		<span><button class="btn-top btn-top-text btn-top-w170" id="clearmsg" name="clearmsg" onclick="form_confirm('<?php getResource("confirm.clearmsg");?>');" title="<?php getResource("button.clearmsg.hint");?>"><span><?php getResource("button.clearmsg");?></span></button></span>&nbsp;&nbsp;&nbsp;&nbsp;
	</form>
 <?php } else { ?>
	<section id="box-buttons">
		<span><button disabled class="btn-top btn-top-text btn-top-w170 btn-top-text-disabled" id="clearrat" name="clearrat" onclick="form_confirm('<?php getResource("confirm.clearrat");?>');" title="<?php getResource("button.clearrat.hint");?>"><span><?php getResource("button.clearrat");?></span></button></span>&nbsp;&nbsp;&nbsp;&nbsp;<br /><br />
		<span><button disabled class="btn-top btn-top-text btn-top-w170 btn-top-text-disabled" id="clearcnt" name="clearcnt" onclick="form_confirm('<?php getResource("confirm.clearcnt");?>');" title="<?php getResource("button.clearcnt.hint");?>"><span><?php getResource("button.clearcnt");?></span></button></span>&nbsp;&nbsp;&nbsp;&nbsp;<br /><br />
		<span><button disabled class="btn-top btn-top-text btn-top-w170 btn-top-text-disabled" id="clearmsg" name="clearmsg" onclick="form_confirm('<?php getResource("confirm.clearmsg");?>');" title="<?php getResource("button.clearmsg.hint");?>"><span><?php getResource("button.clearmsg");?></span></button></span>&nbsp;&nbsp;&nbsp;&nbsp;
	</form>
 <?php } ?>

	</section>
	<br/>
	<br/>
	<br/>
<?php renderFooterTemplate(); ?>
</body>

<script>
	// global params
	var gCloseTitle = "<?php getResource('title.close');?>";
	var gOpenTitle = "<?php getResource('title.open');?>";
	var gResizeTitle = "<?php getResource('title.resize');?>";
</script>
<script src="js/libs/jquery.js"></script>
<script src="js/script.js"></script>
<script>
    $('#refresh').submit(function(){
  		ShowModalWindow(true);
	});

	function form_confirm(msg) {
		if (window.confirm(msg)) {
      		ShowModalWindow(true);
      		form_chk.submit();
   		}
	}

	function CheckChange(id) {
		var values = $('#selobjects').last().val();
		var arr = values.split(",");

		if ($.inArray(id,arr) > -1) {
			arr = $.grep(arr, function(value) {
  				return value != id;
			});
		} else {
			arr.push(id);
		}
		$('#selobjects').last().val(arr);
     	$('#sall').attr('value',0);
     	$("#CheckBoxAll").prop("checked", false);
     	CheckButtonsEnable();
	}

	function CheckButtonsEnable() {
		var values = $('#selobjects').last().val();
		var arr = values.split(",");
		if (values.length > 0 || arr.length > 1) {
            $("#clearrat").removeAttr('disabled').removeClass("btn-top-text-disabled");
            $("#clearcnt").removeAttr('disabled').removeClass("btn-top-text-disabled");
            $("#clearmsg").removeAttr('disabled').removeClass("btn-top-text-disabled");
     	} else {
            $("#clearrat").attr('disabled','disabled').addClass("btn-top-text-disabled");
            $("#clearcnt").attr('disabled','disabled').addClass("btn-top-text-disabled");
            $("#clearmsg").attr('disabled','disabled').addClass("btn-top-text-disabled");
     	}
	}

    function mySubmitSAll(val) {
		if (val == 0) {
			$("#CheckBoxAll").prop("checked", false);
			$(".checkbox_for_report").prop("checked", false);
			$('#selobjects').last().val('');
		} else {
			$("#CheckBoxAll").prop("checked", true);
			$(".checkbox_for_report").prop("checked", true);
		}
     	$('#sall').attr('value',val);
     	ShowModalWindow(true);
        form_chk.submit();
    }

  	function clickPage(page){
    	$("#page").val(page);
     	ShowModalWindow(true);
    	form_chk.submit();
    }

    $(document).ready(function()
	{
    	CheckButtonsEnable()
  	});
</script>
</html>
<?php
db_disconnect($cn);
ob_end_flush();
?>

