<?php
require_once('system/func.php');
auth(); // Закроем от не авторизованных
$title = 'Клан';

# Настройки #
$id = abs(intval($_GET['id']));
if ($id) {
    $clan = mysql_fetch_assoc(mysql_query("SELECT * FROM `clans` WHERE `id` = '" . $id . "'"));
} else {
    $clan = mysql_fetch_assoc(mysql_query("SELECT * FROM `clans` WHERE `id` = '" . $user[id_clan] . "'"));
}
# Ошибки #
if (!$clan) {
    $_SESSION['msg'] = 'Такой клан не существует';
    header('Location: /clans/');
    exit();
}






if($clan['tour'] >= 0 && $clan['tour'] <= 9)$almaz = 0;
elseif($clan['tour'] >= 10 && $clan['tour'] <= 24)$almaz = 5;
elseif($clan['tour'] >= 25 && $clan['tour'] <= 49)$almaz = 10;
elseif($clan['tour'] >= 50 && $clan['tour'] <= 99)$almaz = 15;
elseif($clan['tour'] >= 100 && $clan['tour'] <= 149)$almaz = 25;
elseif($clan['tour'] >= 150 && $clan['tour'] <= 299)$almaz = 50;
elseif($clan['tour'] >= 300 && $clan['tour'] <= 499)$almaz = 100;
elseif($clan['tour'] >= 500 && $clan['tour'] <= 999)$almaz = 250;
elseif($clan['tour'] >= 1000)$almaz = 500;
if(isset($_GET['tour']) && $user['id_clan'] >= 1){
if($user['id_clan'] != $clan['id']){
header('Location: /clan.php?id='.$user['id_clan'].'&tour#'.$r.'');
exit();
}
if(isset($_GET['tour_ok']) && $user['id_clan'] >= 1 && $user['clan_rang'] >= 4 && $clan['tour'] >= 10 && $clan['id'] == $user['id_clan']){
mysql_query("UPDATE `clans` SET `tour` = '0', `almaz` = '".($clan['almaz'] + $almaz)."' WHERE `id` = '".$user['id_clan']."'");
$_SESSION['msg'] = '<div class="text center"><font color="lime">Золото перечисленно в казну</font></div>';
header('Location: /clan.php?id='.$user['id_clan'].'&tour#'.$r.'');
exit();
}
$title = 'Клановый турнир';
require_once('./system/header.php');
echo '<div class="de center"><img src="/icons/cland.png" width="14" height="14"> '.$title.'</div>';
echo '<div class="text">';
echo '<center>Чем больше очков рейтинга, тем больше алмазов можно получить.</center><hr>';
if($user['id_clan'] >= 1 && $user['clan_rang'] >= 4 && $clan['tour'] >= 10)echo '<center><a href="/clan.php?id='.$user['id_clan'].'&tour&tour_ok" class="but">Получить алмазы</a></center>';
echo '<hr><img src="/icons/quest_adven.png" width="16" height="16"> Очки клана: '.$clan['tour'].'<br><img src="/icons/quest_adven.png" width="16" height="16"> Мои очки: '.$user['clan_tour'].'<br><img src="/icons/ok.png" width="16" height="16"> Награда: <img src="/icons/almaz.png" width="16" height="16">'.$almaz.'<br><center><a href="/clan_tour.php?info#'.$r.'"><img src="/icons/cland.png" width="14" height="14"> <u>Подробнее о сражении</u></a></center>';
echo '</div>';
echo "<a href='/clan.php?id=".$user['id_clan']."#".$r."' class='link'><img src='/icons/back.png' width='16' height='16'> Вернуться назад</a>";
require_once('system/footer.php');exit();
}
















