<?php
include_once '../sys/inc/home.php';
include_once H.'sys/inc/start.php';
include_once H.'sys/inc/compress.php';
include_once H.'sys/inc/sess.php';
include_once H.'sys/inc/settings.php';
include_once H.'sys/inc/db_connect.php';
include_once H.'sys/inc/ipua.php';
include_once H.'sys/inc/fnc.php';
include_once H.'sys/inc/user.php';

include_once 'duels_start.php';
only_reg();

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: ./');
    exit;
}

$id = (int)$_GET['id'];

$q = mysql_query("SELECT * FROM `duels` WHERE `id` = '{$id}'");
$duel = mysql_fetch_assoc($q);

if (!mysql_num_rows($q)) {
    header('Location: ./');
    exit;
}

$set['title'] = 'Дуэль № '. $duel['id'];
include_once H.'sys/inc/thead.php';
title();

$ank = get_user($duel['id_user']);
$ank2 = get_user($duel['id_ank']);

$duser = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_rat` WHERE  `id_duser` = '1' AND `id_duel` = '{$duel['id']}'"), 0);
$dank = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_rat` WHERE  `id_dank` = '1' AND `id_duel` = '{$duel['id']}'"), 0);

$duser_rat = mysql_fetch_array(mysql_query("SELECT * FROM `duels_rat` WHERE `id_user` = '{$user['id']}' AND `id_duel` = '{$duel['id']}' LIMIT 1"));

if ($duel['time'] > $duel_time) {
if (isset($_GET['user']) && !isset($_GET['ank']) && isset($user)) {
if (!$duser_rat['id']) {
    mysql_query("INSERT INTO `duels_rat` (`id_user`, `id_duser`, `id_dank`, `id_duel`, `time`) VALUES ('{$user['id']}', '1', '0', '{$duel['id']}', '".time()."')");
    mysql_query("UPDATE `duels` SET `rat` = `rat`+ '1' WHERE `id` = '{$duel['id']}' LIMIT 1");
    mysql_query("UPDATE `user` SET `balls` = '".($user['balls']+$balls_golos)."' WHERE `id` = '{$user['id']}' LIMIT 1");
    msg('Голос успешно учтен!');
    header('Refresh: 1; url=?id='.$duel['id']);
} else {
if ($duser_rat['id_duser'] == '0') {
    mysql_query("UPDATE `duels_rat` SET `id_duser` =  '1' WHERE `id_user` = '{$user['id']}' AND `id_duel` = '{$duel['id']}' LIMIT 1");
    mysql_query("UPDATE `duels_rat` SET `id_dank` =  '0' WHERE `id_user` = '{$user['id']}' AND `id_duel` = '{$duel['id']}' LIMIT 1");
    msg('Голос успешно изменен!');
    header('Refresh: 1; url=?id='.$duel['id']);
} else {
    header('Location: ./');
	exit;
}
}
}

if (isset($_GET['ank']) && !isset($_GET['user']) && isset($user)) {
if (!$duser_rat['id']) {
    mysql_query("INSERT INTO `duels_rat` (`id_user`, `id_duser`, `id_dank`, `id_duel`, `time`) VALUES ('{$user['id']}', '0', '1', '{$duel['id']}', '".time()."')");
    mysql_query("UPDATE `duels` SET `rat` = `rat`+ '1' WHERE `id` = '{$duel['id']}' LIMIT 1");
    mysql_query("UPDATE `user` SET `balls` = '".($user['balls']+$balls_golos)."' WHERE `id` = '{$user['id']}' LIMIT 1");
    msg('Голос успешно учтен!');
    header('Refresh: 1; url=?id=' . $duel['id']);
} else {
if ($duser_rat['id_dank'] == '0') {
    mysql_query("UPDATE `duels_rat` SET `id_duser` =  '0' WHERE `id_user` = '{$user['id']}' AND `id_duel` = '{$duel['id']}' LIMIT 1");
    mysql_query("UPDATE `duels_rat` SET `id_dank` =  '1' WHERE `id_user` = '{$user['id']}' AND `id_duel` = '{$duel['id']}' LIMIT 1");
    msg('Голос успешно изменен!');
    header('Refresh: 1; url=?id=' . $duel['id']);
} else {
    header('Location: ./');
	exit;
}
}
}

if (isset($_GET['ank']) && isset($_GET['user'])) {
    header('Location: ./');
	exit;
}
} else {
	msg('Голосование остановлено');
}

$mess_sad = "Увы! Вы приграли в [url=/duels/duel.php?id={$duel_send['id']}]дуэле[/url]!Не унывай, всё ещё впереди! =)";
$mess_ye = "Ура! Вы победили в [url=/duels/duel.php?id={$duel_send['id']}]дуэле[/url], в подарок получаете баллы: {$balls_winner}!Продолжайте в том же духе! =)";

