<?
include './system/common.php';
include './system/functions.php';
include './system/user.php';
    
if(!$user OR $user['access'] < 1) {
header('location: /');   
exit;}

switch($_GET['action']) {
default:

$title = 'Панель управления';    
include './system/h.php';


echo'<div class="title">'.$title.'</div>';


if($user['access'] >= '1') {
echo'<div class="block_link"><a href="/ban/list/"> Все забаненные</a></div>
<div class="line"></div>';}
if($user['access'] >= '2') {
echo'<div class="block_link"><a href="/adm/block/list/"> Все заблокированые</a></div>
<div class="line"></div>';}



  echo'<div class="block_link"><a href="/adm/chat/"> Админ чат</a></div>
<div class="line"></div>';

$tickets = mysql_result(mysql_query('SELECT COUNT(*) FROM `ticket` WHERE `admin_read`="0" ORDER BY `id`'),0);
echo'<div class="block_link"><a href="/tickets/admin_question/"> Служба поддержки '.($tickets >= 1 ? '<font color="green">+</font>':'').'</a></div>
<div class="line"></div>';



include './system/f.php';
break;
/////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////// 
case 'clon':
$title = 'Проверка на мультоводство';    
include './system/h.php';

echo'<div class="title">'.$title.'</div>';

$id = _string(_num($_GET['id']));
  if($id) {
    $users = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$id.'"');
    $users = mysql_fetch_array($users);
  
  if(!$users) {
header('location: /adm/clon/');
exit;}

$count = mysql_result(mysql_query('SELECT COUNT(*) FROM `users` WHERE `ip` = "'.$users['ip'].'" AND `id` != "'.$users['id'].'"'),0);

echo' <div class="empty_block">
IP: '.$users['ip'].' ['.$users['ua'].']<br/>
</div>
<div class="line"></div>';





if($count > 0) {

$q = mysql_query('SELECT * FROM `users` WHERE `ip` = "'.$users['ip'].'" AND `id` != "'.$users['id'].'"');
  while($row = mysql_fetch_array($q)) {
echo'<div class="block_link"><a href="/user/'.$row['id'].'/"> '.nick($row['id']).' 
</a></div>
<div class="line"></div>';
  }
}else{
echo'<div class="empty_block item_center">Мультов нет!</div>
<div class="line"></div>';
}
  
}else{


echo' <div class="empty_block item_center">
Произошла ошибка</div>
<div class="line"></div>
<div class="block_link"><a href="/adm/"><img src="/images/ico/png/back.png" alt="*"/> Вернуться</a></div>
<div class="line"></div>';
}
include './system/f.php';
break;
///////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
case 'block':
$id = abs(intval($_GET['id']));
$block = mysql_fetch_assoc(mysql_query("SELECT * FROM `block` WHERE `user` = '".$id."'"));

if($user['id'] == $id){
header('Location: /user/'.$id.'/');
$_SESSION['mes'] = mes('Вы не можете сами себя заблокировать!');
exit; }

if(isset($block['user']))
{
  if($user['access'] < '2'){
     header('Location: /user/'.$id.'');
     $_SESSION['mes'] = mes('Произошла ошибка!');
     exit;   
}

}

 if(isset($_REQUEST['submit'])) { //Если нажимаем Да
$text = _string($_POST['text']);
$time = _string($_POST['time']);
    $users = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$id.'"');
    $users = mysql_fetch_array($users);
    
  $count = mysql_result(mysql_query('SELECT COUNT(*) FROM `block` WHERE `user` = "'.$users['id'].'"'),0);
  if($count == 0) {
      if(mb_strlen($text) < 3){
      header('Location: /adm/block/'.$id.'');
     $_SESSION['mes'] = mes('Вы не ввели причину!');
     exit;  }
  if($users['access'] >= $user['access']){
      header('Location: /adm/block/'.$id.'');
     $_SESSION['mes'] = mes('У вас недостаточно прав!');
     exit;  }
        
    mysql_query('INSERT INTO `block` (`user`,
                                    `time`,
                                    `text`,
									`who`,
                                      `ip`) VALUES ("'.$users['id'].'",
               "'.(time() + $time).'",
			                                               "'.$text.'",
											        "'.$user['id'].'",
                                                    "'.$users['ip'].'")');


   
$_SESSION['mes'] = mes('Персонаж заблокирован');	
header('location: /adm/block/'.$id.'');
exit;
}else{
$_SESSION['mes'] = mes('Персонаж уже заблокирован');	
header('location: /adm/block/'.$id.'');
exit;
}

}
$title='Заблокировать';
include './system/h.php';
echo '<div class="title">'.$title.'</div>';

     echo' '.$_SESSION['mes'].'  ';
    $_SESSION['mes']=NULL; //Удаляем сесию
echo '<div class="empty_block item_center">Вы действительно хотите заблокировать '.nick($id).' ? </div>
<div class="line"></div>
<div class="empty_block item_center">
<form action="/adm/block/'.$id.'" method="post">
Причина:<br/>
<textarea name="text" style="width: 70%;"> '.($to ? $_to['login'].', ':'').' </textarea><br/>

Время:<br/>
<select name="time"/>
<option value="3600"> 1 час </option> 
<option value="43200"> 12 час </option> 
<option value="604800"> 7 деней </option> 
<option value="2592000"> 1 месяц </option> 
<option value="99999999999"> Навсегда </option> 
</select/> 

<center><input class="button" type="submit" name="submit" value="Сохранить"/></center>
</form></div>
<div class="line"></div>
<div class="block_link"><a href="/adm/block/list/"><img src="/images/ico/png/black.png" alt="*"/> Все заблокированые ('.mysql_result(mysql_query('SELECT COUNT(*) FROM `block` WHERE `time` > "'.time().'"'),0).') </a></div>
<div class="line"></div>';
include './system/f.php';
break;

case 'block_list':
$title='Все заблокированые';
include './system/h.php';
echo '<div class="title">'.$title.'</div>';
    
echo' '.$_SESSION['mes'].'  ';
$_SESSION['mes']=NULL; //Удаляем сесию
    
$max = 10;
$count = mysql_result(mysql_query('SELECT COUNT(*) FROM `block` WHERE `time` > "'.time().'"'),0);
$pages = ceil($count/$max);
$page = _string(_num($_GET['page']));

if($page > $pages) {$page = $pages;}
if($page < 1) {$page = 1;}
$start = $page * $max - $max;


if($count > 0) {
$id = _string(_num($_GET['id']));

  if($id) { 
  $block = mysql_query('SELECT * FROM `block` WHERE `id` = "'.$id.'"');
  $block = mysql_fetch_array($block);
  
  if(!$block) {
$_SESSION['mes'] = mes('Игрок не заблокирован!');	
header('location: /adm/block/list/?page='.$page);
exit;}
  


  if($_GET['delete'] == true) {
$_SESSION['mes'] = mes('С игрока снята блокировка!');	
mysql_query('DELETE FROM `block` WHERE `id` = "'.$id.'"');
header('location: /adm/block/list/?page='.$page);
} 
  }



$q = mysql_query('SELECT * FROM `block` WHERE `time` > "'.time().'" ORDER BY `id` DESC LIMIT '.$start.', '.$max.'');
while($row = mysql_fetch_array($q)) {

  $u = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$row['user'].'"');
  $u = mysql_fetch_array($u);


echo'<div class="empty_block">
<span style="float: right;"> <a href/adm/block/list/?id='.$row['id'].'&delete=true&page='.$page.'"> снять</a></span>
<a href="/user/'.$u['id'].'/">'.nick($u['id']).'</a>
  <br/>
  Причина: '.$row['text'].' </br>
  Осталось: '._time($row['time'] - time()).'
  </div><div class="line"></div>';
}

echo pages('/adm/block/list/?');
echo'<div class="line"></div>';
 
}else{
echo'<div class="empty_block item_center">
Нет заблокированных игроков </div>
<div class="line"></div>';
}
include './system/f.php';
break;
//////////////////////////////////////////////////////////




  
  
  
////////////////////////////////////////////////////////
case 'acc':
$id = _string(_num($_GET['id']));
if($user['access'] < 3) {//Доступно только создателю
header('location: /adm/');
$_SESSION['mes'] = mes('У вас недостаточно прав!');
exit;
}
	