//Чат клана
if (isset($_GET['chat']) and $user['id_clan'] == $clan['id']) {
    $title = 'Клановый чат';
    require_once('system/header.php');
    if (isset($_GET['text'])) {
        if (isset($_POST['text'])) {
            $text = text($_POST['text']);
            $ban = mysql_query('SELECT * FROM `ban` WHERE `id_user` = "' . $myID . '" AND `last` > "' . time() . '" ORDER BY `id` DESC LIMIT 1');
            $ban = mysql_fetch_array($ban);
            if (strlen($text) < 3 or strlen($text) > 300) {
                $err = 'Длина сообщения должна быть в пределах 3 - 300 символов';
            }
            if ($ban) {
                $err = "На вас наложен, бан осталось " . tl($ban[last] - time());
            }
            if (!$err) {
                mysql_query("INSERT INTO `clanchat` SET `id_user` = '$user[id]', `time` = '" . time() . "', `text` = '" . text($text) . "', `id_clan` = '$clan[id]'");
                $_SESSION['msg'] = 'Сообщение отправлено </div>';
                header('Location: /clan/chat/');
                exit();
            } else {
                $_SESSION['msg'] = $err;
                header('Location: /clan/chat/');
                exit();
            }
        } else {
            $_SESSION['msg'] = 'Введите сообщение ';

            header('Location: /clan/chat/');
            exit();
        }
    }
    if (isset($_GET['del']) and $user['clan_rang'] >= 4) {
        mysql_query("DELETE FROM `clanchat` WHERE `id` = '" . num($_GET['del']) . "'");
        $_SESSION['msg'] = 'Сообщение удалено';
        header('Location: ?');
        exit();
    }
    echo "<div class='header'>";
    if ($user['level'] < 10) {
        echo "В чате можно писать только с " . ico('icons', 'level.png') . " 10 уровня";
    } else {
        if (isset($_GET['to'])) {
            echo "<form method='post' action='?text=$_GET[to]'>";
            $opponent = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = $_GET[to] LIMIT 1"));
            echo "<input type='text' name='text' value = '$opponent[login], '>";
            echo "<input type='submit' class='btn_grey' value='Отправить'></form>";
        } else {
            echo "<form method='post' action='?text'>";
            echo "<input type='text' name='text'>";
            echo "<input type='submit' class='btn_grey' value='Отправить'></form>";
        }
    }
    echo "</div>";
    $set['p_str'] = 10;
    $k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `clanchat` WHERE `id_clan` = '$clan[id]'"), 0);
    $k_page = k_page($k_post, $set['p_str']);
    $page = page($k_page);
    $start = $set['p_str'] * $page - $set['p_str'];
    $q = mysql_query("SELECT * FROM `clanchat` WHERE `id_clan` = '$clan[id]' ORDER BY `id` DESC LIMIT $start, $set[p_str]");
    while ($post = mysql_fetch_assoc($q)) {
        echo "<div class='text_p1'>";

        $ank = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = $post[id_user] LIMIT 1"));
        echo " <a href='/profile/$ank[id]'>$ank[login]</a>, " . tl(time() - $post['time']) . " ";
        if ($myID != $ank['id']) {
            echo "<a href='?to=$ank[id]'>[Отв]</a>";
        }
        $msg = str_replace(array($user[login] . ','), "<b>$user[login],</b> ", $post['text']);
        echo "<br>" . text_msg($msg);
        if ($user['clan_rang'] >= 4) {
            echo " <a href='?del=$post[id]'><font color='red'>[×]</font></a>";
        }
        echo "</div>";

    }
    if ($k_post > 10) {

        echo "<div class='block_l'>";
        str('?', $k_page, $page); // Вывод страниц
        echo "</div>";
    }

    $clan = "";
    require_once('system/footer.php');
    break;
}
if (isset($_GET['ResetGold'])) {
    if ($user['clan_rang'] < 4) {
        header('Location: ?');
        exit();

    }
    $_SESSION['msg'] = "Статистика по золоте обнулена ";
    $log = ' <a href="/profile/' . $user['id'] . '"> <a> ' . $user[login] . ' <a></a> обнулил статистку по  ' . ico('icons', 'gold.png') . '  золоте';

    mysql_query("INSERT INTO `clan_journal` SET `clan` = '$clan[id]', `time` = '" . time() . "', `text` = '$log' ");


    mysql_query("UPDATE `users` SET `clan_gold` = '0' WHERE `id_clan` = '" . $clan['id'] . "'");
    mysql_query("UPDATE `clans` SET `reset_gold` = '" . time() . "' WHERE `id` = '" . $user['id_clan'] . "'");

    header('Location: ?');
    exit();

}
if (isset($_GET['ResetAlmaz'])) {
    if ($user['clan_rang'] < 4) {
        header('Location: ?');
        exit();

    }
    $_SESSION['msg'] = "Статистика по алмазам обнулена ";
    $log = ' <a href="/profile/' . $user['id'] . '"> <a> ' . $user[login] . ' <a></a> обнулил статистку по  ' . ico('icons', 'almaz.png') . ' алмазам';

    mysql_query("INSERT INTO `clan_journal` SET `clan` = '$clan[id]', `time` = '" . time() . "', `text` = '$log' ");


    mysql_query("UPDATE `users` SET `clan_almaz` = '0' WHERE `id_clan` = '" . $clan['id'] . "'");
    mysql_query("UPDATE `clans` SET `reset_almaz` = '" . time() . "' WHERE `id` = '" . $user['id_clan'] . "'");

    header('Location: ?');
    exit();

}
if (isset($_GET['ResetExp'])) {
    if ($user['clan_rang'] < 4) {
        header('Location: ?');
        exit();

    }
    $_SESSION['msg'] = "Статистика по опыту обнулена ";
    $log = ' <a href="/profile/' . $user['id'] . '"> <a> ' . $user[login] . ' <a></a> обнулил статистку по  ' . ico('icons', 'exp.png') . ' опыту';

    mysql_query("INSERT INTO `clan_journal` SET `clan` = '$clan[id]', `time` = '" . time() . "', `text` = '$log' ");

    mysql_query("UPDATE `users` SET `ResetClanExp` = '0' WHERE `id_clan` = '" . $clan['id'] . "'");
    mysql_query("UPDATE `clans` SET `reset_exp` = '" . time() . "' WHERE `id` = '" . $user['id_clan'] . "'");

    header('Location: ?');
    exit();

}


