<?php
require_once('../classes/body.class.php');
require_once('../classes/db.class.php');
require_once('../classes/system.class.php');
$title= new Body;
$title->SetTitle('Панель управления - Админ форум');

///Подключаем шапку
$title->GetHeader();

if ($b['level'] == 0) {
header('location:/');
die();
}
echo '<div class="container-fluid page_header"><div class="container"><div class="row"><div class="col-xs-12 col-sm-8 col-md-9 col-lg-9"><h1>Панель управления </h1><ol class="breadcrumb" xmlns:v="http://'.homeurl.'/#"><li typeof="v:Breadcrumb"><a href="/" rel="v:url" property="v:title">'.homeurl.'</a></li><li typeof="v:Breadcrumb"><a href="/panel" rel="v:url" property="v:title">Дата-центр</a></li> <li class="active" typeof="v:Breadcrumb"><span property="v:title">Админ форум</span></li></ol></div></div></div></div>';
echo'<div class="container page_body"><div class="row"><div class="col-xs-12 page_content col-lg-9"><div class="navbar page_content_navbar collapse hidden-lg"><div class="container-fluid"><div class="navbar-collapse"></div></div></div><div class="text_box hidden-lg pr_block_small hidden"></div><div class="container-fluid cols_table">';
$do = isset($_GET['do']) ? check($_GET['do']) : false;
switch($do) {
default:
echo '<div class="catSides"><a href="/panel"><i class="md-format-list-bulleted"></i> Админка</a> - Админ форум</div>';
echo '<ul class="nav nav-pills nav-stacked"><li><a href="rulls.html"><i class="md-forum"></i>  Правила модераторов <strong><span style="color:#ff0000;">[Обязательно!]</span></strong></a></ul>';
echo '<div class="row text_box"><i class="md-shuffle"></i> <a href="?do=add">Создать</a> | <a href=javascript:document.location.reload()>Обновить</a></div>';

$k_topic = DB::$dbs->querySingle("SELECT COUNT(id) FROM adm_topic");
$num = 10;
$k_page = k_page($k_topic, $num);
$page = page($k_page);
$start = $num*$page-$num;
$sql = DB::$dbs->query("SELECT * FROM adm_topic ORDER BY last DESC LIMIT $start,$num");
if ($sql -> rowCount() == 0) {
err('Тем ещё не нет!');
} else {
while($a = $sql->fetch()) {
$us_mess = DB::$dbs->queryFetch("SELECT user_id,tid,time FROM adm_mess WHERE tid = ? ORDER BY time DESC", [$a['id']]);
$k_mess = DB::$dbs->querySingle("SELECT COUNT(id) FROM adm_mess WHERE tid = ?", array($a['id']));
if ($k_mess > 10) {
$pg = ceil($k_mess / 10);
$st = ' <a href="?do=view&id='.$a['id'].'&page='.$pg.'">></a>';
} else {
$st = '';
}
echo '<div class="row text_box"><a href="?do=view&id='.$a['id'].'"><i class="md-forum"></i>  '.($a['type'] == 1 ? '#':NULL).' '.$a['name'].'</a> ('.$k_mess.') '.$st.' ('.Nick($us_mess['user_id']).' написал '.vr($us_mess['time']).')</div>';
}
}
if ($k_page>1) {
str('?', $k_page,$page);
}
break;
case 'add':
echo '<div class="catSides"><a href="/panel"><i class="md-format-list-bulleted"></i> Админка</a> - <a href="fort.html">Админ форум</a> - Создать тему</div>';
if (isset($_POST['add'])) {
$err = [];
$form = ['name' => isset($_POST['name']) ? check($_POST['name']) : null, 'text' => isset($_POST['text']) ? check($_POST['text']) : null];
if (empty($form['name']) OR empty($form['text'])) {
$err[] = 'Заполните название темы и её содержание!';
}
if (mb_strlen($form['name']) < 3 OR mb_strlen($form['name']) > 45) {
$err[] = 'Ошибка названия темы! Мин. 3 / макс. 45 символов.';
}
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM adm_topic WHERE name = ?", [$form['name']]) > 0) {
$err[] = 'Такая тема уже есть!';
}
if (empty($err)) {
DB::$dbs->query("INSERT INTO adm_topic SET name = ?, user_id = ?, time = ?, last = ?", [$form['name'],$b['id'],time(),time()]);
$last = DB::$dbs->lastInsertId();
DB::$dbs->query("INSERT INTO adm_mess SET text = ?, user_id = ?, time = ?, tid = ?", [$form['text'],$b['id'],time(),$last]);
header('location: ?do=view&id='.$last);
die();
} else {
echo '<div class="error">';
foreach($err as $error) {
echo '<b>'.$error.'</b><br/>';
}
echo '</div>';
}
}
echo '<form action="?do=add" method="POST"><div class="row text_box"> Название:<br/><br/>';
quickpaste('text');
quickpanel();
echo'</br></br><input type="text" class="form-control" name="name"/><br/>Содержание:<br/><textarea class="form-control" rows="3" name="text"></textarea><br/><input type="submit" name="add" class="btn btn-primary" value="Отправить"/></div></form>';
break;
case 'view':
$id = isset($_GET['id']) ? abs((int)$_GET['id']) : false;
$array = DB::$dbs->query("SELECT * FROM adm_topic WHERE id = ? LIMIT 1", [$id]);

