<?php
require_once('system/func.php');
auth(); // Закроем от не авторизованных
## Топик ##
$topic_id = isset($_GET['topic']) ? intval($_GET['topic']) : null;

if (!empty($topic_id)) {
    $topic = mysql_fetch_assoc(mysql_query("SELECT * FROM `topic` WHERE `id` = '" . $topic_id . "'"));
    # Ошибки #
    if (!$topic) {
        $_SESSION['msg'] = 'Такой топик не существует';
        header('Location: /forum/');
        exit();
    }
    if (isset($_GET['delete_post']) and $user['access'] > 0) {
        mysql_query("DELETE FROM `topic_msg` WHERE `id` = '" . $_GET['delete_post'] . "'");
        $_SESSION['msg'] = 'Пост удален';
        header('Location: ?');
        exit();
    }
    if (isset($_GET['delete']) and $user['access'] > 0) {
        $title = 'Удалить топ?';
        require_once('system/header.php');
        echo "<div class='block2'>";
        echo "<li><a href='?delete_ok'>Да, удалить</a></li>";
        echo "<li><a href='?'>Нет, отмена</a></li>";
        echo "</div>";
        require_once('system/footer.php');
        exit();
    }
    if (isset($_GET['delete_ok']) and $user['access'] > 0) {
        mysql_query("DELETE FROM `topic` WHERE `id` = '" . $topic[id] . "'");
        $_SESSION['msg'] = 'Топик удален';
        header("Location: /64564564654564/$topic[id_forum]");
        exit();
    }
    if (isset($_GET['close']) and $user['access'] > 0) {
        mysql_query("UPDATE `topic` SET `close` = '1' WHERE `id` = '$topic[id]'");
        $_SESSION['msg'] = "Топик успешно закрыт";
        header("Location: ?");
        exit();
    }
    if (isset($_GET['no_close']) and $user['access'] > 0) {
        mysql_query("UPDATE `topic` SET `close` = '0' WHERE `id` = '$topic[id]'");
        $_SESSION['msg'] = "Топик успешно открыт";
        header("Location: ?");
        exit();
    }
    if (isset($_GET['top']) and $user['access'] > 0) {
        mysql_query("UPDATE `topic` SET `top` = '1' WHERE `id` = '$topic[id]'");
        $_SESSION['msg'] = "Топик успешно закреплен";
        header("Location: ?");
        exit();
    }
    if (isset($_GET['no_top']) and $user['access'] > 0) {
        mysql_query("UPDATE `topic` SET `top` = '0' WHERE `id` = '$topic[id]'");
        $_SESSION['msg'] = "Топик успешно откреплен";
        header("Location: ?");
        exit();
    }
    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) > 5000) {
                $err = 'Длина сообщения должна быть в пределах 3 - 5000 символов';
           // }
            //if ($ban) {
              //  $err = "На вас наложен бан, осталось " . tl($ban[last] - time());
            }
            if (!isset($err)) {
                mysql_query("INSERT INTO `topic_msg` SET `id_topic` = '$topic[id]', `id_user` = '" . $myID . "', `text` = '" . mysql_real_escape_string($text) . "' , `time` = '" . time() . "'");
                mysql_query("UPDATE `topic` SET `onlick` = '" . time() . "' WHERE `id` = '$topic[id]'");
                $_SESSION['msg'] = 'Комментарий успешно добавлен';
                header('Location: ?');
                exit();
            } else {
                $_SESSION['msg'] = $err;
                header('Location: ?page=end');
                exit();
            }
        } else {
            $_SESSION['msg'] = 'Ведите текст';
            header('Location: ?page=end');
            exit();
        }
    }
    if (isset($_GET['sett_topic_post'])) {
        if (isset($_POST['text']) && isset($_POST['name'])) {
            $text = text($_POST['text']);
            $name = text($_POST['name']);
            if (strlen($text) < 3 or strlen($text) > 5000) {
                $err = 'Длина сообщения должна быть в пределах 3 - 5000 символов';
            }
            if (strlen($name) < 3 or strlen($name) > 40) {
                $err = 'Длина названия должна быть в пределах 3 - 40 символов';
            }
            if (!isset($err)) {
                mysql_query("UPDATE `topic` SET `text` = '" . mysql_real_escape_string($text) . "', `name` = '$name' WHERE `id` = '$topic[id]'");
                $_SESSION['msg'] = 'Топик успешно изменен';
                header('Location: ?');
                exit();
            } else {
                $_SESSION['msg'] = $err;
                header('Location: ?');
                exit();
            }
        } else {
            $_SESSION['msg'] = 'Заполните поля';
            header('Location: ?');
            exit();
        }
    }
    $title = 'Форум - ' . $topic['name'];
    require_once('system/header.php');
    if ($user['access'] > 0 or $myID == $topic['id_user']) {
        if (isset($_GET['sett_topic'])) {
            echo "<div class='block center'>";
            echo '<form name="text" method="post" action="?sett_topic_post">';
            echo "<input type='text' name='name' placeholder='Введите название...' value='$topic[name]'><br>";
            echo '<textarea name="text" placeholder="Введите сообщение..." maxlength="5000">' . $topic['text'] . '</textarea><br>';
            echo '<input class="btn" type="submit" value="Изменить"><a href="?">Отмена</a>';
            echo "</form>";
            echo "</div>";
            require_once('system/footer.php');
            exit();
        }
    }
    $ank = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = $topic[id_user] LIMIT 1"));
    echo ' <div class="header">  <font color="grey">  <a href="/profile/' . $ank[id] . '"> <font color="white"> ' . $ank['login'] . '</font></a>, ' . tl(time() - $topic[time]) . '</div><div class="wrapper white"> ' . text_msg($topic['text']) . '';
    echo "</div></div>";
    if ($user['access'] > 0 or $myID == $topic['id_user']) {
        echo "<div class='wrapper blue'>";
        echo "<li><a href='?sett_topic'>" . ico('icons', 'ok.png') . "Редактировать</a></li>";
        if ($topic['close'] == 0 and $user['access'] > 0) {
            echo "<li><a href='?close'>" . ico('icons', 'ok.png') . "Закрыть</a></li>";
        }
        if ($topic['close'] == 1 and $user['access'] > 0) {
            echo "<li><a href='?no_close'>" . ico('icons', 'ok.png') . "Открыть</a></li>";
        }
        if ($topic['top'] == 0 and $user['access'] > 0) {
            echo "<li><a href='?top'>" . ico('icons', 'ok.png') . "Прикрепить</a></li>";
        }
        if ($topic['top'] == 1 and $user['access'] > 0) {
            echo "<li><a href='?no_top'>" . ico('icons', 'ok.png') . "Открепить</a></li>";
        }
        if ($user['access'] > 0) {
            echo "<li><a href='?delete'>" . ico('icons', 'ok.png') . "Удалить топ</a></li>";
        }
        echo "</div>";
    }
    $set['p_str'] = 10;
    $k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `topic_msg` WHERE `id_topic` = '$topic[id]'"), 0);
    echo "<b><div class='header'>Комментарии [$k_post]</b></div>";
    $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 `topic_msg` WHERE `id_topic` = '$topic[id]' ORDER BY `id` ASC LIMIT $start, $set[p_str]");
    while ($post = mysql_fetch_assoc($q)) {
        echo div('wrapper white');
        $ank = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = $post[id_user] LIMIT 1"));
        echo ' <font color="grey">  <a href="/profile/' . $ank[id] . '"> <font color="white"> ' . $ank['login'] . '</font></a>, ' . tl(time() - $post['time']) . ' ';


        if ($ank['id'] != $myID and $topic['close'] == 0) {
            echo "<a href='?to=$ank[id]&page=end'> " . ico('icons', 'rarrow.png') . "</a>";
        }
        echo "<br>" . text_msg($post['text']);
        if ($user['access'] > 0) {
            echo " <a href='?delete_post=$post[id]'><font color='red'>[×]</font></a>";
        }
        echo "</div>";


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

    echo "<div class='header'>";
    if ($topic['close'] == 0) {
        if (isset($_GET['to'])) {
            $opponent = mysql_fetch_assoc(mysql_query("SELECT * FROM `users` WHERE `id` = $_GET[to] LIMIT 1"));
            echo '<form name="text" method="post" action="?text">';
            echo '<textarea name="text" maxlength="5000">' . $opponent['login'] . ', </textarea><br>';
            echo '<input class="btn_grey" type="submit" value="Ответить">';
            echo "</form>";
        } else {
            echo '<form name="text" method="post" action="?text">';
            echo '<textarea name="text" placeholder="Введите сообщение..." maxlength="5000"></textarea><br>';
            echo '<input class="btn_grey" type="submit" value="Отправить">';
            echo "</form>";
        }
    } else {
        echo "<font color='red'>Топик закрыт</font>";
    }

    echo "</div>";
    $forum = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum` WHERE `id` = '" . $topic['id_forum'] . "'"));
    echo "<div class='header'> <img src='/images/icons/topic.png' width ='28px'>  <a href='/forum/$forum[id]'>$forum[name]</a> | $topic[name]</div>";

} else {
    ## Раздел ##
    $id = abs(intval($_GET['id']));
    if ($id) {
        $forum = mysql_fetch_assoc(mysql_query("SELECT * FROM `forum` WHERE `id` = '" . $id . "'"));
        # Ошибки #
        if (!$forum) {
            $_SESSION['msg'] = 'Такой раздел не существует';
            header('Location: /forum/');
            exit();
        }
        if (isset($_GET['new_topic_post'])) {
            if (isset($_POST['name']) && isset($_POST['text'])) {
                $name = text($_POST['name']);
                $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($name) < 3 or strlen($name) > 40) {
                    $err = 'Длина названия должна быть в пределах 3 - 40 символов';
                }
                if (strlen($text) < 3 or strlen($text) > 5000) {
                    $err = 'Длина сообщения должна быть в пределах 3 - 5000 символов';
                }
                if (isset($ban)) {
                    $err = "На вас наложен бан, осталось " . tl($ban['last'] - time());
                }
                if (!isset($err)) {
                    if ($forum['id'] == 1) {
                        mysql_query("UPDATE users SET news_read = '1'");
                    }
                    mysql_query("INSERT INTO `topic` SET `id_forum` = '$forum[id]', `id_user` = '" . $myID . "', `name` = '" . mysql_real_escape_string($name) . "', `text` = '$text', `time` = '" . time() . "', `onlick` = '" . time() . "'");
                    exit();
                } else {
                    $_SESSION['msg'] = $err;
                    header('Location: ?new_topic');
                    exit();
                }
            } else {
                $_SESSION['msg'] = 'Заполните поля';
                header('Location: ?new_topic');
                exit();
            }
        }
        $title = 'Форум - ' . $forum['name'];
        require_once('system/header.php');
        if (isset($_GET['create_top']) and $user['access'] >= $forum['access']) {
            echo "<div class='header'>";
            echo '<form name="text" method="post" action="?new_topic_post">';
            echo "<input type='text'   class='input text w97' id ='msg' name='name' placeholder='Название'><br>";
            echo '<textarea name="text" class="input text w97 " id="msg" placeholder="Введите сообщение..." maxlength="5000"></textarea><br>';
            echo '<input class="btn_grey" type="submit" value="Создать"> <div class="btn_grey"><span class="cb_end"><span class="cb_ttl"><a href="?">Отмена</span></span></div></a>';
            echo "</form>";
            echo "</div>";
            require_once('system/footer.php');
            exit();
        }
        $set['p_str'] = 10;
        $k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `topic` WHERE `id_forum` = '$forum[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 `topic` WHERE `id_forum` = '$forum[id]' ORDER BY `top` DESC, `onlick` DESC LIMIT $start, $set[p_str]");

        if ($k_post == 0) {
            echo div('main_link') . " В данном разделе нет топиков</div>";
        }
        while ($post = mysql_fetch_assoc($q)) {
            echo "<div class='wrapper '>";
            echo "<li><a href='/64564564654564/sub/$post[id]?page=end'> <img src='/images/icons/topic.png' width ='28px'>" ;
            if ($post['close'] == 1 and $post['top'] == 1) {
                echo "<b> $post[name]</b>";
            } elseif ($post['close'] == 1) {
                echo "<font color='grey'> $post[name]</font><font color='white'>(Закрыт)</font>";
            } elseif ($post['top'] == 1) {
                echo "<b><font color='grey'>$post[name]</font></b>";
            } else {
                echo $post['name'];
            }
            echo "</a></div>";
        }
        echo "</div></div>";
        if ($user['access'] >= $forum['access']) {
            echo div('header') . " <div class='btn_grey'><span class='cb_end'><span class='cb_ttl'><a  href='?create_top'>Создать  топик</span></span></div></a></div>";
        }
        if ($k_post > 10) {
            echo "<div class='header'>";
            str('?', $k_page, $page); // Вывод страниц
            echo "</div>";
        }

        echo "<a href='/64564564654564/'>class='llb'><div class='ssilki_dop p_0'><img src='/images/icons/back.png' width ='28px'> Вернуться назад</div></div></a>";
    } else {
        ## Форум ##
        $title = 'Форум';
        require_once('system/header.php');
        $k_post = mysql_result(mysql_query("SELECT COUNT(*) FROM `forum`"), 0);
        $q = mysql_query("SELECT * FROM `forum` ORDER BY `id` ASC");
        if ($k_post == 0) {
            echo "<div class='header'>Нет разделов...</div>";
        }

        while ($post = mysql_fetch_assoc($q)) {
            echo div('wrapper mt2 center');
            echo "<a href='/64564564654564/$post[id]'><img src='/images/icons/topic.png' width ='28px'> $post[name]</a><br></div>";
        }
    }
}
require_once('system/footer.php');
?>