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

checkUserAndRedirectToLogin();
RedirectToModelAnonymous();

$cn = db_connect();
$url = getCurPageURL();
$urlWO = getCurPageURLWO();
$contlngid = $_SESSION['user_idlanguagecontent']; 
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 (isset($_REQUEST['command'])) {
  	$command = $_REQUEST['command'];
  	$id = (isset($_REQUEST['id']) ? $_REQUEST['id'] : -1);
  	if ($command == "up") {
		db_movePersonalLink($cn, $usr_arr[0], $id, -1);
  	} else if ($command == "down") {
		db_movePersonalLink($cn, $usr_arr[0], $id, 1);
  	} else if ($command == "del") {
	  	db_delPersonalLink($cn, $usr_arr[0], $id);
  	}
  	db_disconnect($cn);
	$url = getCurPageURLWO()."/personal.php";
	header("Location: ".$url); // вырезать из урла параметры но не язык
	ob_end_flush();
	exit;
}

if ( getSetting('portal','useRights',0) == 0 || getSetting('page','showpage.personal',0) == 0){
	header("Location: ".getCurPageURLWO()."/businessmodel.php");
	ob_end_flush();
	exit;
}

?>
<!doctype html>
<html>
<head>
	<title><?php echo renderTitle();?></title>
	<? 
	renderCommonMeta(renderTitle());
	renderCommonCSS(); 
	?>
</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">
			<section class="box-front front-menu clearfix">
<?php
	db_dropTempTable($cn, 't_ulinks');

	$query = "CREATE TEMPORARY TABLE `t_ulinks` (
	    `iduserlink` INT NOT NULL,
	    `idlink` INT NOT NULL,
	    `idsection` INT NOT NULL,
	    `ul_url` VARCHAR(5000) NOT NULL,
	    `lnk_type` INT NOT NULL,
	    `lnk_pos` INT NOT NULL,
	    `lnk_name`  VARCHAR(5000) NOT NULL,
    	`sc_name`  VARCHAR(5000) NOT NULL
	    )ENGINE=MEMORY;";
	db_runQuery($cn, $query);

	$query = "INSERT INTO t_ulinks
		SELECT ul.iduserlink, ln.`idlink`, ln.`idsection`, ul.ul_url, ln.lnk_type, ln.lnk_pos, '', ''
		FROM `userslinks` AS ul INNER JOIN `links` AS ln ON ul.`idlink` = ln.`idlink`
		WHERE ul.`iduser` =".$usr_arr[0].";";
	db_runQuery($cn, $query);

	$query = "UPDATE `t_ulinks` as tul,  `resourcefromtables` as rft
		SET tul.sc_name = rft.rft_columnname_text
		WHERE rft.idlanguage = ".$contlngid."
		AND rft.idtable = 3 AND rft.idrecord = tul.idsection;
		";
	db_runQuery($cn, $query);

	$query = "UPDATE `t_ulinks` as tul,  `resourcefromtables` as rft
		SET tul.lnk_name = rft.rft_columnname_text
		WHERE rft.idlanguage = ".$contlngid."
		AND rft.idtable = 4 AND rft.idrecord = tul.idlink;";
	db_runQuery($cn, $query);

	$query = "SELECT tul.*, sct.sct_icon, sct.sct_pos FROM `t_ulinks` as tul INNER JOIN `sections` as sct ON tul.idsection = sct.idsection ORDER BY sct.sct_pos, tul.lnk_pos;";

	$trSt = db_runQueryAndReturnArray($cn, $query);
	$size = sizeof($trSt);
	$fst0 = 0;
	$fstH = 0;
	if ( $size > 0 ){
		$cur_sc = "";
		for($i=0; $i<$size; $i++){
			if ($cur_sc != $trSt[$i]['sc_name']){
				if ($fst0 != 0) {
					echo '									</ul>';
					echo '								</li>';
				}

				$icon = $trSt[$i]['sct_icon'];
                if($icon=== null || trim($icon) === '')
                   $icon = 'icon-frontpage-4.png '; 

				if ($fstH != 0) {
					echo '</ul>';
					echo '</div>';
					echo '</article>';}

				echo '<article> <img src="'.$urlWO.'/'.$icon.'" class="personalPage_image"/>';
				echo '<div>';
				echo '<h2>'.$trSt[$i]['sc_name'].'</h2>';

				$cur_sc = $trSt[$i]['sc_name'];
				$fstH = 1;
				$fst0 = 0;

				if ($i != $size - 1 && $trSt[$i+1]['lnk_type'] != 0 ) {
					echo '						<ul class="list-front-menu-level-2">';

				} else if ($i != $size - 1 && $trSt[$i+1]['lnk_type'] == 0 && $trSt[$i]['sc_name'] != $trSt[$i+1]['sc_name']) {
					echo '						<ul class="list-front-menu-level-2">';
				} else if ($i == $size - 1) {
					echo '						<ul class="list-front-menu-level-2">';
				}
			}

			if ($trSt[$i]['lnk_type'] == 0){
				if ($fst0 != 0) {
					echo '									</ul>';
					echo '								</li>';
				}
				$fst0 = 1;
				echo '								<li>'.$trSt[$i]['lnk_name'].' ';
				echo '								<ul class="list-front-menu-level-2">';
			} else {
				$link = $trSt[$i]["ul_url"];
				if ( $link[0] == '/') {
					$link = urlReplaceParam(getCurPageSubFolders().$link,'lang');
				}
				echo '<li><a href="'.$link.'" > '.$trSt[$i]['lnk_name'].' </a></li>';
			}
		}

				if ($fst0 != 0) {
					echo '									</ul>';
					echo '								</li>';
				}

				if ($fstH != 0) {
					echo '							</ul>';
					echo '						</div>';
					echo '					</article>';
            	}
	}