if ($duel['time'] > $duel_time) {
if (isset($user)) {

if ($duser_rat['id_duser'] == '0' || !$duser_rat['id'])
 $golosuser = "<img src='yes.gif' alt=''/> <a href='?id={$duel['id']}&amp;user'>Мне нравится</a><br />";
else
 $golosuser = "<img src='yes.gif' alt=''/> Вам нравится<br />";
 
if ($duser_rat['id_dank']=='0' || !$duser_rat['id'])
 $golosank = "<img src='yes.gif' alt=''/> <a href='?id={$duel['id']}&amp;ank'>Мне нравится</a><br />";
else
 $golosank = "<img src='yes.gif' alt=''/> Вам нравится<br />";

}
} else {
$golosuser = false;
$golosank = false;
if ($duser >= $dank) {
	echo "<div class='msg'>{$ank['nick']} Победил" . ($ank['pol']?'':'а') . "!</div>";
if ($duel['who'] == '0') {
	mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('0', '{$ank['id']}', '".$mess_ye."', '" . time() . "')");
	mysql_query("UPDATE `duels` SET `who` =  '{$ank['id']}' WHERE `id` = '{$duel['id']}'");
	mysql_query("UPDATE `user` SET `balls` = '".($ank['balls']+$balls_winner)."' WHERE `id` = '{$ank['id']}' LIMIT 1");
}
if ($duel['who2'] == '0') {
	mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('0', '{$ank2['id']}', '".$mess_sad."', '" . time() . "')");
	mysql_query("UPDATE `duels` SET `who2` =  '{$ank2['id']}' WHERE `id` = '{$duel['id']}'");}
}
if ($dank > $duser) {
	echo "<div class='msg'>{$ank2['nick']} Победил" . ($ank2['pol']? null : 'а') . "!</div>";
if ($duel['who'] == '0') {
	mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('0', '{$ank2['id']}', '".$mess_ye."', '" . time() . "')");
	mysql_query("UPDATE `duels` SET `who` =  '{$ank2['id']}' WHERE `id` = '{$duel['id']}'");
	mysql_query("UPDATE `user` SET `balls` = '".($ank2['balls']+$balls_winner)."' WHERE `id` = '{$ank2['id']}' LIMIT 1");
}
if ($duel['who2'] == '0') {
	mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('0', '{$ank['id']}', '".$mess_sad."', '" . time() . "')");
	mysql_query("UPDATE `duels` SET `who2` =  '{$ank['id']}' WHERE `id` = '{$duel['id']}'");}
}
}

if (isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_rat` WHERE  `id_user` = '{$user['id']}' AND `id_duel` = '{$duel['id']}'"), 0) == '1' && $duel['time'] > $duel_time) {

    if (isset($_POST['send']) && isset($_POST['message'])) {

        $message = (string)$_POST['message'];

        if ($message) {
            mysql_query("INSERT INTO `duels_comments` (`id_user`, `id_duel`, `time`, `message`) VALUES ('{$user['id']}', '{$duel['id']}', '" . time() . "', '" . my_esc($message) . "')");
            msg('Сообщение успешно отправлено');
			$mess = "{$user['nick']} оставил" . ($user['pol'] ? '' : 'а') . " комментарий к Вашему [url=/duels/duel.php?id={$duel['id']}]Дуэлю[/url]";
if ($ank['id'] != $user['id'])mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('0', '{$ank['id']}', '".$mess."', '".time()."')");
if ($ank2['id'] != $user['id'])mysql_query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values('0', '{$ank2['id']}', '".$mess."', '".time()."')");
        } else {
            $err[] = 'Сообщение пусто';
        }
    }
}

if ($user['group_access'] >= 7 && isset($_GET ['message_delete'])) {
if (!is_numeric($_GET ['message_delete'])) {
    header('Location: ./');
	exit;
}
$id_message = (int) $_GET ['message_delete'];

$q = mysql_query("SELECT * FROM `duels_comments` WHERE `id` = '$id_message' LIMIT 1");

if (!mysql_num_rows($q)) {
    header('Location: ./');
	exit;
}

	$message = mysql_fetch_assoc($q);
	mysql_query("DELETE FROM `duels_comments` WHERE `id` = '{$id_message}' LIMIT 1");
	msg('Сообщение успешно удалено');
}

err();
aut();

$icon = "<img src='star.png' alt=''/>";
	echo "<table class='post'>";
	echo "<tr>\n";
	echo "<td class='p_t'>\n";
	echo "<img src='/style/icons/duels.png' alt=''/> <b>Дуэль №$duel[id]</b> (" . vremja($duel['time'] + $duel_config['duel_time']) . ")<br />";
	echo "</td>\n";
	echo "</tr>\n";
	echo "<tr>\n";
	echo "<td class='p_m'>\n";
	echo "<img src='/style/themes/{$set['set_them']}/user/{$ank['pol']}.png' alt='' /> <a href='/info.php?id=$duel[id_user]'>{$ank['nick']}</a> " . ($duser >= $dank? $icon:'') . "<br />";
	echo "<img class='photo' src='avatars/$duel[id]/$duel[id_user].jpg' alt=''/> <br />";
	echo "<div class='$div'>";
	echo $golosuser;
	echo "<img src='who.png' alt=''/> <a href='duel.who.php?id=$duel[id]&amp;user'>Кто голосовал?</a> ($duser " . number($duser,'голос', 'голоса', 'голосов') . ")";
	echo "</div>";
	echo "</td>\n";
	echo "</tr>\n";
	echo "<tr>\n";
	echo "<td class='p_t'>\n";
	echo "Против:";
	echo "</td>\n";
	echo "</tr>\n";
	echo "<tr>\n";
	echo "<td class='p_m'>\n";
	echo "<img src='/style/themes/{$set['set_them']}/user/{$ank2['pol']}.png' alt='' /> <a href='/info.php?id=$duel[id_ank]'>{$ank2['nick']}</a> " . ($dank > $duser? $icon:'') . "<br />";
	echo "<img class='photo' src='avatars/$duel[id]/$duel[id_ank].jpg' alt=''/> <br />";
	echo "<div class='$div'>";
	echo $golosank;
	echo "<img src='who.png' alt=''/> <a href='duel.who.php?id=$duel[id]&amp;ank'>Кто голосовал?</a> ($dank " . number($dank,'голос', 'голоса', 'голосов') . ")";
	echo "</div>";
	echo "</td>\n";
	echo "</tr>\n";
	echo "</table>";
	
	echo "<div class='post'>";
	$time1 = $duel['time'] + $duel_config['duel_time'];
	echo ($time1 > TIME ? "Дуэль закончится: " . vremja($time1) . "<br />":null) . "Всего голосов: {$duel['rat']}<br />
*Участники могут тоже голосовать, что-бы хоть как то продвинуть свой рейтинг в дуэли!<br />
*Если голоса равны то победа присваевается тому-кто вызвал на дуэль!<br />
*Комментировать могут только те, кто проголосовал в этом дуэле";
	echo "</div>";



if (isset($user) && mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_rat` WHERE  `id_user` = '{$user['id']}' AND `id_duel` = '{$duel['id']}'"), 0) == '1' && $duel['time'] > $duel_time) {
	
	$value = false;
	if (isset($_GET['reply'])) {
	$ank_reply = get_user((int)$_GET['reply']);
	if ($ank_reply['id'] && $ank_reply['id'] != 0 && $user['id'] != $ank_reply['id'])
	$value = "Ответ: {$ank_reply['nick']}, ";
	}
        echo '
		<form method="post" action="?id=' . $duel['id'] . '&amp;' . passgen() . '">
		Комментарий:<br /><textarea name="message">' . $value . '</textarea>
		<br />
		<input type="submit" name="send" value="Добавить" />
		</form>
		';		
    }
	