if (isset($_GET[treasury]) and $user[id_clan] == $clan[id]) {
    if (isset($_GET[rating_exp])) {
        $title = 'Рейтинг по опыту';
        require_once('system/header.php');
        echo div('header') . " Статистика  обнулялась <span class='white'> " . tl(time() - $clan['reset_exp']) . " </span> назад </div>";
        $set['p_str'] = 10;
        $k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `id_clan` = '$clan[id]' AND `ResetClanExp` >'0'"), 0);
        $k_page = k_page($k_post, $set['p_str']);
        $page = page($k_page);
        $start = $set['p_str'] * $page - $set['p_str'];
        $q = mysql_query("SELECT * FROM `users` WHERE `id_clan` = '$clan[id]' AND `ResetClanExp` > '0' ORDER BY `ResetClanExp` DESC LIMIT $start, $set[p_str]");
        while ($post = mysql_fetch_assoc($q)) {
            echo "<div class='text_p1'>";

            echo "<a href='/profile/$post[id]'>$post[login]</a> " . ico('icons', 'exp.png') . " $post[ResetClanExp] опыта";
            echo "</div></div>";


        }

        if ($user['clan_rang'] >= 4) {
            echo div('header') . " <div class='btn_grey'><a href='?ResetExp'>Обнулить статистику</div></span></span></div></span>";
        }
        if ($k_post > 10) {
            echo "<div class='header'>";
            str('?rating_exp&', $k_page, $page); // Вывод страниц
            echo "</div>";
        }

        require_once('system/footer.php');
        break;
    }

    if (isset($_GET[rating_almaz])) {
        $title = 'Рейтинг по алмазам';
        require_once('system/header.php');
        echo div('header') . " Статистика  обнулялась <span class='white'> " . tl(time() - $clan['reset_almaz']) . " </span> назад </div>";

        $set['p_str'] = 10;
        $k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `id_clan` = '$clan[id]' AND `clan_almaz` >= '0'"), 0);
        $k_page = k_page($k_post, $set['p_str']);
        $page = page($k_page);
        $start = $set['p_str'] * $page - $set['p_str'];
        $q = mysql_query("SELECT * FROM `users` WHERE `id_clan` = '$clan[id]' AND `clan_almaz` >= '0' ORDER BY `clan_almaz` DESC LIMIT $start, $set[p_str]");
        while ($post = mysql_fetch_assoc($q)) {
            echo "<div class='text_p1'>";

            echo "<a href='/profile/$post[id]'>$post[login]</a> " . ico('icons', 'almaz.png') . " " . n_f($post[clan_almaz], 1) . " алмазов";
            echo "</div>";


        }

        if ($user['clan_rang'] >= 4) {
            echo div('header') . " <div class='btn_grey'><a href='?ResetAlmaz'>Обнулить статистику</div></span></span></div></span>";
        }
        if ($k_post > 10) {
            echo "<div class='block_l'>";
            str('?rating_almaz&', $k_page, $page); // Вывод страниц
            echo "</div>";
        }

        require_once('system/footer.php');
        break;
    }
    if (isset($_GET[rating_gold])) {
        $title = 'Рейтинг по золоте ';
        require_once('system/header.php');
        echo div('header') . " Статистика  обнулялась <span class='white'> " . tl(time() - $clan['reset_gold']) . " </span> назад </div>";

        $set['p_str'] = 10;
        $k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `id_clan` = '$clan[id]' and `clan_gold` >= '0'"), 0);
        $k_page = k_page($k_post, $set['p_str']);
        $page = page($k_page);
        $start = $set['p_str'] * $page - $set['p_str'];
        $q = mysql_query("SELECT * FROM `users` WHERE `id_clan` = '$clan[id]' AND `clan_gold` >= '0' ORDER BY `clan_gold` DESC LIMIT $start, $set[p_str]");
        while ($post = mysql_fetch_assoc($q)) {
            echo "<div class='text_p1'>";
            echo " <a href='/profile/$post[id]'>$post[login]</a> " . ico('icons', 'gold.png') . " " . n_f($post[clan_gold], 1) . " золота ";
            echo "</div>";

        }

        if ($user['clan_rang'] >= 4) {
            echo div('header') . " <div class='btn_grey'><a href='?ResetGold'>Обнулить статистику</div></span></span></div></span>";
        }

        if ($k_post > 10) {
            echo "<div class='block_l'>";
            str('?rating_gold&', $k_page, $page); // Вывод страниц
            echo "</div";
        }
        require_once('system/footer.php');
        break;
    }
    if (isset($_GET['contribution'])) {
        if (isset($_POST['almaz']) && isset($_POST['gold'])) {
            $almaz = num($_POST['almaz']);
            $gold = num($_POST['gold']);
            if ($almaz > $user[almaz] or $gold > $user[gold]) {
                $err = 'У вас не достаточно средств';
            }


            echo " <div class='block_c'> Лимит превышен</div>";

            if ($almaz < 0) {
                $err = 'Ошибка взноса средств';
            }
            if ($gold < 0) {
                $err = 'Ошибка взноса средств';
            }

            if (!$err) {
                mysql_query("update `users` set `almaz` = '" . ($user['almaz'] - $almaz) . "', `gold` = '" . ($user['gold'] - $gold) . "', `clan_almaz` = '" . ($user['clan_almaz'] + $almaz) . "', `clan_gold` = '" . ($user['clan_gold'] + $gold) . "' where (`id` = '" . $myID . "')");


                mysql_query("update `limit_clan_kazna` set `almaz` = '" . ($limit_clan_kazna['almaz'] - almaz) . "', `gold` = '" . ($limit_clan_kazna['gold'] - $gold) . "' where (`id` = '" . $limit_clan_kazna[id] . "')");
                mysql_query("update `clans` set `almaz` = '" . ($clan['almaz'] + $almaz) . "', `gold` = '" . ($clan['gold'] + $gold) . "' where (`id` = '" . $clan[id] . "')");
                $log = ' <a href="/profile/' . $user['id'] . '"> <a> ' . $user[login] . ' <a></a> пополнил казну на
 ' . ico('icons', 'gold.png') . '' . $gold . ' и  ' . ico('icons', 'almaz.png') . ' ' . $almaz . '';

                mysql_query("INSERT INTO `clan_journal` SET `clan` = '$clan[id]', `time` = '" . time() . "', `text` = '$log' ");


                $_SESSION['msg'] = 'Казна клана успешно пополнена';
                header('Location: ?');
                exit();


            } else {
                $_SESSION['msg'] = $err;
                header('Location: ?');
                exit();
            }
        } else {
            $_SESSION['msg'] = '<center><font color="red" size="4px">Поля не заполнены!</font></center>';
            header('Location: ?');
            exit();
        }
    }
    $title = 'Казна клана';
    require_once('system/header.php');
    echo "<div class='header'><div class='btn_grey'>";

    echo "<a href='?rating_almaz' class=''> <span class='almaz'> " . ico('icons', 'almaz.png') . " Рейтинг по  алмазам </a></div></div>";
    echo "<div class='header'><div class='btn_grey'>";
echo "<a href='?rating_gold' class=''> <span class='money'>" . ico('icons', 'gold.png') . "  Рейтинг по золоту </span></a></div></div>";
echo "<div class='header'><div class='btn_grey'>";
echo "<a href='?rating_exp' class=''> <span class='orange'>" . ico('icons', 'exp.png') . "  Рейтинг по опыту </span></a></div></div>";




    echo "<div class='text_p1'>";


    echo "<center><font size ='4px' color='white'> Казна<br></font>";


    echo ico('icons', 'almaz.png') . " " . n_f($clan[almaz], 1) . " " . ico('icons', 'gold.png') . " " . n_f($clan[gold], 1) . "</center>";
    echo "</div>";
    echo "<div class='header'>";

    echo "<form method='post' action='?contribution'>";


    echo ico('icons', 'almaz.png') . " Алмазы :<br><input type='text' class='input_text wt98' name='almaz' value=''></div>";
    echo "<div class='header'>";


    echo ico('icons', 'gold.png') . " Золото:<br><input type='text'  class='input_text' name='gold' value=''></div>";
    echo "<div class='header'>";

    echo "<center><input type='submit' class='btn_grey' value=' Пополнить'>
</form></center></div>";
    echo "<div class ='header'><div class ='main_link'>";

    echo "<a href='/clan/' class='llb'><div class='ssilki_dop p_0'><img src='/images/icons/back.png' width ='28px'> Вернуться назад</a></div></div>";
    require_once('system/footer.php');
    exit();
}
if (isset($_GET[my_delete_ok]) and $user[id_clan] == $clan[id] and $user[clan_rang] != 5) {
    mysql_query("UPDATE `users` SET `id_clan` = '0', `clan_gold` = '0' ,`clan_rang` = '0',  `clan_exp` = '0', `clan_almaz` = '0', `str` = `str` - '" . ($clan['str_plus']) . "', `def` = `def` - '" . ($clan['def_plus']) . "', `max_health` = `max_health` - '" . ($clan['max_health_plus']) . "', `clan_exp` = '0',  `ResetClanExp` = '0',`trust` = '0',`vstup` = '0' WHERE `id` = '" . $myID . "'");
    $log = ' <a href="/profile/' . $user['id'] . '"> <a> ' . $user[login] . ' </a></a> покинул клан';

    mysql_query("INSERT INTO `clan_journal` SET `clan` = '$clan[id]', `time` = '" . time() . "', `text` = '$log' ");


    header('Location: /');
    exit();
}
if (isset($_GET[my_delete]) and $user[id_clan] == $clan[id] and $user[clan_rang] != 5) {
    $title = 'Покинуть клан';
    require_once('system/header.php');
    echo "<div class='header'>Вы уверены что хотите покинуть клан?<br>";
    echo "<a href='/clan/' class='main_link'>Нет, отмена</a>";
    echo "<a class='main_link' href='?my_delete_ok'>Да, покинуть</a></div>";
    require_once('system/footer.php');
    exit();
}


