<?php
	
	include_once __DIR__ . '/include/common.php';
	include_once __DIR__ . '/include/general_functions.php';
	include_once __DIR__ . '/include/utils.php';	
	include_once __DIR__ . '/include/user.php';
	
	if ( ! @$user)
	{
		redirect('/');
	}
	
	$params	=	[];
	$params['title']	=	'Форум';
	$params['list_errors']=	[];
	
	ob_start();
	
	include_once __DIR__ . '/include/header.php';
	
		if (isset($_GET['subforum']))
	{
		
		$query	=	@mysql_query(sprintf(
			'SELECT
					*
				FROM
					`subforums`
				WHERE
					`id`	=	%d',
			intval($_GET['subforum'])
		));
		
		if (@mysql_num_rows($query) == 0)
		{
			redirect('/forum/');
		}
		
		$subforum		=	@mysql_fetch_assoc($query);
		
		//
		$params['title']=	$subforum['name'];
		
		switch	(@$_GET['act'])
		{
			default:
			
			$markUp		=	isset($_GET['markUp'])	?	intval($_GET['markUp'])	:	0;
			if ($markUp==	1)
			{
				
			}
			
			$sql	=	sprintf(
				'SELECT
						*
					FROM
						`topics`
					WHERE
						`subforum_id`	=	%d',
				$subforum['id']
			);
			
			$items	=	@mysql_num_rows(@mysql_query($sql));
			$items_per_page	=	15;
			$pages	=	c_page($items, $items_per_page);
			$page	=	page($pages);
			
			$sql	.=	'
					ORDER BY
						`stick`	DESC,
						`lastUpdate`	DESC,
						`id`	DESC';
			
			$at		=	($page	-	1)	*	$items_per_page;
			$sql	.=	sprintf(
				'
					LIMIT
						%d, %d',
				$at,
				$items_per_page
			);
				
			$query	=	@mysql_query($sql);
			if ($items != 0)
			{
			
	?>
	<ul class='list'>
	<?php
				while	(
					$topic	=	@mysql_fetch_assoc($query)
				)
				{
				
					//	Непрочитанный топик
					if (@mysql_num_rows(@mysql_query(sprintf(
						'SELECT
								*
							FROM
								`forum_read`
							WHERE
								`topic_id`	=	%d AND `user_id`	=	%d',
						$topic['id'], $user ['id']
					))) == 0)
					{
		?>
		<li><?=($topic['stick'] == 0 ? sprintf(
			'<a href="/forum/topic/%d/"><img src="/images/icon/forum_2.png" alt="" /> %s</a>',
			$topic['id'], $topic['name']
		)	: sprintf(
			'<a href="/forum/topic/%d/"><img src="/images/icon/forum_2.png" alt="" /> <b>%s</b></a>',
			$topic['id'], $topic['name']
		))?></li>
	<?php
	
					}
					//	Прочитанный топик
					else
					{
	?>
		<li><?=($topic['stick'] == 0 ? sprintf(
			'<a href="/forum/topic/%d/" class="c_grey"><img src="/images/icon/forum_3.png" alt="" /> %s</a>',
			$topic['id'], $topic['name']
		)	: sprintf(
			'<a href="/forum/topic/%d/" class="c_grey"><img src="/images/icon/forum_3.png" alt="" /> <b>%s</b></a>',
			$topic['id'], $topic['name']
		))?></li>
	<?php
					}
					
				}
	?>
	</ul>
	<?php
				if ($pages > 1)
				{
	?>
	<div class='min-line'></div>
	<div class='container cntr'>
	<?php
					pagenation(
						sprintf(
							'/forum/subforum/%d/',
							$subforum['id']
						),
						$pages,
						$page
					);
	?>
	</div>
	<?php
				}
			}
			else
			{
	?>
	<div class='container cntr c_grey'>Раздел пуст</div>
	<?php
			}
		
	?>
	<div class='min-line'></div>
	<ul class='list'>
	<?php
			if ($user['accesslevel'] >= $subforum['accesslevel'])
			{
	?>
		<li><a href='/forum/subforum/newTopic/<?=$subforum['id']?>/'><img src='/images/icon/arrow.png' alt='' /> Новый топик</a></li>
	<?php
			}
	?>
		<li><a href='/forum/subforum/<?=$subforum['id']?>/markUp/'><img src='/images/icon/arrow.png' alt='' /> Отметить все как прочитанное</a></li>
		<li><a href='/forum/'><img src='/images/icon/arrow.png' alt='' /> Вернуться</a></li>
	</ul>
	<?php
			
			break;
			
			//	Новый топик
			case	'newTopic':
			
			if ($subforum['accesslevel']>$user['accesslevel'])
			{
				redirect(sprintf(
					'/forum/subforum/%d/',
					$subforum['id']
				));
			}
			
			//	
			$params['title']	=	'Новый топик';
			
			
			if (isset($_POST['name'], $_POST['text']))
			{
				
				$name	=	input($_POST['name']);
				$text	=	input($_POST['text']);
				
				if ($name && $text)
				{
					
					if ($user['saved']==0)
						$params['list_errors'][]	=	'Создавать топики могут только сохраненные игроки';
					
					if ($user['level']>=10)
						$params['list_errors'][]	=	'Создавать топики могут игроки достигшие 10 уровня';
					
					if (@mysql_num_rows(@mysql_query(sprintf(
						'SELECT
								*
							FROM
								`topics`
							WHERE
								`user_id`	=	%d
									AND
								`time`		>	%d',
						$user['id'],	//	user id
						time()-(60*15)	//	delay
					)))!=0)
						$params['list_errors'][]	=	'Вы слишком часто создаете топики';
					
					if (sizeof($params['list_errors'])==0)
					{
						
						@mysql_query(sprintf(
							'INSERT INTO
									`topics`
									(
										`subforum_id`,
										`user_id`,
										`name`,
										`text`,
										`time`,
										`lastUpdate`
									)
										VALUES
									(
										%d,
										%d,
										"%s",
										"%s",
										%d,
										%d
									)',
							$subforum['id'], $user['id'], $name, $text, time(), time()
						));
						
						$topic_id	=	@mysql_insert_id();
						
						redirect(sprintf(
							'/forum/topic/%d',
							$topic_id
						));
						
					}
					
				}
				
				
			}
			
	?>
	<div class='container'>
		<form action='/forum/subforum/newTopic/<?=$subforum['id']?>/' method='POST'>
			Название топика: <br />
			<input name='name' /><br />
			Оглавление: <br />
			<textarea name='text' style='width:	75%;'></textarea><br />
			<input type='submit' value='Отправить' />
		</form>
	</div>
	<div class='min-line'></div>
	<ul class='list'>
		<li><a href='/forum/subforum/<?=$subforum['id']?>'><img src='/images/icon/arrow.png' alt='' /> Вернуться</a></li>
	</ul>
	<?php
			break;
			
		}
		
	}
	elseif (isset($_GET['topic']))
	{
		
		$query	=	@mysql_query(sprintf(
			'SELECT
					*
				FROM
					`topics`
				WHERE
					`id`	=	%d',
			intval($_GET['topic'])
		));
		
		if (@mysql_num_rows($query)==0)
		{
			redirect('/forum/');
		}
		
		$topic	=	@mysql_fetch_assoc($query);
					$author	=	get_user($topic['user_id']);
		
		$params['title']	=	$topic['name'];
		
		switch	(@$_GET['act'])
		{
			
			default:
			
			if (@mysql_num_rows(@mysql_query(sprintf(
				'SELECT
						*
					FROM
						`forum_read`
					WHERE
						`topic_id`	=	%d AND `user_id`	=	%d',
				$topic['id'], $user['id']
			)))==0)
			{
				@mysql_query(sprintf(
					'INSERT INTO
							`forum_read`
							(
								`topic_id`,	`user_id`
							)
							VALUES
							(
								%d, %d
							)',
					$topic['id'],
					$user ['id']
				));
			}
			
			if ($user['id']==$topic['user_id'] || $user['accesslevel']>$author['id'])
			{
	?>
	<div class='container'>
		<img src='/images/icon/arrow.png' alt='' /> <a href='/forum/topic/redact/<?=$topic['id']?>' class='small'>Редактировать</a><br />
	<?php
			if ($topic['closed']==0)
			{
				if ($topic['user_id']==$user['id'] || $user['accesslevel']>=$author['accesslevel'])
				{
	?>
		<img src='/images/icon/arrow.png' alt='' /> <a href='/forum/topic/close/<?=$topic['id']?>' class='small'>Закрыть</a>
	<?php
				}
			}
			else
			{
				if ($topic['user_id']==$user['id'] && $user['accesslevel']>=1 || $user['accesslevel']>=$author['accesslevel'])
				{
	?>
		<img src='/images/icon/arrow.png' alt='' /> <a href='/forum/topic/open/<?=$topic['id']?>' class='small'>Открыть</a>
	<?php
				}
			}
	?>
	</div>
	<div class='min-line'></div>
	<?php
	
			}
			
			$sql	=	sprintf(
				'SELECT
						*
					FROM
						`comments`
					WHERE
						`topic_id`	=	%d',
				$topic['id']
			);
			
			$items	=	@mysql_num_rows(@mysql_query($sql));
			$items_per_page	=	10;
			$pages	=	c_page($items, $items_per_page);
			$page	=	page(
				$pages	//	all
			);
			$sql	.=	'
					ORDER BY
						`id`';
			
			$at		=	($page	-	1)	*	$items_per_page;
			$sql	.=	sprintf(
				'
					LIMIT
						%d, %d',
				$at,
				$items_per_page
			);
			
			if ($page == 1)
			{
	?>
	<div class='container dtd-line'>
	<?=player($topic['user_id'])?>, <?=timeleft(time()-$topic['time'])?> назад<br />
	<?php
				switch	($author['accesslevel'])
				{
					case	0:
	?>
			<?=bb($topic['text'])?>
	<?php
					break;
					case	1:
	?>
			<span class='c_orange'><?=bb($topic['text'])?></span>
	<?php
					break;
					case	2:
	?>
			<span class='c_blue'>  <?=bb($topic['text'])?></span>
	<?php
					break;
				}
		
				if ($topic['last_redact']!=0)
				{
	?>
	<div style='padding:	6px 0px;'></div>
	<span class='small c_grey'>Отредактировал(а): <?=player($topic['last_redact_uid'])?>, <?=timeleft(time()-$topic['last_redact'])?> назад</span>
	<?php	
				}
			
	?>
	</div>
	<?php
			}
	?>
	<div class='container'>
	Комментарии:	<b><?=$items?></b>
	</div>
	<?php
		
			if ($items != 0)
			{
	?>
	<div class='min-line'></div>
	<ul class='menu'>
	<?php
				$query	=	@mysql_query($sql);
				while	(
					$comment	=	@mysql_fetch_assoc($query)
				)
				{
					
					$info	=	get_user(
						$comment['user_id']
					);
					
	?>
		<li>
			<?=player($comment['user_id'])?>
	<?php
					if ($comment['user_id'] != $user['id'])
					{
	?>
			<a href='/forum/topic/<?=$topic['id']?>/to/<?=$comment['user_id']?>'>(&#187;)</a>
	<?php
					}
	?>
			, <?=timeleft(time()-$comment['time'])?> назад<br />
	<?php
					if ($comment['to']!=0)
					{
						
						$to	=	get_user(
							$comment['to']
						);
	?>
	<span class='c_l-green'><?=$to['login']?></span>, 
	<?php
					}
					
					switch	($info['accesslevel'])
					{
						case	0:
	?>
			<?=bb($comment['text'])?>
	<?php
						break;
						case	1:
	?>
			<span class='c_orange'><?=bb($comment['text'])?></span>
	<?php
						break;
						case	2:
	?>
			<span class='c_blue'>  <?=bb($comment['text'])?></span>
	<?php
						break;
					}
	?>
		</li>
	<?php
				}
				
				
				
				if ($pages>1)
				{
	?>
		<li>
	<?php
					pagenation(
					sprintf(
						'/forum/topic/%d/',
						$topic['id']
					),
						$pages,
						$page);
	?>
		</li>
	<?php
				}
	?>
	</ul>
	<?php
			}
	?>
	<div class='min-line'></div>
	<div class='container'>
	<?php
			if ($topic['closed']==0)
			{
				
					$_GET['to']	=	isset($_GET['to'])	?	intval($_GET['to'])	:	0;
				if ($_GET['to'] != 0)
				{
					
					$to	=	get_user(
						$_GET['to']
					);
					
					if ( ! $to || $to['id'] == $user['id'])
						redirect(sprintf(
							'/forum/topic/%d/',
							$cid
						));
					
				}
				
				if (isset($_POST['text']))
				{
					
						$text	=	input($_POST['text']);
					if ($text)
					{
						
						if ($user['saved']==0)
							$params['list_errors'][]	=	'Оставлять комментарии могут только сохраненные игроки';
						
						if ($user['level']>=5)
							$params['list_errors'][]	=	'Оставлять комментарии могут игроки достигшие 5 уровня';
						
						if (@mysql_num_rows(@mysql_query(sprintf(
							'SELECT
									*
								FROM
									`comments`
								WHERE
									`user_id`	=	%d
										AND
									`time`		>=	%d',
							$user['id'],
							time()-5
						)))!= 0)
							$params['list_errors'][]	=	'Вы слишком часто пишите';
						
						if (sizeof($params['list_errors'])==0)
						{
							
							if ($_GET['to'] != 0)	{
								$text	=	strtr($text, [
										$to['login'] . ', '	=>	''
								]);
							}
							
							@mysql_query(sprintf(
								'UPDATE
										`topics`
									SET
										`lastUpdate`=	%d
									WHERE
										`id`		=	%d',
								time(),
								$topic['id']
							));
							@mysql_query(sprintf(
								'INSERT INTO
										`comments`
										(
											`topic_id`,
											`user_id`,
											`text`,
											`to`,
											`time`
										)
											VALUES
										(
											%d, %d, "%s", %d, %d
										)',
								$topic['id'], $user['id'], $text, $_GET['to'], time()
							));
							
							redirect(sprintf(
								'/forum/topic/%d',
								$topic['id']
							));
							
						}
						
					}
					
				}
				
	?>
		<form action='/forum/topic/<?=$topic['id']?>/to/<?=$_GET['to']?>' method='POST'>
			Комментарий: <br />
			<textarea name='text' style='width:	75%;'><?=($_GET['to']!=0 ? sprintf('%s, ', $to['login']) : '')?></textarea><br />
			<input type='submit' value='Отправить' />
		</form>
	<?php
			}
			else
			{
	?>
	<span class='c_red'>Топик закрыт</span>
	<?php
			}
			
			break;
			
			case	'redact':
				
			if ($topic['user_id'] == $user['id'] && $topic['closed'] != 0 || $topic['user_id']!=$user['id'] && $author['accesslevel']>$user['accesslevel'])
				redirect(sprintf(
					'/forum/topic/%d/',
					$topic['id']
				));
			
			if (isset($_POST['text']))
			{
				
					$text	=	input($_POST['text']);
				if ($text)
				{
				
					@mysql_query(sprintf(
						'UPDATE
								`topics`
							SET
								
								`text`			=	"%s",
								
								`last_redact`	=	%d,
								`last_redact_uid`
												=	%d
							WHERE
								`id`			=	%d',
						$text, time(), $user['id'],
						$topic['id']
					));
					
					redirect(sprintf(
						'/forum/topic/%d/',
						$topic['id']
					));
					
				}
			}
			
	?>
	<div class='container'>
		<form action='/forum/topic/redact/<?=$topic['id']?>' method='POST'>
			Оглавление: <br />
			<textarea name='text' style='width:	75%;'><?=$topic['text']?></textarea><br />
			<input type='submit' value='Изменить' />
		</form>
	</div>
	<?php
			break;
			
			case	'close':
			
			if ($topic['closed']==0)
			{
				
				if ($topic['user_id']==$user['id'] || $author['accesslevel']<$user['accesslevel'])
				{
					
					@mysql_query(sprintf(
						'UPDATE
								`topics`
							SET
								`closed`	=	%d
							WHERE
								`id`		=	%d',
						$user ['id'],
						$topic['id']
					));
					
				}
				
			}
			
			redirect(sprintf(
				'/forum/topic/%d/',
				$topic['id']
			));
			
			break;
			
			case	'open':
			
			if ($topic['closed']!=0)
			{
				
				$ho	=	get_user(
					$topic['closed']	//	ho closed this topic
				);
				
				if ($topic['closed']==$user['id'] && $user['accesslevel']>=1 || $ho['accesslevel']<$user['accesslevel'])
				{
					
					@mysql_query(sprintf(
						'UPDATE
								`topics`
							SET
								`closed`	=	0
							WHERE
								`id`		=	%d',
						$topic['id']
					));
					
				}
				
			}
			
			redirect(sprintf(
				'/forum/topic/%d/',
				$topic['id']
			));
			
			break;
			
		}
	?>
	</div>
	<div class='min-line'></div>
	<ul class='list'>
		<li><a href='/forum/subforum/<?=$topic['subforum_id']?>'><img src='/images/icon/arrow.png' alt='' /> Вернуться</a></li>
	</ul>
	<?php
	}
	else
	{
		
			$cid	=	isset($_GET['cid'])	?	intval($_GET['cid'])	:	0;
		if ($cid!=0)
		{
			if(@mysql_num_rows(@mysql_query(sprintf(
				'SELECT
						*
					FROM
						`clans`
					WHERE
						`id`	=	%d',
				$cid
			)))==0)
				redirect('/forum/');
		}
		
		$query	=	@mysql_query(sprintf(
			'SELECT
					*
				FROM
					`subforums`
				WHERE
					`clan_id`	=	%d',
			$cid
		));
		if (@mysql_num_rows($query) != 0)
		{
	?>
	<ul class='list'>
	<?php
			while	(
				$subforum	=	@mysql_fetch_assoc($query)
			)
			{
	?>
		<li><a href='/forum/subforum/<?=$subforum['id']?>/'><img src='/images/icon/section.png' alt='' /> <?=$subforum['name']?></a></li>
	<?php
			}
	?>
	</ul>
	<?php
		}
		else
		{
	?>
	<div class='container cntr c_grey'>Разделов нет</div>
	<?php
		
		}
		
	}
	
	include_once __DIR__ . '/include/footer.php';
	
	setContentType('text/html; charset=UTF-8');
	render(
		__DIR__ . '/include/template.php',
		ob_get_clean(),
		$params
	);
	
	?>
