<?php

include '../system/sys.php';
include '../system/funcs.php';

if (!isset ($us)) {
        header ('location: /');
        exit;
}

if ($us['level']<3) {
        header ('location:/');
        exit;
}

H ('Новости', 'Новости');

if (isset ($_GET['add'])) {
        echo '<form action="/adm/news.php?add&ok" method="post">';
        echo '<div class="list1">';
        echo 'Текст:<br/><textarea name="text"></textarea><br/>';
        echo '</div>';
        echo '<div class="lst"><input type="submit" value="Добавить"></div>';
        echo '</form>';
        if (isset ($_GET['ok'])) {
                $_POST['text'] = htmlspecialchars (addslashes ( trim ($_POST['text'])));
                if (empty ($_POST['text'])) {
                        echo '<div class="list1"><b>Вы не ввели текст новости..</b></div>';
                }
                else {
                        DB :: $dbs -> query ("INSERT INTO `news` (`text`,`us`, `t`) VALUES (?, '" . $us['id'] . "', '" . time () . "')", array ($_POST['text']));
                        echo '<div class="list1">Новость добавлена!</div>';
                        header ("refresh: 1; url=/adm/news.php");
                }
        }
        
}
else {
        echo '<div class="menu2"><a href="/adm/news.php?add" style="color:white;">Добавить</a></div>';
        
}

if (isset ($_GET['del'])) {
        $query = DB :: $dbs -> query ("SELECT * FROM `news` WHERE (`id`=?)", array (intval ($_GET['del'])));
        if ($query -> rowCount () == 0) {
                header ('location: /adm/news.php');
                exit;
        }
        $news = $query -> fetch ();
        $u = DB :: $dbs -> queryFetch  ("SELECT * FROM `us` WHERE (`id`='" . $news['us'] . "')");
        if ($u['id']!=$us['id'] && $u['level']>=$us['level']) {
                header ('location: /adm/news.php');
                exit;
        }
        
        DB :: $dbs -> query ("DELETE FROM `news` WHERE (`id`='" . $news['id'] . "')");
        header ('location: /adm/news.php');

}

if (DB :: $dbs -> querySingle ("SELECT COUNT(*) FROM `news`") != 0) {

        $query = DB :: $dbs -> query ("SELECT * FROM `news`");
        while ($news = $query -> fetch ()) {

                $u = DB :: $dbs -> queryFetch  ("SELECT * FROM `us` WHERE (`id`='" . $news['us'] . "')");
                echo '<div class="list1">';
                echo (mb_strlen ($news['text']) > 150 ? mb_substr (bb ($news['text']), 0, 1500) . '..' : bb ($news['text']));
                
                
                if ($u['id']==$us['id'] || $u['level']<$us['level']) {
                        echo ' [<a href="/adm/news.php?del=' . $news['id'] . '">Удалить</a>]';
                }

                echo '</div>';


        }

}
else {
        echo 'Новостей пока нет..';
}

F ();

?>