$title = 'Редактирование Игрока';
include './system/h.php';
echo '<div class="title">'.$title.' '.nick($id).'</div>';


     if(isset($_REQUEST['submit'])) { //Если нажимаем Да
mysql_query('UPDATE `users` SET `login` = \''._string($_POST['login']).'\', `sex` = '._string(_num($_POST['sex'])).', `s` = '._string(_num($_POST['s'])).', `g` = '._string(_num($_POST['g'])).', `level` = '._string(_num($_POST['level'])).', `exp` = '._string(_num($_POST['exp'])).', `str` = '._string(_num($_POST['str'])).', `vit` = '._string(_num($_POST['vit'])).', `def` = '._string(_num($_POST['def'])).' WHERE `id` = '.$id.' LIMIT 1');
header('location: /adm/acc/'.$id.'/');
$_SESSION['mes'] = mes('Игрок успешно отредактирован!');
exit;
}


$acc = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = '.$id.' LIMIT 1'));
echo' '.$_SESSION['mes'].'  ';
$_SESSION['mes']=NULL; //Удаляем сесию

echo'<div class="empty_block">
<form action="/adm/acc/'.$id.'/" method="post">
Никнейм:<br/>
<input type="text" name="login" value="'.$acc['login'].'"/> <br/>
Пол:
<select name="sex"/> 
<option value="1">Мужской</option>
<option value="2">Женский</option> 
</select/> </br>
Кол-во серебра:<br/>
<input name="s" value="'.$acc['s'].'"/> <br/>
Кол-во золота:<br/>
<input name="g" value="'.$acc['g'].'"/> <br/>
Уровень:<br/>
<input name="level" value="'.$acc['level'].'"/> <br/>	
Опыт:<br/>
<input name="exp" value="'.$acc['exp'].'"/> <br/>	
Сила:<br/>
<input name="str" value="'.$acc['str'].'"/> <br/>	
Жизнь:<br/>
<input name="vit" value="'.$acc['vit'].'"/> <br/>	