if (isset($_GET['user']) && $user['clan_rang'] >= 3 && $user['id_clan'] == $clan['id']) {
    $id = num($_GET['user']);
    $prof = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = '" . $id . "'"));
    $title = "Редактор - $prof[login]";
    require_once('system/header.php');
    echo "<div class='wrapper'>";
    switch ($prof['clan_rang']) {
        case 1:
            $clan_rang = 'Новичок';
            break;
        case 2:
            $clan_rang = 'Сержант';
            break;
        case 3:
            $clan_rang = 'Лейтенант';
            break;
        case 4:
            $clan_rang = 'Генерал';
            break;
        case 5:
            $clan_rang = "<font color='lime'>Лидер клана</font>";
            break;
    }
    //$status =  '   '.($prof['sex'] == 'w' ? '<font color="pink">Была </font>' : '<font color="orange">Был</font>').' <span class="white"> в игре '.ico('icons','time.png').' '.vremja($prof['online']).'  </span>';

    echo "  <a href='/profile/$prof[id]'>$prof[login]</a> - $clan_rang<br>";
    echo "Сдано <span class='money'>алмазов </span> в казну " . ico('icons', 'almaz.png') . " $prof[clan_almaz]<br>Сдано <span class='money'>золота </span> в казну " . ico('icons', 'gold.png') . " $prof[clan_gold] <br> Клановый опыт: " . ico('icons', 'exp.png') . " $prof[clan_exp]   <br> Верность клану:" . ico('icons', 'clan.png') . " $prof[trust]%<br>$status</div>";
    if ($user['clan_rang'] == 4) {
    if ($prof[clan_rang] != 3 and $prof[clan_rang] < $user[clan_rang]) {
        
        if (isset($_GET[up])) {

            mysql_query("UPDATE `users` SET `clan_rang` = '" . ($prof[clan_rang] + 1) . "' WHERE `id` = '" . $prof['id'] . "'");
            $_SESSION['msg'] = '<font color="lime" size="4px">Игрок повышен !</font>';
            $log = color('lime') . ' <a href="/profile/' . $user['id'] . '"></a> <a> ' . $user[login] . ' </a></font>  повысил <a href="/profile/' . $prof['id'] . '">  ' . $prof[login] . ' </a></a> ';
            mysql_query("INSERT INTO `clan_journal` SET `clan` = '$clan[id]', `time` = '" . time() . "', `text` = '$log' ");

            header('Location: ?');
            exit();
        }
        
        
        echo div('header');

        echo "<div class='main_link'><div class='ssilki_dop p_0'><a href='?up'>Повысить</div></div></a>";
    }
    }
    
    
    
    
    if ($user['clan_rang'] == 5) {
    
     if ($prof[clan_rang] != 4 and $prof[clan_rang] < $user[clan_rang]) {
        
        if (isset($_GET[up])) {

            mysql_query("UPDATE `users` SET `clan_rang` = '" . ($prof[clan_rang] + 1) . "' WHERE `id` = '" . $prof['id'] . "'");
            $_SESSION['msg'] = '<font color="lime" size="4px">Игрок повышен !</font>';
            $log = color('lime') . ' <a href="/profile/' . $user['id'] . '"></a> <a> ' . $user[login] . ' </a></font>  повысил <a href="/profile/' . $prof['id'] . '">  ' . $prof[login] . ' </a></a> ';
            mysql_query("INSERT INTO `clan_journal` SET `clan` = '$clan[id]', `time` = '" . time() . "', `text` = '$log' ");

            header('Location: ?');
            exit();
        }
        
        
        echo div('header');

        echo "<div class='main_link'><div class='ssilki_dop p_0'><a href='?up'>Повысить</div></div></a>";
    }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    if ($prof[clan_rang] < $user[clan_rang] && $prof[clan_rang] >= 2) {
        if (isset($_GET[down])) {
            mysql_query("UPDATE `users` SET `clan_rang` = '" . ($prof[clan_rang] - 1) . "' WHERE `id` = '" . $prof['id'] . "'");
            $log = color('lime') . ' <a href="/profile/' . $user['id'] . '"></a> <a> ' . $user[login] . ' </a></font> понизил <a href="/profile/' . $prof['id'] . '">  ' . $prof[login] . ' </a></a> ';
            mysql_query("INSERT INTO `clan_journal` SET `clan` = '$clan[id]', `time` = '" . time() . "', `text` = '$log' ");


            header('Location: ?');
            exit();
        }
        echo "<div class='main_link'><div class='ssilki_dop p_0'><a href='?down' class='link center'>Понизить</div></div></a>";
    }
    if ($prof['clan_rang'] == 1 && $prof['clan_rang'] < $user['clan_rang']) {

        if (isset($_GET['kick'])) {
            mysql_query("UPDATE `users` SET `max_health` = `max_health` - '" . $clan['max_health_plus'] . "', `def` = `def` - '" . $clan['def_plus'] . "', `id_clan` = '0', `clan_gold` = '0' ,`clan_rang` = '0',  `clan_exp` = '0', `clan_almaz` = '0', `clan_exp` = '0',  `ResetClanExp` = '0',`trust` = '0',`vstup` = '0', `str` = `str` - '" . $clan['str_plus'] . "' WHERE `id` = '" . $prof['id'] . "'");

            $log = color('lime') . ' <a href="/profile/' . $user['id'] . '"></a> <a> ' . $user[login] . ' </a></font> исключил из клана <a href="/profile/' . $prof['id'] . '">  ' . $prof[login] . ' </a></a> ';
            mysql_query("INSERT INTO `clan_journal` SET `clan` = '$clan[id]', `time` = '" . time() . "', `text` = '$log' ");

            $_SESSION['msg'] = 'Вы исключили игрока <a>' . $prof['login'] . '</a> </font>';

            header('Location: /clan/');
            exit();
        }
        echo "<div class='main_link'><div class='ssilki_dop p_0'><a href='?kick' class='link center'>Исключить из клана</a></div></div>";

    }
    echo "</div>";
    require_once('system/footer.php');
    exit();
}

if (isset($_GET['setting_clan'])) {
    $title = 'Настройки ';
    require_once('system/header.php');
    echo "<div class='header'>
";
    if ($user['id_clan'] == $clan['id'] && $user['clan_rang'] != 5) {
        echo "<a href='?my_delete' <div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/settings.png' width ='28px'> Покинуть клан</div></div></a>";
    } else {
        echo "<a href='?del'><div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/settings.png' width ='28px'> Удалить клан </div><br>" . span('white') . "Запроса удалить клан или нет не будет, после нажатия клан удаляется сразу же.</span></div></div></a>";

    }
    echo div('header');

    if ($user['clan_rang'] == 5) {
        echo "<a href='?info'><div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/settings.png' width ='28px'> Установить описание </div></div></a>";
    }
    if ($user['clan_rang'] > 4) {
        echo "<a href='?n'><div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/settings.png' width ='28px'> Изменить название клана </div></div></a>";
    }

    if ($user['clan_rang'] >= 3) {
        echo "<a href='?announcement'><div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/settings.png' width ='28px'> Добавить объявление  </div></div></a>";
    }


    echo "</div>";

    require_once('system/footer.php');
    exit();
}

// удаление клана
if (isset($_GET['del']) and $user['clan_rang'] == 5) {

    mysql_query("update `users` set `id_clan` = '0', `max_health` = `max_health` - '" . $clan['max_health_plus'] . "', `def` = `def` - '" . $clan['def_plus'] . "', `clan_rang` = '0', `str` = `str` - '" . $clan['str_plus'] . "' where (`id_clan` = '" . $clan['id'] . "')");
    mysql_query("DELETE FROM `clans` WHERE `id`='$user[id_clan]' ");
    $_SESSION['msg'] = "Bы распустили клан!";
    header('location:/');
    exit();
}


//Обьявление

if (isset($_GET['announcement']) and $user['clan_rang'] >= 3 and $user['id_clan'] == $clan['id']) {
    require_once('system/header.php');

    if (isset($_REQUEST['add'])) {
        $announcement = text($_POST['announcement']);
        if (empty($announcement)) {
            $err = 'Ошибка';
        }
        if (mb_strlen($announcement) > 1000 or mb_strlen($announcement) < 3) {
            $err = 'Описание не может быть короче 3 и длиннее 1000 символов';
        }
        if (!$err) {
            mysql_query("UPDATE `clans` SET `announcement` = '$announcement' WHERE `id` = '" . $clan['id'] . "'");
            mysql_query("UPDATE `users` SET `announcement_read` = '1' WHERE `id_clan` = '" . $clan['id'] . "'");
            $_SESSION['msg'] = "Обьявление создано!";
            header('Location: /clan/');
            exit();
        } else {
            $_SESSION['msg'] = $err;
            header('Location: ?announcement');
            exit();
        }
    }

    echo "<div class='header'>";
    echo '<form action="" method="post">';
    echo 'Новое объявление:
<input type="text" name="announcement" maxlength="1000" value="" /><br/>';
    echo '<input type="submit" name="add" class="auth_login" value="Продолжить">';
    echo '</form>';
    echo "</div>";
    $clan = '';
    require_once('system/footer.php');
    exit();
}


//Описание
if (isset($_GET['info'])) {
    require_once('system/header.php');

    if (isset($_REQUEST['add'])) {

        $info = text($_POST['info']);

        $sql = mysql_query("SELECT COUNT(`id`) FROM `clans` WHERE `info` = '$info'"); // Доступность описания
        if (empty($info)) {
            $err = 'Введите статус';
        }
        if (mysql_result($sql, 0) > 0) {
            $err = 'Такой статус уже занят';
        }
        if (mb_strlen($info) >= 500 or mb_strlen($info) < 3) {
            $err = 'Описание не может быть короче 3 и длиннее 500 символов';
        }
        if (!$err) {
            mysql_query("UPDATE `clans` SET `info` = '$info'  WHERE (`id` = '" . $clan[id] . "')");
            $_SESSION['msg'] = "Вы успешно изменили ";
            header('Location: ?');
            exit();
        } else {
            $_SESSION['msg'] = $err;
            header('Location: ?info');
            exit();
        }
    }
    echo "<div class='block_c'>";
    if ($user['clan_rang'] < 4) {
        echo "<div class='block_b'>ОШИБКА </div>";
        break;
    }


    echo '<div class="header">';
    if (!empty($clan['info'])) {
        echo ' Текущий статус: <font color=orange>' . n_f($clan['info']) . '</font><br/>';
    }
    echo '</div>';
    echo '</div>';

    echo '<div class="block_c">';
    echo '<form action="" method="post">';
    echo 'Новый статус:
<input type="text" name="info" maxlength="1000" value="" /><br/>';
    echo '<input type="submit" name="add" class="auth_login" value="Установить"></form>';

    echo "</div>";
    require_once('system/footer.php');

    break;


}

//Измена название клана
if (isset($_GET['n'])) {
    $price = 500;


    require_once('system/header.php');
    if (isset($_REQUEST['add'])) {
        if ($price > $clan['almaz']) {
            $_SESSION['msg'] = " Не хватает алмазов  ";
            header('Location: ?n');
            exit();

        }
        $change = text($_POST['change']);
        $sql = mysql_query("SELECT COUNT(`id`) FROM `clans` WHERE `name` = '$change'"); // Доступность описания
        if (empty($change)) {
            $err = 'Введите название клана';
        }
        if (mysql_result($sql, 0) > 0) {
            $err = 'Такой клан уже есть';
        }
        if (mb_strlen($change) >= 30 or mb_strlen($change) < 3) {
            $err = 'Название не может быть короче 3 и длиннее 30 символов';
        }
        if (!$err) {
            mysql_query("UPDATE `clans` SET `name` = '$change' WHERE (`id` = '" . $clan[id] . "')");
            mysql_query("UPDATE `clans` SET `almaz` = '" . ($clan[almaz] - $price) . "' WHERE `id` = '" . $clan['id'] . "'");

            $_SESSION['msg'] = "Вы успешно изменили ";
            header('Location: ?');
            exit();
        } else {
            $_SESSION['msg'] = $err;
            header('Location: ?n');
            exit();
        }
    }
    echo "<div class='block_c'>";
    if ($user['clan_rang'] < 5) {
        echo "<div class='block_b'>ОШИБКА </div>";
        break;
    }


    echo '</div><div class="block_c">';
    echo '<form action="" method="post">';
    echo 'Введите новое название клана:<br>
<input type="text" name="change" maxlength="1000" value="" /><br/>';
    echo '<input type="submit" name="add" class="button" value="Изменить название "></form>';
    echo "</div>";
    echo '<div class="header"> Смена название клана стоит ' . $price . '' . ico('icons', 'almaz.png') . '</div>';


    require_once('system/footer.php');

    break;


}


require_once('system/header.php');

$title = $clan[name];


echo "<div class='header'>";

echo ico('icons', 'clan.png') . " $clan[name]<br>
" . img('icons', 'flag.png') . "<br>" . ico('icons', 'level.png') . " Уровень: $clan[level]<br>" . ico('icons', 'exp.png') . " Опыт: " . n_f($clan[exp]) . "/" . n_f(clan_exp($clan[level])) . " (" . round($clan[exp] / clan_exp($clan[level]) * 100, 1) . "%)<br>";

echo "<div class='exp'><div class='exp_in' style='width:" . round($clan[exp] / clan_exp($clan[level]) * 100, 1) . "%;'></div></div>";
echo "</div>";
echo div('header center ') . "" . $clan['info'] . "</div>";

echo "<div class='text_p1 center'>";

echo "" . ico('icons', 'str.png') . " +$clan[str_plus]";
echo "" . ico('icons', 'def.png') . " +$clan[def_plus] ";
echo "" . ico('icons', 'health.png') . " +$clan[max_health_plus] <br>";
//echo "</div>";


echo div('heade') . " </span>  " . ico('icons', 'exp.png') . " + $clan[level]%   " . ico('icons', 'gold.png') . " + $clan[level]% </div>";
echo "</div>";


//$podzemelie = mysql_fetch_assoc(mysql_query("SELECT * FROM `clan_podzemelie` WHERE `id_clan` = '$clan[id]' ORDER BY `id` DESC LIMIT 1"));
//if($user[id_clan] == $clan[id])echo "<li class='original'><a href='/clan/podzemelie/'><div class='oh'><img src='/images/clan/boss/10.png' width='30px'></div>".ico('icons','sum_stat.png')."Клановое подземелье ".($podzemelie['last'] < time() ? "<font color='green'>(+)</font>" : "")."<br>".($podzemelie['last'] < time() ? "<span class='small grey'>Беспощадные монстры</span>" : "<span class='small grey'>До следующего боя: ".tl($podzemelie['last']-time())."</span>")."<div style='clear:both;'></div></a></li>";
echo div('header');

//if($user['id_clan'] == $clan['id'])echo "<div class='text'><a href='/clan.php?id=".$user['id_clan']."&tour#".$r."' class='link'><img src='/icons/clan/tour.png' width='16' height='16'> Клановый турнир</a>";


if ($user[id_clan] == $clan[id]) {
    echo "<a class='llb' href='/clan/b/'><div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/build.png' width ='28px'> " . span('white') . "  Клановые постройки </span></div></div></a>";
}
echo "<a class='llb ' href='/clan/$id/forum'><div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/topic1.png' width ='28px'> " . span('white') . " Форум клана</span></div></div></a>";
if ($user[id_clan] == $clan[id]) {
    echo "<a class='llb 'href='/clan_journal.php'><div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/journal.png' width ='28px'> " . span('white') . "Журнал клана</span></div></div></a>";
}
if ($user[id_clan] == $clan[id]) {
    echo "<a class='llb'href='/clan/treasury/'><div class='main_link'> <div class='ssilki_dop p_0'><img src='/images/icons/ItemShop.png' width ='28px'>" . span('white') . " Казна клана</span></div></div></a>";
}
if ($user[id_clan] == $clan[id]) {
    echo "<a class='llb 'href='/clan/chat/'><div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/chat1.png' width ='28px'> " . span('white') . " Чат клана</span></div></div></a>";
}

if ($user[id_clan] == $clan[id]) {
    echo "<a class='llb' href='/clan/?setting_clan'><div class='main_link'><div class='ssilki_dop p_0'><img src='/images/icons/settings.png' width ='28px'> " . span('white') . " Настройки</div></div></a>";
}
echo "</div>";

$member = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `id_clan` = '$clan[id]' "));
$member_on = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `id_clan` = '$clan[id]' AND  `online` > '" . (time() - 1800) . "'"));


echo div('header') . "";
echo span('grey') . " Состав клана:</span>" . n_f($member) . "  </div> ";
$set['p_str'] = 10;
$k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `users` WHERE `id_clan` = '$clan[id]'"), 0);
$k_page = k_page($k_post, $set['p_str']);
$page = page($k_page);

$start = $set['p_str'] * $page - $set['p_str'];
$q = mysql_query("SELECT * FROM `users` WHERE `id_clan` = '$clan[id]' ORDER BY  `clan_rang` DESC, `clan_exp` DESC LIMIT $start, $set[p_str]");


while ($post = mysql_fetch_assoc($q)) {
    echo "<div class='wrapper'>";

    switch ($post['clan_rang']) {
        case 1:
            $clan_rang = 'Новичок';
            break;
        case 2:
            $clan_rang = 'Сержант';
            break;
        case 3:
            $clan_rang = 'Лейтенант';
            break;
        case 4:
            $clan_rang = 'Генерал';
            break;
        case 5:
            $clan_rang = "<font color='lime'>Лидер клана</font>";
            break;
    }


    if ($post['online'] > time() - 300) {
        $online = color('yellow') . " *</font>";
    } else if ($post['online'] > time() - 900) {
        $online = color('yellow') . " ** </font>";
    } else {
        $online = color('red') . " * </font>";
    }


    echo icons_user($post[id])."  <a href='/profile/$post[id]'>$post[login] </a> $online  $clan_rang";
    echo "       " . ico('icons', 'exp.png') . " " . n_f($post['clan_exp']);
    if ($myID != $post['id'] and $user['id_clan'] == $clan['id'] and $user['clan_rang'] >= 3) {
        echo "  <a href='/clan/user/$post[id]/'>Изменить </a>";
    }
    echo "</div>";


}


if ($k_post > 10) {
    echo "<div class='header'>";
    str('?', $k_page, $page); // Вывод страниц

    echo "</div>";

}

require_once('system/footer.php');
?>
