<?php
define('_CONSTANT_', 1);
require_once '../../core/start.php';

/*
 * * * * * * * * * * * * *
 * Connect logic files;  *
 * * * * * * * * * * * * *
 */
require_once '../../logic/chatLogic.php'; // Chat ban and other;
$chatLogic = new ChatLogic(); 

checkAuth();
head('Чат', 'Чат');

# User lvl check;
if ($user['lvl'] < 2) 
{
    error('Чат доступен с 2 уровня', '/game/');
}

if (isset($_POST['try'])) 
{
    $data = $_POST;
    $data['text'] = $Filter->clearString($data['text']); 
    
    if (empty($data['text'])) 
    {
        error('Пустое сообщение.','/');
    } 
    elseif (strlen($data['text']) < 1 || strlen($data['text']) > $settings['chat_max']) 
    {
        error('Длина сообщения должна быть в пределе [1-'.$Filter->clearInt($settings['chat_max']).']', '/');
    } 
    else 
    { 
        if (!empty($_GET['otv']) && $_GET['otv'] != $user['id']) 
        {
            $_GET['otv'] = $Filter->clearInt($_GET['otv']);
            $ank = DB::$dbs->queryFetch("SELECT `id`, `login` FROM ".USERS." WHERE `id` = ? ",[$_GET['otv']]); 
            if (!empty($ank)) 
            {
                $data['text'] = '' . $Filter->output($ank['login']) . ', ' . $data['text'];
            }
        } 
        $idKont = (!empty($ank) ? $ank['id'] : 0);
        DB::$dbs->query("INSERT INTO ".CHAT." (`id_user`, `id_kont`, `time`, `text`) VALUES (?, ?, ?, ?)", [$user['id'], $idKont, time(), $data['text']]);
        $journal = 'Вам написали в <a href="' . HOME . '/modules/chat/index.php">чате</a>.';
		$User->addUserJournal($journal, $ank['id']);
        success('Сообщение отправлено.', '/modules/chat/', 'Вернуться в чат');
    }
} 
if (isset($_POST['postDelete']) && $user['access'] == 2) 
{
    $data = $_POST; 
    $data['postDelete'] = $Filter->clearInt($data['postDelete']); 
    print_r($data);
    foreach ($data as $name => $value) 
    {
        DB::$dbs->query("DELETE FROM ".CHAT." WHERE `id` = ?", [$name]);
        $User->addLog($user['id'], 'Удалил сообщение в чате'); 
    } 
    success('Удалено.', '/modules/chat/', 'В чат');
} 
if (isset($_POST['clean']) && $user['access'] == 2) 
{ 
    $data = $_POST; 
    $data['clean'] = $Filter->clearInt($data['clean']); 
    DB::$dbs->query("DELETE FROM ".CHAT."");
    DB::$dbs->query("INSERT INTO ".CHAT." (`id_user`, `id_kont`, `time`, `text`) VALUES (?, ?, ?, ?)", [$user['id'], 0, time(), 'Чат очищен.']);
    $User->addLog($user['id'], 'Очистил чат');
    success('Очищено.', '/modules/chat/', 'В чат');
} 
if (isset($_POST['postUpdate']) && $user['access'] == 2) 
{
    $data = $_POST; 
    $data['postUpdate'] = $Filter->clearInt($data['postUpdate']); 
    foreach ($data as $name => $value) 
    {
        DB::$dbs->query("UPDATE ".CHAT." SET `text` = ? WHERE `id` = ?", [NULL, $name]);
        $User->addLog($user['id'], 'Удалил текст сообщения в чате');
    } 
    success('Текст удален.', '/modules/chat/', 'В чат');
}
?>
<table style="width:100%" cellspacing="0" cellpadding="0"><tr>
<td style="vertical-align:top;width:50%;white-space: nowrap;">
<a href="<?=HOME?>/modules/chat/" class="link-touch"> Обновить</a> 
</td>
<td style="vertical-align:top;width:50%;white-space: nowrap;"> 
<a href="<?=HOME?>/modules/other/smiles.php" class="link-touch"> Смайлы</a> 
</td></tr>
</table>
 <?php