if ($array -> rowCount() == 0) {
header('location: /');
die();
}
$arr = $array -> fetch();
echo '<div class="catSides"><a href="/panel"><i class="md-format-list-bulleted"></i> Админка</a> - <a href="fort.html">Админ форум</a> - '.$arr['name'].'</div>';
echo '<div class="row text_box"><i class="md-shuffle"></i>  <a href=javascript:document.location.reload()>Обновить</a> |'.($b['level'] > 2 ? ($arr['type'] == 1 ? '<a href="?do=view&id='.$id.'&closed"> Открыть</a>':'<a href="?do=view&id='.$id.'&closed"> Закрыть</a>').'':NULL).' '.($b['level'] > 4 ? '| <a href="?do=view&id='.$id.'">Удалить тему</a>':NULL).'</div>';

$mess = DB::$dbs->querySingle("SELECT COUNT(id) FROM adm_mess WHERE tid = ?", array($id));
if ($mess > 10) {
$pg = ceil($mess / 10);
$st = '&page='.$pg;
} else {
$st = '';
}
if (isset($_GET['delp'])) {

if ($b['level'] < 3) {
header('location: ?');
die();
}
DB::$dbs->query("DELETE FROM adm_mess WHERE id = ?", [abs((int)$_GET['delp'])]);
header('location: ?do=view&id='.$id.$st);
die();
}
if (isset($_GET['del'])) {
if ($b['level'] < 3) {
header('location: ?');
die();
}
DB::$dbs->query("DELETE FROM adm_mess WHERE tid = ?", [$id]);
DB::$dbs->query("DELETE FROM adm_topic WHERE id = ?", [$id]);
header('location: ?');
die();
}
if (isset($_GET['closed'])) {
if ($b['level'] < 3) {
header('location: ?do=view&id='.$id.$st);
die();
}
if ($arr['type'] != 1) {
DB::$dbs->query("UPDATE adm_topic SET type = ? WHERE id = ? LIMIT 1", [1,$id]);
header('location: ?do=view&id='.$id.$st);
die();
} else {
DB::$dbs->query("UPDATE adm_topic SET type = ? WHERE id = ? LIMIT 1", [0,$id]);
header('location: ?do=view&id='.$id.$st);
die();
}
}
if ($arr['type'] != 1) {
if (isset($_GET['otv'])) {
$post = DB::$dbs->queryFetch("SELECT user_id,id FROM adm_mess WHERE id = ? LIMIT 1", [abs((int)$_GET['otv'])]);
$user = DB::$dbs->queryFetch("SELECT nick,id FROM blogger WHERE id = ? LIMIT 1", [$post['user_id']]);

if (empty($user['id']) OR empty($post['id'])) {
header('location: ?do=view&id='.$id.$st);
die();
}
$reply = $user['nick'].', ';
} else {
$reply = '';
}

if (isset($_POST['add'])) {
$err = [];
$form = ['text' => isset($_POST['text']) ? check($_POST['text']) : null];

if (empty($form['text'])) {
$err[] = 'Заполните сообщение!';
}
if (DB::$dbs->querySingle("SELECT COUNT(id) FROM adm_mess WHERE text = ?", [$form['text']]) > 0) {
$err[] = 'Такое сообщение уже есть!';
}
if (empty($err)) {
DB::$dbs->query("INSERT INTO adm_mess SET text = ?, user_id = ?, time = ?, tid = ?", [$form['text'],$b['id'],time(),$id]);
DB::$dbs->query("UPDATE adm_topic SET last = ? WHERE id = ? LIMIT 1", [time(),$id]);   
                                        
header('location: ?do=view&id='.$id.'&sort='.$sorts.'&'.$st);
die();
} else {
echo '<div class="error">';
foreach($err as $error) {
echo '<b>'.$error.'</b><br/>';
}
echo '</div>';
}
}
echo '<form name="form" method="post" action="?do=view&id='.$id.'" method="POST"><div class="row text_box"> Сообщение:<br/><br/>';
quickpaste('text');
quickpanel();
echo'</br></br><textarea class="form-control" rows="3" name="text">'.$reply.'</textarea><br/><input type="submit" class="btn btn-primary" name="add" value="Написать"/></div></form>';
}
else err('Эта тема закрыта, вы не можете писать ответы и редактировать сообщения.');
$k_mess = DB::$dbs->querySingle("SELECT COUNT(id) FROM adm_mess WHERE tid = ?", [$id]);
$num = 10;
$k_page = k_page($k_mess, $num);
$page = page($k_page);
$start = $num*$page-$num;
$sql = DB::$dbs->query("SELECT * FROM adm_mess WHERE tid = ? ORDER BY time ASC LIMIT $start,$num", [$id]);
if ($sql -> rowCount() == 0) {
err('Сообщений ещё нет!');
} else {
while($a = $sql->fetch()) {
$us = DB::$dbs->queryFetch("SELECT last,id FROM blogger WHERE id = ? LIMIT 1", [$a['user_id']]);
echo '<div class="row text_box"><div class="pull-right text-muted top_right_box"></div>'.($b['level'] > 4 ? '[<a href="?do=view&id='.$id.'sort='.$sorts.'&delp='.$a['id'].'">Удл</a>] ':NULL) .Nick($a['user_id']).'  ('.vr($a['time']).') '. (($arr['type'] != 1 && $a['user_id'] != $b['id']) ? ' <a href="?do=view&id='.$id.'&sort='.$sorts.'&otv='.$a['id'].'">[Отв]</a><br/>':'<br/>') . text($a['text']).'</div>';
}
}
if ($k_page>1) {
str('?do=view&id='.$id.'&sort='.$sort.'&', $k_page,$page);
}
break;
}

///Подключаем меню
$title->GetMenu();


///Подключаем футер
$title->GetFooter();
?>