<?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 || $user['level'] < 3)
			redirect('/');
	
	$params	=	[];
	$params['title']	=	'Дуэли';
	
	ob_start();
	
	include_once __DIR__ . '/include/header.php';
	
	$duel	=	@mysql_fetch_assoc(@mysql_query(sprintf(
		'SELECT
				*
			FROM
				`duel`
			WHERE
				`uid`	=	%d',
		$user['id']
	)));
	
	if ($duel['enemy_id']	==	0):
		
		$query	=	@mysql_query(sprintf(
			'SELECT
					`duel`.*
				FROM
					`duel`
				LEFT JOIN
					`users`
				ON
					`users`.`align`	!=	%d
				WHERE
					`duel`.`rating`	>=	%d AND `duel`.`rating`	<=	%d AND `duel`.`uid`	!=	%d
				ORDER BY
						RAND()
				LIMIT	1',
			$user['align'],
			$duel['rating']/2,
			$duel['rating']*2,
			$user['id']
		));
		
		if (@mysql_num_rows($query)!=0)
		{
			$enemy	=	@mysql_fetch_assoc($query);
			@mysql_query(sprintf(
				'UPDATE
						`duel`
					SET
						`enemy_id`	=	%d
					WHERE
						`uid`		=	%d',
				$enemy['uid'],
				$user ['id']
			));
		}
		
	endif;
	
	?>
	<div class='container cntr'>
		<span class='c_blue'>Мой рейтинг: <?=$duel['rating']?></span><br />
		Чем выше рейтинг, тем больше награда
	</div>
	<div class='min-line'></div>
	<?php
	
	if ($duel['enemy_id'] == 0):
	?>
	<div class='container cntr c_grey'>Соперника нет</div>
	<?php
		else:
		$d_enemy=	@mysql_fetch_assoc(@mysql_query(sprintf(
			'SELECT
					*
				FROM
					`duel`
				WHERE
					`uid`	=	%d',
			$duel['enemy_id']
		)));
		$u_enemy=	get_user($duel['enemy_id']);	//	соперник
		
		if (isset($_GET['change'])):
			
			$query	=	@mysql_query(sprintf(
				'SELECT
						`duel`.*
					FROM
						`duel`
					LEFT JOIN
						`users`
					ON
						`users`.`align`	!=	%d
					WHERE
						`duel`.`rating`	>=	%d AND `duel`.`rating`	<=	%d AND `duel`.`uid`	!=	%d
					ORDER BY
							RAND()
					LIMIT	1',
				$user['align'],
				$duel['rating']/2,
				$duel['rating']*2,
				$user['id']
			));
			
			if (@mysql_num_rows($query)!=0)
			{
				
				$enemy	=	@mysql_fetch_assoc($query);
				
				if ($enemy['uid'] != $duel['enemy_id']):
					
					@mysql_query(sprintf(
						'UPDATE
								`duel`
							SET
								`enemy_id`	=	%d
							WHERE
								`uid`		=	%d',
						$enemy['uid'],
						$user ['id']
					));
					@mysql_query(sprintf(
						'UPDATE
								`duel`
							SET
								`changes`	=	`changes`	-	1
							WHERE
								`uid`		=	%d',
						$user['id']
					));
					
				endif;
				
				
				
			}
			
			redirect('/duel/');
		
		endif;
		
		if (isset($_GET['attack'],
			$_GET['z']))
		{
			
			$errorList	=	[];
			
			if ($_GET['z']	!= $_SESSION['z'] || $duel['fights'] == 0)
				redirect('/duel/');
			
			$_SESSION['z']	=	md5(mt_rand());
			
			$hp		=	$user['life']	*	2;
			$part_4	=	ceil($hp	/	4);
				if ($user['hp'] < $part_4)
			{
				
				//	
				
			}
			else
			{
				
				$damage	=	0;
				$enemy_damage	=	0;
				
				$all_hp	=	$user['life']	*	2;
				$enemy_all_hp	=	$u_enemy['life']	*	2;
				
				//	
				$abilities	=	get_user_abilities(
					$user['id']
				);
				
				//	
				$train		=	get_user_abilities_train(
					$user['id']
				);
				
				$ability_1	=	FALSE;
				$ability_2	=	FALSE;
				$ability_3	=	FALSE;
				$ability_4	=	FALSE;
				$ability_5	=	FALSE;
				
				if ($abilities[5]	!=	0)
				{
							
					$a_5_b	=	(4	+	($abilities[5]	*	10))+	($train[5]	-	10);	//	
					$a_5_c	=	10 	+	($abilities[5]	*	5)	-	5;	//	chanse
							
					if (mt_rand(0, 100) <= $a_5_c)
					{
						
						$ability_5 = TRUE;
						$enemy_all_hp	-=	min($enemy_all_hp, ceil($enemy_all_hp/100)*$a_5_b);
						
					}
					
				}
						
				if ($abilities[1]	!=	0)
				{
						
					$ability_1_b	=	(20	+	($abilities[1]	*	10))+	($train[1]	-	10);	//	
					$ability_1_c	=	10 	+	($abilities[1]	*	4)	-	4;	//	chanse
					
					if (mt_rand(0, 100) <= $ability_1_c)
					{
						$ability_1 = TRUE;
					}
					
				}
						
				if ($abilities[2]	!=	0)
				{
					
					$ability_2_b	=	(20	+	($abilities[2]	*	10))+	($train[2]	-	10);	//	
					$ability_2_c	=	10 	+	($abilities[2]	*	5)	-	5;	//	chanse
						
					if (mt_rand(0, 100) <= $ability_2_c)
					{
						$ability_2 = TRUE;
					}
					
				}
						
				if ($abilities[3]	!=	0)
				{
					
					$ability_3_b	=	(5	+	($abilities[3]	*	10))+	($train[3]	-	10);
					$ability_3_c	=	20	+	($abilities[3]	*	5)	-	5;
					
					if (mt_rand(0, 100) <= $ability_3_c)
					{
						$ability_3 = TRUE;
					}
					
				}
						
				if ($abilities[4]	!=	0)
				{
					
					$ability_4_b	=	(22	+	($abilities[4]	*	10))+	($train[4]	-	10);	//	
					$ability_4_c	=	10 	+	($abilities[4]	*	5)	-	5;	//	chanse
					
					if (mt_rand(0, 100) <= $ability_4_c)
					{
						$ability_4 = TRUE;
					}
					
				}				
					
				$damage	+=	ceil(
					mt_rand(
						($user['str']	/	6),	//	min. atk
						($user['str']	/	4)	//	max. atk
					)
				);
					
				if ($ability_1)
				{
					
					$damage	+=	ceil(($damage	/	100)	*	$ability_1_b);
					
				}
				
				$damage	-=	ceil(
					mt_rand(
						($u_enemy['protection']	/	12),
						($u_enemy['protection']	/	6)
					)
				); 
					
				$damage	=	max(0, $damage);
				
				$crit = $ability_1	?
					((mt_rand(1, 2)	*	($user['dex']	/	100))	-	(mt_rand(1,2)	*	($u_enemy['dex']	/	100)))
						:
					((mt_rand(1,2)	*	($user['dex']	/	100))	-	(mt_rand(1,2)	*	($u_enemy['dex']	/	100)));
					
				if (mt_rand(0, 100)	<=	$crit)
				{
						
					$damage	*=	2;
						
					if ($ability_3)
					{
						
						$damage	+=	ceil(($damage	/	100)	*	$ability_3_b);								
						
					}
					
				}
					
				$dodge	=	((mt_rand (1,2)	*	($u_enemy['dex']	/	100))	-	(mt_rand(1,2)	*	($user['dex']	/	100)));
				if(mt_rand(0, 100) <= $dodge)
				{
					$damage	=	0;
				}
				
				
				
				
				
				
				$enemy_damage	+=	ceil(
					mt_rand(
						($u_enemy['str']	/	6),
						($u_enemy['str']	/	4)
					)
				);
				if	($ability_2)
				{
							
					$enemy_damage	-=	ceil(($enemy_damage	/	100)	*	$ability_2_b);
							
				}
						
				$enemy_damage	-=	ceil(
					mt_rand(
						($user['protection']	/	12),
						($user['protection']	/	7)
					)
				);
    
				if ($enemy_damage	<	0)
				{
					
					$enemy_damage	=	0;
				
				}
						
				$enemy_crit = (mt_rand(1,2)	*	($u_enemy['dex']	/	100))	-	(mt_rand(1,2)	*	($user['dex']	/	100));
				if (mt_rand(0, 100)	<=	$enemy_crit)
				{
					
					$enemy_damage	*=	2;
					
					if ($ability_4)
					{
						$enemy_damage	-=	ceil(($enemy_damage	/	100)	*	$ability_4_b);
					}
					
				}    
				
				$enemy_dodge	=	(mt_rand(1,2)	*	($user['dex']	/	100))	-	(mt_rand(1,2)	*	($u_enemy['dex']	/	100));
				if (mt_rand(0, 100)	<=	$enemy_dodge)
				{
					$enemy_damage	=	0;
				}
				
				
				
				
				///
				$award_silver	=	mt_rand(0, sqrt($u_enemy['hp']) *30);
					$award_exp	=	mt_rand(0, ceil($u_enemy['hp'] / 10));
				
				if (premium_exists($user['id']))
				{
					
					$award_silver	*=	4;
						$award_exp	*=	4;
					
				}
				
				//	Эффекты
				if (eff_exists($user['id'], 10)) $award_exp	*=	4;	//	Основной эффект	(+50%)
				if (eff_exists($user['id'], 11)) $award_exp	*=	2;	//	Боевой эффект (+25%)
				if (eff_exists($user['id'], 12)) $award_exp	*=	2;	//	Добывающий эффект (+25%)
				///
				
				
				
				$rating			=	0;
	?>
	<div class='box'>
	<?php
				
				//	Победа
					if ($damage	>	$enemy_damage)
				{
					
					$rating		+=	mt_rand(0, $user['level']);
					
	?>
		<img src='/images/icon/2hit.png' alt='' /> <b class='large c_l-green'>Победа</b> <img src='/images/icon/2hit.png' alt='' />
	<?php
					
				}
				//	Поражение
				else
				{
					
					$rating		-=	mt_rand(0, $user['level']);
					
					$award_silver	=	0;
					$award_exp	=	1;
					
	?>
		<img src='/images/icon/2hit.png' alt='' /> <b class='large c_red'>Поражение</b> <img src='/images/icon/2hit.png' alt='' />
	<?php			
				}
				
				if ($ability_1 || $ability_2 || $ability_3 || $ability_4 || $ability_5)
				{
	?>
		<div class='spr-line'></div>
	<?php
					if ($ability_1):
	?>	
		<img src='/images/ability/1.<?=$abilities[1]?>.png' alt='' style='width:	25px;height:	25px;' />
	<?php
					endif;
					
					if ($ability_2):
	?>	
		<img src='/images/ability/2.<?=$abilities[2]?>.png' alt='' style='width:	25px;height:	25px;' />
	<?php
					endif;

					if ($ability_3):
	?>	
		<img src='/images/ability/3.<?=$abilities[3]?>.png' alt='' style='width:	25px;height:	25px;' />
	<?php
					endif;
					if ($ability_4):
	?>	
		<img src='/images/ability/4.<?=$abilities[4]?>.png' alt='' style='width:	25px;height:	25px;' />
	<?php
					endif;
					if ($ability_5):
	?>	
		<img src='/images/ability/5.<?=$abilities[5]?>.png' alt='' style='width:	25px;height:	25px;' />
	<?php
					endif;
					
				}
				
				$award_silver	=		round($award_silver);
				$award_exp	=	max(1,	round($award_exp));
				
	?>
		<div class='spr-line'></div>
		<span class='c_blue'>Награда:</span>
	<?php
		
				if ($award_silver	!=	0)
				{
	?>
	<img src='/images/icon/silver.png' alt='' /> <?=$award_silver?> серебра
	<?php
				}
				
				if ($award_exp	!=	0)
				{
	?>
	<img src='/images/icon/exp.png' alt='' /> <?=$award_exp?> опыта
	<?php
				}
	?>
		<div class='spr'></div>
		Рейтинг: <?=($rating>0?sprintf(
			'<span class="c_green">+%d</span>',
			$rating
		):sprintf(
			'<span class="c_red">   %d</span>',
			$rating
		))?>
	<?php
	
			if ($duel['gather_fights']==4):
				
				$r_index=	mt_rand(1, 9);
				$amount	=	mt_rand(1, 3);
				
				@mysql_query(sprintf(
					'UPDATE
							`user_sack`
						SET
							`%d`	=	%d	+	%d
						WHERE
							`user_id`		=	%d',
					$r_index, $r_index, $amount,
					$user['id']
				));
				
	?>
		<div class='spr-line'></div>
		<span class='c_blue'>Награда за 5 поединков:</span><br />
		
		<img src='/images/icon/res/<?=$r_index?>.png' alt='' /> <?=get_sack($r_index)?> (<span class='c_blue'><?=$amount?></span> шт.)
		
	<?php
			
			endif;
	
	?>
	
	</div>
	<?php
				
				@mysql_query(sprintf(
					'UPDATE
							`users`
						SET
							`hp`	=	`hp`	-	%d,
							`silver`=	`silver`	+	%d,
							`exp`	=	`exp`	+	%d
						WHERE
							`id`	=	%d',
					min($user['hp'], $enemy_damage),
					$award_silver,
					$award_exp,
					$user['id']
				));
				
				if ($duel['gather_fights'] == 4):
					
					@mysql_query(sprintf(
						'UPDATE
								`duel`
							SET
								`gather_fights`	=	0
							WHERE
								`uid`		=	%d',
						$user['id']
					));
					
					else:
					
					@mysql_query(sprintf(
						'UPDATE
								`duel`
							SET
								`gather_fights`	=	`gather_fights`	+	1
							WHERE
								`uid`		=	%d',
						$user['id']
					));
					
				endif;
				
				@mysql_query(sprintf(
					'UPDATE
							`duel`
						SET
							`rating`	=	`rating`	+	%d,
							`fights`	=	`fights`	-	1
						WHERE
							`uid`		=	%d',
					$rating,
					$user['id']
				));
				
				$query	=	@mysql_query(sprintf(
					'SELECT
							`duel`.*
						FROM
							`duel`
						LEFT JOIN
							`users`
						ON
							`users`.`align`	!=	%d
						WHERE
							`duel`.`rating`	>=	%d AND `duel`.`rating`	<=	%d AND `duel`.`uid`	!=	%d
						ORDER BY
								RAND()
						LIMIT	1',
					$user['align'],
					$duel['rating']/2,
					$duel['rating']*2,
					$user['id']
				));
				
				if (@mysql_num_rows($query)!=0)
				{
					
					$enemy	=	@mysql_fetch_assoc($query);
					
					@mysql_query(sprintf(
						'UPDATE
								`duel`
							SET
								`enemy_id`	=	%d
							WHERE
								`uid`		=	%d',
						$enemy['uid'],
						$user ['id']
					));
					
				}
				
			}
			
			
		}
		
		
		$equip	=	[];
		
		for	(
				$i	=	1;
				$i	<	9;
				$i++
			)
		{
			
			if ($u_enemy[ $i ] != 0)
			{
				
				$item	=	get_user_item(
					$u_enemy['id'],
					$u_enemy[ $i ]
				);
					
				$equip[ $i ]	=	$item['shop_id'];
				
			}
				
		}
		
	?>
	<div class='container'>
		<div class='cntr'>
			<img src='/images/icon/align/<?=$u_enemy['align']?>.png' alt='' /> <b><?=$u_enemy['login']?></b><br />
			Рейтинг: <?=$d_enemy['rating']?><br />
			<a href='/duel/?attack&z=<?=$_SESSION['z']?>'><img src="/manekenImage/<?=$u_enemy['sex']?>/<?=(isset ($equip[1]) ? $equip[1] : 0)?>/<?=(isset ($equip[2]) ? $equip[2] : 0)?>/<?=(isset ($equip[3]) ? $equip[3] : 0)?>/<?=(isset ($equip[4]) ? $equip[4] : 0)?>/<?=(isset ($equip[5]) ? $equip[5] : 0)?>/<?=(isset ($equip[6]) ? $equip[6] : 0)?>/<?=(isset ($equip[7]) ? $equip[7] : 0)?>/<?=(isset ($equip[8]) ? $equip[8] : 0)?>" alt='' /></a><br />
			<img src='/images/icon/str.png' alt='' /> <?=$u_enemy['str']?>
			<img src='/images/icon/agi.png' alt='' /> <?=$u_enemy['dex']?>
			<img src='/images/icon/def.png' alt='' /> <?=$u_enemy['protection']?>
			<img src='/images/icon/vit.png' alt='' /> <?=$u_enemy['life']?>
			<div class='spr'></div>
			
			<a href='/duel/?attack&z=<?=$_SESSION['z']?>' class='btn'><img src='/images/icon/hit.png' alt='' /> Атаковать</a>
			<div style='padding:	6px 0px;'></div>
			
			<span class='c_blue'>Доступно боев:</span> <img src='/images/icon/2hit.png' alt='' /> <b><?=$duel['fights']?></b><br />
			<span class='c_blue'>Награда:</span> <?=$duel['gather_fights']?> из 5
			
		</div>
	</div>
	<div class='min-line'></div>
	<div class='container cntr'>
		Ваши параметры:<br />
		<img src='/images/icon/str.png' alt='' /> <?=($u_enemy['str'] > $user['str'] ? sprintf(
			'<span class="c_red">%d</span>',
			$user['str']
		)	:	$user['str'])?>
		<img src='/images/icon/agi.png' alt='' /> <?=($u_enemy['dex'] > $user['dex'] ? sprintf(
			'<span class="c_red">%d</span>',
			$user['dex']
		)	:	$user['dex'])?>
		<img src='/images/icon/def.png' alt='' /> <?=($u_enemy['protection'] > $user['protection'] ? sprintf(
			'<span class="c_red">%d</span>',
			$user['protection']
		)	:	$user['protection'])?>
		<img src='/images/icon/vit.png' alt='' /> <?=($u_enemy['life'] > $user['life'] ? sprintf(
			'<span class="c_red">%d</span>',
			$user['life']
		)	:	$user['life'])?>
	</div>
	<div class='min-line'></div>
	<div class='container cntr'>
		<a href='/duel/?change' class='btn'>Другой противник</a><br />
		<span class='c_grey'>Бесплатная смена противника: <img src='/images/icon/hit.png' alt='' /> <?=$duel['changes']?> раз</span>
	</div>
	<div class='min-line'></div>
	<ul class='hint'>
	<li>1 бой восстанавливается 1 час. Бои не накапливаются больше 10.</li>
	<li>После 5 поединков, вы получите по 1 случайному ресурсу</li>
	<li>Одна бесплатная смена противника добавляется каждые 1 час. Бесплатных смен не накапливается больше 5</li>
	</ul>
	<?php
	
	endif;
	
	include_once __DIR__ . '/include/footer.php';
	
	setContentType('text/html; charset=UTF-8');
	render(
		__DIR__ . '/include/template.php',
		ob_get_clean(),
		$params
	);
	
	?>
	