<?php
	header('Content-Type: text/html; charset=utf-8');

	include('../../../inc/start.php');
	include('../../../inc/protect.php');

	if(!isset($_POST['token']) || $_SESSION['token'] != clean($_POST['token'], null))
		exit(json_encode(array('status' => 'error', 'text' => 'Неверный токен')));

	$menu = '';

	$query = $pdo->query('SELECT * FROM `menu` ORDER BY `poz`');
			 $query->execute();

	$qMenu = $query->fetchAll();

	$all = count($qMenu);

	if(!$all)
		exit;

	for($i = 0; $i < $all; $i+=1)
	{
		if($qMenu[$i]['podmenu'] != '0')
		{
			$query = $pdo->query('SELECT * FROM `podmenu` WHERE `menu`="'.$qMenu[$i]['id'].'" ORDER BY `poz`');
					 $query->execute();

			$qSubMenu = $query->fetchAll();

			$allSub = count($qSubMenu);

			if($allSub && $qMenu[$i]['for_all'] == 1 || ($qMenu[$i]['for_all'] == 2 && isset($_SESSION['id'])) || ($qMenu[$i]['for_all'] == 3 && empty($_SESSION['id'])))
			{
				$menu.= '<li class="collapsible"><a href="">'.$qMenu[$i]['name'].'</a><ul>';

				for($n = 0; $n < $allSub; $n+=1)
				{
					if($allSub[$n]['for_all'] == 1 || ($allSub[$n]['for_all'] == 2 && isset($_SESSION['id'])) || ($allSub[$n]['for_all'] == 3 && empty($_SESSION['id'])))
					{
						if($allSub[$n]['link'] == '../profile')
							$allSub[$n]['link'] = '../profile?id='.$_SESSION['id'];

						$menu.= '<li><a href="'.$allSub[$n]['link'].'">'.$allSub[$n]['name'].'</a></li>';
					}
				}

				$menu.= '</ul></li>';
			}
		}else{
			if($qMenu[$i]['for_all'] == 1 || ($qMenu[$i]['for_all'] == 2 && isset($_SESSION['id'])) || ($qMenu[$i]['for_all'] == 3 and empty($_SESSION['id'])))
			{
				if($allSub[$n]['link'] == '../profile')
					$allSub[$n]['link'] = '../profile?id='.$_SESSION['id'];

				$menu.= '<li><a href="'.$allSub[$n]['link'].'">'.$allSub[$n]['name'].'</a></li>';
			}
		}
	}
	
	echo $menu;
?>

