<?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['errorList']=	[];
	
	ob_start();
	
	include_once __DIR__ . '/include/header.php';
	
	if (isset ($_GET['id']))
	{	
		$info	=	get_user(
			(int) $_GET['id']
		);
		
		if ( ! $info || $info['id'] == $user['id'])
			redirect('/mail/');
		
		$costSend	=	($info['align'] == $user['align']) ? 1 : 100;	//	silver
		
		if (isset ($_POST['message']//,
			//$_POST['token']
		))
		{
			
			$errorList	=	[];
			
			$message	=	input(
				$_POST['message']
			);
			
			if ( ! $message)
				$params['errorList'][]	=	'Вы не ввели текст сообщения';
					
			if ($user['silver'] < $costSend)
					$params['errorList'][]	=	sprintf(
						'Не хватает <img src="/images/icon/silver.png" alt="" /> %d',
						$costSend-$user['silver']
					);
			
			if (@mysql_num_rows(@mysql_query(sprintf(
				'SELECT
						*
					FROM
						`mail`
					WHERE
						`from`	=	%d
							AND
						`time`		>=	%d',
				$user['id'],
				time()-5
			))) != 0)
				$params['errorList'][]	=	'';
			
			if (sizeof($params['errorList']) == 0)
			{
				
				if (@mysql_num_rows(@mysql_query(sprintf(
					'SELECT
							*
						FROM
							`contacts`
						WHERE
							`user_id`	=	%d
								AND
							`cid`		=	%d',
					$user['id'],
					$info['id']
				))) == 0)
				{
					@mysql_query(sprintf(
						'INSERT INTO
								`contacts`
								(
									`user_id`,
									`cid`
								)
								VALUES
								(
									%d,
									%d
								)',
						$user['id'],
						$info['id']
					));
				}
				
				if (@mysql_num_rows(@mysql_query(sprintf(
					'SELECT
							*
						FROM
							`contacts`
						WHERE
							`user_id`	=	%d
								AND
							`cid`		=	%d',
					$info['id'],
					$user['id']
				))) == 0)
				{
					@mysql_query(sprintf(
						'INSERT INTO
								`contacts`
								(
									`user_id`,
									`cid`
								)
								VALUES
								(
									%d,
									%d
								)',
						$info['id'],
						$user['id']
					));
				}
				
				@mysql_query(sprintf(
					'INSERT INTO
							`mail`
							(
								`from`,
								`to`,
								`message`,
								`time`
							)
							VALUES
							(
								%d,
								%d,
								"%s",
								%d
							)',
					$user['id'],
					$info['id'],
					$message,
					time()
				));
				
				@mysql_query(sprintf(
					'UPDATE
							`contacts`
						SET
							`lastUpdate`	=	%d
						WHERE
							`user_id`		=	%d AND `cid`	=	%d',
					time(),
					$user['id'],
					$info['id']
				));
				
				@mysql_query(sprintf(
					'UPDATE
							`contacts`
						SET
							`lastUpdate`	=	%d
						WHERE
							`user_id`		=	%d AND `cid`	=	%d',
					time(),
					$info['id'],
					$user['id']
				));
				
				@mysql_query(sprintf(
					'UPDATE
							`users`
						SET
							`silver`	=	`silver`	-	%d
						WHERE
							`id`		=	%d',
					$costSend,
					$user['id']
				));
				
				redirect(sprintf(
					'/mail/%d',
					$info['id']
				));
				
			}
			
		}
		
	?>
	<div class='title'>Диалог с <?=$info['login']?></div>
	<div class='container cntr'>
		<form action='/mail/<?=$info['id']?>' method='POST'>
			<!--<input type='hidden' name='token' value='<?=$_SESSION['token']?>' />-->
			Сообщение:<br />
			<textarea name='message' style='width:	75%;'></textarea><br />
			
			<input type='submit' value='Отправить' /><br />
			<span class='small c_grey'>Стоимость отправки сообщения <img src='/images/icon/silver.png' alt='' /> <?=$costSend?></span>
		</form>
	</div>
	<div class='min-line'></div>
	<ul class='menu'>
	<?php
		
		$lastActive	=	time() - $info['lastActive'];
		if ($lastActive > (60 * 15))
		{
	?>
		<li><span class='c_grey'>Последний раз был(а): <?=get_time($lastActive)?> назад</span></li>
	<?php
		}
	?>
		<li><img src='/images/icon/arrow.png' alt='' /> <a href='/mail/<?=$info['id']?>' class='c_grey'>Обновить</a></ul>
	<div class='min-line'></div>
	<?php
	
		$sql	=	sprintf(
			'SELECT
					*
				FROM
					`mail`
				WHERE
					`from`	=	%d AND `to`	=	%d OR `from`	=	%d AND `to`	=	%d',
			$user['id'], $info['id'],
			$info['id'], $user['id']
		);
		
		$items	=	@mysql_num_rows(@mysql_query($sql));
		$items_per_page	=	10;
		$pages	=	c_page($items, $items_per_page);
		$page	=	page($pages);
		
		$sql	.=	'
				ORDER BY
					`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='menu'>
	<?php
			while	(
				$post	=	@mysql_fetch_assoc($query)
			)
			{
				
				$info	=	get_user(
					$post['from']
				);
				
				//	Прочтение
				if ($post['to'] == $user['id'] && $post['read'] == 0)
				{
					
					@mysql_query(sprintf(
						'UPDATE
								`mail`
							SET
								`read`	=	%d
							WHERE
								`id`	=	%d',
						time(),
						$post['id']
					));
					
				}
				
	?>
		<li>
			<?=player($post['from'])?>, <?=get_time(time()	-	$post['time'])?> назад<br />
	<?php
				switch ($info['accesslevel'])
				{
					
					default:
					case	0:
	?>
	<?=bb($post['message'])?>
	<?php
					break;
					
					case	1:
	?>
	<span class='c_orange'>
		<?=bb($post['message'])?>
	</span>
	<?php
					break;
					
					case	2:
	?>
	<span class='c_blue'>
		<?=bb($post['message'])?>
	</span>
	<?php
					break;
				
				}
				
				if ($post['from'] == $user['id'])
				{
	?>
			<div style='padding:	6px 0px;'></div>
	<?php
					if ($post['read'] == 0)
					{
	?>
			<span class='small c_red'>Непрочитано</span>
	<?php
					}
					else
					{
	?>
			<span class='small c_grey'>Прочитано <?=get_time(time() - $post['read'])?> назад</span>
	<?php
					}
				
	?>
		</li>
	<?php
				}
			}
			
			if ($pages > 1)
			{
	?>
		<li class='cntr'>
	<?php
				
				pagenation(
					sprintf(
						'/mail/%d/',
						$_GET['id']
					),
					$pages,
					$page
				);
	?>
		</li>
	<?php
			}
	?>
	</ul>
	<?php
		}
		else
		{
	?>
	<div class='container cntr c_grey'>Сообщений нет</div>
	<?php
		}
	?>
	<div class='min-line'></div>
	<div class='container cntr'>
	
	</div>
	<div class='min-line'></div>
	<ul class='list'>
		<li><a href='/mail/'><img src='/images/icon/arrow.png' alt='' /> Вернуться</a></li>
	</ul>
	<?php
	
	}
	else
	{
		
			$deleteAllRead	=	isset($_GET['deleteAllRead']) ? intval($_GET['deleteAllRead'])	:	0;
		if ($deleteAllRead	==	1)
		{
			
			@mysql_query(sprintf(
				'DELETE FROM
						`mail`
					WHERE
						`to`	=	%d AND `read`	!=	0',
				$user['id']
			));
			
			redirect('/mail/');
			
		}
		
	?>
	<div class='title'>Почта</div>
	<?php
		
		$sql	=	sprintf(
			'SELECT
					*
				FROM
					`contacts`
				WHERE
					`user_id`	=	%d',
			$user['id']
		);
		
		$items	=	@mysql_num_rows(@mysql_query($sql));
		$items_per_page	=	10;
		$pages	=	c_page($items, $items_per_page);
		$page	=	page($pages);
		
		$sql	.=	'
				ORDER BY
					`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	(
				$contact=	@mysql_fetch_assoc($query)
			)
			{
				
				$info	=	get_user(
					$contact['cid']
				);
				
				$q	=	@mysql_query(sprintf(
					'SELECT
							*
						FROM
							`mail`
						WHERE
							`from`	=	%d AND `to`	=	%d OR `from`	=	%d AND `to`	=	%d
						ORDER BY
								`id`	DESC
						LIMIT	1',
					$user['id'], $info['id'],
					$info['id'], $user['id']
				));
				
	?>
		<li>
			<a href='/mail/<?=$contact['cid']?>' class='c_white'>
				<img src="/images/icon/align/<?=($info['lastActive'] > time() - (60 * 15) ? $info['align'] : $info['align'] . '-off')?>.png" alt='' /> <b><?=$info['login']?></b>, <?=$info['level']?> ур.<br />
	<?php
				if (@mysql_num_rows($q) != 0)
				{
					$last	=	@mysql_fetch_assoc($q);
					if ($last['read'] == 0)
					{
						if ($last['to'] == $user['id'])
						{
	?>
				<span class='c_l-green'>
					<?=$last['message']?>
				</span>
	<?php
						}
						else
						{
	?>
				<span class='c_grey'>
					<?=$last['message']?>
				</span>
	<?php
						}
					}
					else
					{
	?>
				<span class='c_grey'>
					<?=$last['message']?>
				</span>
	<?php
					
					}
				}
	?>
			</a></li>	
	<?php
				
			}
	
	?>
	</ul>
	<?php
			
			if ($pages > 1)
			{
	?>
	<div class='min-line'></div>
	<div class='container cntr'>
	<?php
				pagenation	(
					'/mail/?page=',
					$pages,
					$page
				);
	?>
	</div>
	<?php
			}
			
		}
		else
		{
	?>
	<div class='container c_grey'>Почта пустая, диалогов нет</div>
	<?php
		}
	
	?>
	<div class='min-line'></div>
	<ul class='menu'>
		<li><img src='/images/icon/user.png' alt='' /> <a href='/friends/'>Друзья</a> | <a href='/backlist'>Черный список</a></li>
		<li><img src='/images/icon/arrow.png' alt='' /> <a href='/mail/deleteAllRead/'>Удалить все прочитанные сообщения</a></li>
	</ul>
	<div class='min-line'></div>
	<ul class='hint'>
	<li>Регулярное удаление прочитанных сообщений ускоряет загрузку страниц</li>
	</ul>
	<?php
	
	}
	
	include_once __DIR__ . '/include/footer.php';
	
	setContentType('text/html; charset=UTF-8');
	render(
		__DIR__ . '/include/template.php',
		ob_get_clean(),
		$params
	);
	
	?>