Защита:<br/>
<input name="def" value="'.$acc['def'].'" /> <br/>

<center><input class="button" type="submit" name="submit" value="Сохранить"/></center>
</form></div>
<div class="line"></div>';
			


include './system/f.php';
break;
////////////////////////////////////////////////////////////////




/////////////////////////////////////////////////////////////////
case 'chat':


$title = 'Админ чат';
include './system/h.php';  
echo '<div class="title">'.$title.'</div>';




$text = _string($_POST['text']);
$to = _string(_num($_GET['to']));

  if($to) {
$_to = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$to.'"');
$_to = mysql_fetch_array($_to); }
  
  
  
  
  if(isset($_REQUEST['text'])){
$antiflood = mysql_fetch_array(mysql_query('SELECT * FROM `admin_chat` WHERE `user` = \''.$user['id'].'\' ORDER BY `time` DESC LIMIT 1'));
  
  if(empty($text) or mb_strlen($text,'UTF-8') < 1){
header("Location: ?");
$_SESSION['mes'] = mes('Пустое сообщение!');
exit;}
  if(time() - $antiflood['time'] < 0){
header("Location: ?");
$_SESSION['mes'] = mes('Нельзя писать так часто!');
exit;}
    



$typemsg=_string($_POST['typemsg']);
      if($user['access']>='2' && $typemsg=='sys'){//Если сообщение от системы
  
  mysql_query('INSERT INTO `admin_chat` (`user`, `to`, `text`, `time`) VALUES ("2",  "'.$_to['id'].'", "'.$text.'", "'.time().'")');


}else{//Если от простого пользователя
mysql_query('INSERT INTO `admin_chat` (`user`,`to`,`text`,`time`)
                            VALUES ("'.$user['id'].'",  "'.$_to['id'].'", "'.$text.'", "'.time().'")');
}
      
header('location: /adm/chat/');
$_SESSION['mes'] = mes('Сообщение отправленно!');
exit;  
}


  
  
     echo' '.$_SESSION['mes'].'  ';
    $_SESSION['mes']=NULL; //Удаляем сесию
echo'   
<div class="empty_block" align="center">
<form action="/adm/chat/?to='.$to.'" method="post">
Сообщение:<br/>
<textarea name="text" style="width: 70%;"> '.($to ? $_to['login'].', ':'').' </textarea><br/>
<input class="button" name="send_message" value="Отправить" type="submit">';

if($user['access']=='3'){
echo'<Select name="typemsg"/>
<option value="adm">'.$user['login'].'</option>
<option value="sys">Система</option>
</Select>';
}
echo'</form>
<small><a href="'.$HOME.'/adm/chat">Обновить</a> | <a href="'.$HOME.'/smile">Смайлы</a> | <a href="'.$HOME.'/bb">BB коды</a></small>
</div>
<div class="line"></div>';


?>

  

<?

$max = 10;
$count = mysql_result(mysql_query('SELECT COUNT(*) FROM `admin_chat` '),0);
$pages = ceil($count/$max);
$page = _string(_num($_GET['page']));

if($page > $pages) {$page = $pages;}
if($page < 1) {$page = 1;}
$start = $page * $max - $max;

if($count > 0) {
$q = mysql_query('SELECT * FROM `admin_chat` ORDER BY `id` DESC LIMIT '.$start.', '.$max.'');
  while($row = mysql_fetch_array($q)) {
    echo'<div class="empty_block">';

  if($row['to'] == $user['id'] && $row['read'] == 0) {
mysql_query('UPDATE `admin_chat` SET `read` = "1" WHERE `id` = "'.$row['id'].'"');  
}

  $sender = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$row['user'].'"');
  $sender = mysql_fetch_array($sender);

echo'<a href="/user/'.$sender['id'].'/"> '.nick($sender['id']).' </a>';//Логин отправителя

  if($sender['id'] != $user['id']) {//Ответить на сообщение
echo'<a href="/adm/chat/?to='.$sender['id'].'">(&#187;)</a>';
}
  if($user['access'] == 3) {//Удаляем сообщение
echo'<a href="/adm/chat/delmsg/'.$row['id'].'/">[x]</a>';}
echo'<span style="float: right;"><small>'.vremja($row['time']).'</small></span>';
echo':<br/>';


echo'<font color="'.color($sender[id]).'">';//Цвет сообщений
  

  if($row['to']) {//Если ответ вам
      $__to = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$row['to'].'"');
      $__to = mysql_fetch_array($__to);
if($__to['id'] == $user['id']) {
echo'<font color="#90c090">';
}else{
echo'<font color="'.color($sender[id]).'">';  
}
echo''.$__to['login'].',
</font>';
 
}




echo''.bbcode(smile($row['text'])).'';//Сообщение
echo'</font>';//Закрываем цвет сообщений



  echo'</div>
<div class="line"></div>';
}

}else{ 
echo '<div class="line"></div>
<div class="empty_block item_center"> Сообщений нет </div>
<div class="line"></div>';
}


