<?php

/* DCMS Special
 * Дата последнего редактирования 25.09.2016
 * Модифицировал densnet
 * Автор yadalay
 */

$forum = mysql_fetch_object(mysql_query('SELECT * FROM `forum` WHERE `id` = ' . intval($_GET['edit_forum'])));

if (access('forum_for_edit')) {
    if (isset($_POST['edit'])) {
        $name = mysql_real_escape_string(trim($_POST['name']));
        $description = mysql_real_escape_string(trim($_POST['description']));
        $number = intval($_POST['number']);
        $access = intval($_POST['access']);
        $output = (isset($_POST['output'])) ? 1 : 0;
        $icon = esc(stripcslashes(htmlspecialchars($_POST['icon'])));
        $isset_name = mysql_result(mysql_query('SELECT COUNT(*) FROM `forum` WHERE `name` = "' . $name . '" AND `id` != ' . $forum->id), 0);
        $forum_n = ($forum->number != $number) ? mysql_fetch_object(mysql_query('SELECT `id`, `number` FROM `forum` WHERE `number` = ' . $number . ' AND `id` != ' . $forum->id)) : NULL;

        if ($forum_n) {
            mysql_query('UPDATE `forum` SET `number` = ' . $number . ' WHERE `id` = ' . $forum->id);
            mysql_query('UPDATE `forum` SET `number` = ' . $forum->number . ' WHERE `id` = ' . $forum_n->id);
        }

        if (mb_strlen($name) < 3 || mb_strlen($name) > 40) {
            $_SESSION['err'] = lang('В поле Название подфорума можно использовать от 3 до 40 символов');
        } elseif ($isset_name != 0) {
            $_SESSION['err'] = lang('Подфорум с таким названием существует');
        } elseif ($number < 0 || $number == NULL || $number == 0) {
            $_SESSION['err'] = lang('Введите уровень');
        } elseif (mb_strlen($description) > 100) {
            $_SESSION['err'] = lang('Слишком длинное описание подфорума');
        } elseif ($isset_number != 0) {
            $_SESSION['err'] = lang('Данный уровень уже использует другой подфорум');
        } else {
            if ($forum->name != $name) {
                admin_log(lang('Форум'), lang('Подфорумы'), lang('Подфорум') . ' "' . $forum->name . '" ' . lang('переименован в') . ' "' . $name . '".');
            } else {
                admin_log(lang('Форум'), lang('Подфорумы'), lang('Подфорум') . ' "' . $forum->name . '" ' . lang('был изменён') . '.');
            }

            mysql_query("UPDATE forum SET name = '$name', description = '$description', number = '$number', access = '$access', icon = '$icon', output = '$output' WHERE id = '$forum->id'");

            $_SESSION['message'] = lang('Изменения сохранены');

            header('Location: ' . DIR_FORUM);
            exit;
        }
    } elseif (isset($_POST['delete']) && access('forum_for_delete')) {
        #Навигация
        echo "<div class='list-group-item-null list-group-item-grey'><small>";
        echo "<a href='/' class='hint--right' data-hint='" . lang('На главную') . "'><i class='fa fa-home fa-lg'></i></a> <i class='fa fa-angle-right fa-fw'></i> ";
        echo "<a href='" . DIR_FORUM . "'>" . lang('Форум') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
        echo "<a href='" . DIR_FORUM . "$forum->id/'>" . toOutput($forum->name, 1, 1, 0, 0, 0) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
        echo lang('Удаление');
        echo "</small></div><br />";

        #Форма удаления подфорума
        echo "<form action='" . DIR_FORUM . "?edit_forum=$forum->id' method='post' class='list-group-item-null'>";
        echo lang('Вы уверены, что хотите удалить этот подфорум со всем его содержимым') . "?<br />";

        $doc->Button('btn btn-success btn-sm', 'del', 'trash-o', 'Удалить');
        $doc->Button('btn btn-secondary btn-sm', 'cancel', null, 'Отменить');

        echo "</form>";

        require_once H . 'sys/inc/tfoot.php';
    } elseif (isset($_POST['del']) && access('forum_for_delete')) {
        #Удаляем подфорум
        admin_log('Форум', 'Подфорумы', 'Подфорум "' . $forum->name . '" был удалён.');

        $themes = mysql_query('SELECT `id` FROM `forum_themes` WHERE `id_forum` = ' . $forum->id);

        while ($theme = mysql_fetch_object($themes)) {
            $files = mysql_query('SELECT `name` FROM `forum_post_files` WHERE `id_theme` = ' . $theme->id);
            #Удаляем файлы
            while ($file = mysql_fetch_object($files)) {
                unlink(DIR_FORUM_FILES . $file->name);
            }

            mysql_query('DELETE FROM `forum_post_rating` WHERE `id_theme` = ' . $theme->id);
            mysql_query('DELETE FROM `forum_posts` WHERE `id_theme` = ' . $theme->id);
            mysql_query('DELETE FROM `forum_post_files` WHERE `id_theme` = ' . $theme->id);
            mysql_query('DELETE FROM `forum_votes_var` WHERE `id_theme` = ' . $theme->id);
            #Удаляем опросы, если были
            $votes = mysql_query('SELECT `id` FROM `forum_votes` WHERE `id_theme` = ' . $theme->id);

            while ($vote = mysql_fetch_object($votes)) {
                mysql_query('DELETE FROM `forum_vote_voices` WHERE `id_vote` = ' . $vote->id);
            }
            mysql_query('DELETE FROM `forum_votes` WHERE `id_theme` = ' . $theme->id);
        }

        mysql_query('DELETE FROM `forum_themes` WHERE `id_forum` = ' . $forum->id);
        mysql_query('DELETE FROM `forum_razdels` WHERE `id_forum` = ' . $forum->id);

        $n_forums = mysql_query('SELECT `id`, `number` FROM `forum` WHERE `number` > ' . $forum->number);

        while ($n_forum = mysql_fetch_object($n_forums)) {
            mysql_query('UPDATE `forum` SET `number` = ' . ($n_forum->number - 1) . ' WHERE `id` = ' . $n_forum->id);
        }

        mysql_query('DELETE FROM `forum` WHERE `id` = ' . $forum->id);

        $_SESSION['message'] = lang('Подфорум успешно удалён');

        header('Location: ' . DIR_FORUM);
        exit;
    } elseif (isset($_GET['cancel'])) {
        header('Location: ' . DIR_FORUM);
        exit;
    }

    #Навигация
    echo "<div class='list-group-item-null list-group-item-grey'><small>";
    echo "<a href='/' class='hint--right' data-hint='" . lang('На главную') . "'><i class='fa fa-home fa-lg'></i></a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='" . DIR_FORUM . "'>" . lang('Форум') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "<a href='" . DIR_FORUM . "$forum->id/'>" . toOutput($forum->name, 1, 1, 0, 0, 0) . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo lang('Редактирование');
    echo "</small></div><br />";

    #Форма редактирования подфорума
    echo "<form action='" . DIR_FORUM . "?edit_forum=$forum->id' method='post' class='list-group-item-null'>";
    $doc->Input('name', 'Название подфорума', null, "$forum->name");
    $doc->Textarea('description', 'Описание подфорума', null, "$forum->description");
    $doc->Input('icon', 'Иконка', null, "$forum->icon");
    $doc->Input('number', 'Позиция', null, "$forum->number");

    echo lang('Доступ') . ":<br />";
    echo "<label class='custom-control custom-radio'><input id='access0' name='access' type='radio' value='0' " . (($forum->access == 0) ? " checked='checked'" : NULL) . " class='custom-control-input'><span class='custom-control-indicator'></span> <span class='custom-control-description'>" . lang('Все') . "</span></label><br />";
    echo "<label class='custom-control custom-radio'><input id='access1' name='access' type='radio' value='1' " . (($forum->access == 1) ? " checked='checked'" : NULL) . " class='custom-control-input'><span class='custom-control-indicator'></span> <span class='custom-control-description'>" . lang('Только администраторы') . "</span></label><br />";
    echo "<label class='custom-control custom-radio'><input id='access2' name='access' type='radio' value='2' " . (($forum->access == 2) ? " checked='checked'" : NULL) . " class='custom-control-input'><span class='custom-control-indicator'></span> <span class='custom-control-description'>" . lang('Администраторы + модераторы') . "</span></label>";

    echo "<hr>";

    $doc->Checkbox('output', 'Список разделов', 1, "" . (($forum->output == 1) ? 'checked="checked"' : NULL) . "");

    echo "<hr>";

    $doc->Button('btn btn-success btn-sm', 'edit', 'save', 'Сохранить');

    if (access('forum_for_delete')) {
        $doc->Button('btn btn-danger btn-sm', 'delete', 'trash-o', 'Удалить');
    } else {
        $doc->Button('btn btn-secondary btn-sm', 'cancel', null, 'Отменить');
    }

    echo "</form>";

    require_once H . 'sys/inc/tfoot.php';
} elseif (!access('forum_for_edit') || !$forum) {
    header('Location: ' . DIR_FORUM);
}
exit;