if (!empty($_GET['otv']) && $_GET['otv'] != $user['id']) 
{
    $_GET['otv'] = $Filter->clearInt($_GET['otv']);
    $ank = DB::$dbs->queryFetch("SELECT `id`, `login` FROM ".USERS." WHERE `id` = ? ",[$_GET['otv']]);
    if (!empty($ank)) 
    {
        if ($user['ajax'] == 1) 
        {
            ?> 
            <div class="nameanswer"></div>
            <form action="?otv=<?=$Filter->clearInt($ank['id'])?>" method="POST"> 
            Сообщение пользователю <b><?=$Filter->output($ank['login'])?></b><br/> 
            <?php
        } 
        else 
        {
            ?> 
            <form action="?otv=<?=$Filter->clearInt($ank['id'])?>" method="POST"> 
            Сообщение пользователю <b><?=$Filter->output($ank['login'])?></b><br/>
            <?php
        }
    } 
} 
$_GET['otv'] = (!empty($_GET['otv']) ? $_GET['otv'] : null);
    ?> 
    <?php if($user['ajax'] == 0) : ?>
            <?=(!empty($_GET['otv'] && $_GET['otv'] != $user['id']) ? null : '<form action="" method="POST">')?>
            <textarea class="text" name="text" placeholder="Введите сообщение..."></textarea><br/>
            <input style="display:block;color: white" type="submit" name="try" value="Отправить">
        </form> 
    <?php else : ?>
        <p class="ajaxAnswer"></p>
        <textarea class="text" name="text" placeholder="Введите сообщение..."></textarea><br/>
        <input class="submit" style="display:block;color: white" type="submit" value="Отправить">
    <?php endif ?>
         <?php
?> 
    <div class="userMessage"></div>
   <?php 
   /* IF USER USED LITE DESIGN */
    if($user['ajax'] == 0) {
        $all = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM ".CHAT.""); 
    
        if (empty($all)) { 
            ?> 
            <div class="content">
                Сообщений нет...
            </div>
            <?php
        } 

        $n = new Navigator($all,10,'');
        $sql = DB::$dbs->query("SELECT * FROM ".CHAT." ORDER BY `id` DESC LIMIT {$n->start()}, 10");

        while ($post = $sql ->fetch()) 
        { 
            echo '<div class="wrap">';
            #$chatLogic->chatBan($post['text'], $post['id']);
            $ank = DB::$dbs->queryFetch("SELECT `id`, `login` FROM ".USERS." WHERE `id` = ?",array($post['id_user'])); 
            if ($user['access'] == 2) {
                ?> 
                    <input type="checkbox" name="<?=$Filter->clearInt($post['id'])?>"> 
                <?php
            } 
            if ($post['id_user'] != $user['id']) { 
                ?> 
                    <?=userLink($Filter->clearInt($post['id_user']))?>
                    <font color="#909090">[<?=dataTime($Filter->clearInt($post['time']))?>]</font>
                    <a href="?otv=<?=$post['id_user']?>">[отв]</a>
                    <br/> 
                    <?=outputText($post['text'], $post['id_user'])?>
                </div>
                <?php
            } else {
                ?> 
                    <?=userLink($Filter->clearInt($post['id_user']))?><font color="#909090">[<?=dataTime($Filter->clearInt($post['time']))?>]</font><br/> 
                    <?=outputText($post['text'], $post['id_user'])?>
                </div>
                <?php
            }
        }
        echo $n->navi(); 
    }
        /*  ADMIN MENU  */
        if ($user['access'] == 2) 
        {
            ?> 
        <form action="#" method="POST">
            <!--input style='color:white;' type="submit" name="postDelete" value="Удалить выделенные посты"-->
            <!--input style='color:white;' type="submit" name="postUpdate" value="Удалить текст выделенных постов"-->
            <input style='color:white;' type="submit" name="clean" value="Очистить чат">
        </form>
    <?php
        } 
        ?> 
        <a href="<?=HOME?>/modules/other/administration.php" class="link-touch"><?=ico('panel.png')?> Администрация</a>
        <div style="text-align: center;">
            В чате <?=$Count->chatCountUsers()?>
        </div>
    <?php if($user['ajax'] == 1) : ?>
        <script type="text/javascript" src='message.js'></script>
    <?php endif ?>
    <?php
    require_once '../../core/foot.php';
    ?>