echo''.pages('/adm/chat/?').'';
echo'<div class="line"></div>';
include './system/f.php';
break;


case 'delmsg':
$id = abs(intval($_GET['id']));
$gg = mysql_fetch_assoc(mysql_query("SELECT * FROM `admin_chat` WHERE `id` = '".$id."'"));
if(isset($gg['id']))
{
  if($user['access'] != 3){
     header("Location: /adm/chat");
     $_SESSION['mes'] = mes('Произошла ошибка!');
     exit;   
}
}else{
      header("Location: /adm/chat");
     $_SESSION['mes'] = mes('Произошла ошибка!');
     exit;   
}

 if(isset($_REQUEST['submit'])) { //Если нажимаем Да
mysql_query("DELETE FROM `admin_chat` WHERE `id` = '".$gg[id]."'");
      header('Location: /adm/chat');
     $_SESSION['mes'] = mes('Сообщение удалено!');
     exit;   
}
include './system/h.php';
     echo '<div class= "block">'.nick($gg['user']).'  '.vremja($gg['time']).' <br/> '.bb(smile($gg['text'])).'</div>';
     echo '<div class="empty_block item_center"> Вы действительно хотите удалить?
<form action="" name="message" method="POST"> 
<input class="button" type="submit" name="submit" value="Да"/> <br>
<a href="/adm/chat"> <input class="button2" value="Нет"/>
</form></div><div class="line"></div>';
    echo '<div class="block_link"><a href="/adm/chat"><img src="/images/ico/png/back.png" width="18">Вернуться</a></div>
   <div class="line"></div>';
include './system/f.php';
break;
////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////
case 'access':
$title = 'Назначить на должность';    
include './system/h.php';

echo'<div class="title">'.$title.'</div>';

$id = _string(_num($_GET['id']));
$acc = array("Пользователь","Модератор","Администратор","Создатель");


if($user['id'] == $id){
header('Location: /user/'.$id.'/');
$_SESSION['mes'] = mes('Вы не можете изменять свою должность!');
exit; }


if(isset($_REQUEST['submit'])) { //Если нажимаем Да

$_access=_string(_num($_POST['access']));
mysql_query('UPDATE `users` SET `access`="'.$_access.'" WHERE `id`="'.$id.'" ');

$text='Вы были назначены на должность [img=20]/images/ico/png/premium.png[/img] '.$acc[$_access].' ';
mysql_query("INSERT INTO `mail` SET `from`='2',`to`='".$id."',`text`='".$text."',`time`='".time()."'"); //Отправляем уведомление
mysql_query('UPDATE `contacts` SET `time` = \''.time().'\' WHERE `user` = "2" AND `ho` = "'.id.'" ');  //Оновляем время 
mysql_query('UPDATE `contacts` SET `time` = \''.time().'\' WHERE `ho` = "2" AND `user` = "'.$id.'" ');  //Оновляем время 

header('Location: /adm/access/'.$id.'/');
$_SESSION['mes'] = mes('Игрок назначен на должность '.$acc[$_access].'!');
exit; 
}
  



echo' '.$_SESSION['mes'].'  ';
$_SESSION['mes']=NULL; //Удаляем сесию

echo' <div class="empty_block item_center">Выберите подходящую должность для: '.nick($id).' ? </div>
<div class="line"></div>
<div class="empty_block item_center">
<form action="/adm/access/'.$id.'/" method="post">
<select name="access"/> ';
    
    for($i=0;$i<=$user['access'];$i++){ 
echo'<option value="'.$i.'">'.$acc[$i].'</option> '; } 
echo'</select/> </br>
<input class="button" type="submit" name="submit" value="Продолжить"/>
</form></div>
<div class="line"></div>';

include './system/f.php';
break;
}
  
?>