$count_posts = mysql_result(mysql_query("SELECT COUNT(*) FROM `duels_comments` WHERE `id_duel` = '{$duel['id']}'"), 0);
$count_pages = k_page($count_posts, $set['p_str']);
$page = page($count_pages);
$start = $set['p_str']*$page-$set['p_str'];

	echo "<table class='post'>\n";
if ($count_posts == 0) {
	echo "<tr>\n";
	echo "<td class='p_t'>\n";
	echo "Комментарии отсутствуют";
	echo "</td>\n";
	echo "</tr>\n";
}

$q = mysql_query("SELECT * FROM `duels_comments` WHERE `id_duel` = '{$duel['id']}' ORDER BY `id` DESC LIMIT {$start}, {$set['p_str']}");
while ($comment = mysql_fetch_assoc($q)) {
 $ank_comment = get_user($comment['id_user']);
 
    $title = "<a href='/info.php?id={$ank_comment['id']}'>{$ank_comment['nick']}</a>" . online($ank_comment['id']) . " (" . vremja($comment['time']) . ")";
    $post = output_text($comment['message']);
    $icon = "<img src='/style/themes/{$set['set_them']}/user/{$ank_comment['pol']}.png' alt='' />";
	
        $act = false;
	if (isset($user) && $ank_comment['id'] != $user['id']) {
        $act .= "<a href='?id={$duel['id']}&amp;reply={$ank_comment['id']}'>Ответить</a> ";
    }
	if ($user['group_access'] >= 7 && $user['group_access'] >= $ank_comment['group_access']) {
        $act .= "<a href='?id={$duel['id']}&amp;message_delete={$comment['id']}'>Удалить</a>";
    }
	echo "<tr>";
    echo "<td class='icon14'>\n";
    echo $icon;
    echo "</td>";
	
	echo "<td class='p_t'>\n";
	echo $title;
	echo "</td>";
	echo "</tr>";
	echo "<tr>";

	echo "<td class='p_m' colspan='2'>";
	echo $post. '<br />' . $act;

	echo "</td>\n";
	echo "</tr>\n";
}

	echo "</table>\n";

if ($count_pages > 1)str("?id={$duel['id']}&amp;", $count_pages, $page);
	
echo "<div class='foot'>";
echo "&laquo; <a href='./'>Дуэли</a><br />";
echo "</div>";

include_once H.'sys/inc/tfoot.php';
?>