?>
			</section>

			<section class="box-front front-favorites clearfix">

				<h1><?php getResource("field.favorites");?></h1>

				<div>

<?php
	$trSt = db_getPersonalLinks($cn, $usr_arr);
	$size=sizeof($trSt);
	$half = round($size / 2);

	for($i=0; $i<$size; $i++){
		if ( $i==0 ){
			echo '				<table>';
		}

		if ( $i==$half ){
			echo '				</table>';
			echo '				</div>';
			echo '				<div>';
			echo '				<table>';
		}


		$rname = null;

		$rguidPath = "";
		if ($trSt[$i]['r_guid'] !== null && $trSt[$i]['r_guid'] != '00000000-0000-0000-0000-000000000000'){
			$rname = db_getReportName($cn, $trSt[$i]['r_guid'], $contlngid, $trSt[$i]['skbranch']);
			if ($rname !== null && strlen($rname) > 0 ) {
				$rguidPath = '&rguid='.$trSt[$i]['r_guid'];
			} else {
				$rname = getResourceByLang("message.reportnotfound");
			}
		}

		$oname = db_getObjectName($cn, $trSt[$i]['o_guid'], $contlngid, $trSt[$i]['skbranch']);
		if ($oname !== null && strlen($oname) > 0 ) {
			if ($trSt[$i]['ismain'] == 1) {
				$href = $urlWO.'/businessmodel.php?oguid='.$trSt[$i]['o_guid'].$rguidPath;
			} else {
				$href = $urlWO.'/pollobject.php?skbranch='. $trSt[$i]['skbranch'].'&oguid='.$trSt[$i]['o_guid'].$rguidPath.$trSt[$i]['addurlparams'];
			}
		} else {
			$href = "#";
			$oname = getResourceByLang("message.objectnotfound");
			$rname = null;
		}

		$name = $oname.($rname === null || $rname == '' ? ' ' : ' ('.$rname.')');
			echo		'	<tr><td><a href="'.$href.'" class="link-fav" style="background-image: url( '.getImgIcon($trSt[$i]["o_icon"]).' );">'.$name.'</a>';
			echo		'	<td class="last-child">';
			echo		'	<button class="btn-fav btn-fav-up" onclick="linkCommand('.$trSt[$i]['pl_pos'].',\'up\');" title="'.getResourceByLang("button.up").'">&uarr;</button><button class="btn-fav btn-fav-down" onclick="linkCommand('.$trSt[$i]['pl_pos'].',\'down\');" title="'.getResourceByLang("button.down").'">&darr;</button><button class="btn-fav btn-fav-delete btn-fav-last-child" onclick="linkCommand('.$trSt[$i]['idpersonallink'].',\'del\');" title="'.getResourceByLang("button.delete").'">X</button>';
			echo		'	</td>';
			echo		'	</tr>';

		if ( $i==$size-1 ){
			echo '				</table>';
		}
	}
?>
            </div>
			<div class="cleaner"></div>
			</section>
		</div>
	</div>
</div>

<script src="js/libs/jquery.js"></script>
<script src="js/libs/jquery-ui-1.8.20.custom.min.js"></script>
<script src="js/libs/jquery.cookie.js"></script>
<script src="js/libs/jquery.treeview.js"></script>
<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.layout.js"></script>
<script src="js/script.js"></script>
<script>
	function linkCommand(id, commnad){
		location = "personal.php?command=" + commnad + "&id=" + id;
	}

</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(); ?>
<script src="js/personal.js"></script>
</body>
</html>

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