<?php
define('_CONSTANT_', 1);
require_once '../../core/start.php';
checkAuth();
head('Почта', 'Почта');
?>

<script type="text/javascript" src="mess.js"></script>

<?php
$userId = (!empty($_GET['userId']) ? $Filter->clearInt($_GET['userId']) : NULL); 

if ($userId) 
{
    $profile = DB::$dbs->queryFetch("SELECT * FROM ".USERS." WHERE `id` = ?", [$userId]); 
    
    if (!$profile) 
    {
        error('Персонаж не найден.');
    } 
    else 
    {
        
        ?> 
<div class="head">Сообщение для <?=$Filter->output($profile['login'])?></div>
<a href="<?=HOME?>/modules/mail/index.php?userId=<?=$profile['id']?>" class="link-touch"> Обновить</a>
<a href="#" class="link-touch"> Смайлы</a>
<?php

# Check lvl
if ($user['lvl'] < $settings['mail_lvl']) 
{
    error('Почта доступна с ' . $settings['mail_lvl'] . ' уровня!', '/', 'На главную');
}

# Check user ajax settings;
if ($user['ajax'] == 1) 
{
    ?>
    <textarea class="text" name="text" placeholder="Введите сообщение..."></textarea><br/>
    <input type="hidden" id="usid" name="usid" value="<?=$Filter->clearInt($profile['id'])?>">
    <input class="submit" id="submitMail" style="display:block;color: white" type="submit" value="Отправить"><br/>
    <div class="head">История переписки</div><br/>
    <div class="userMessage"></div>
    <script type="text/javascript" src='message.js'></script>
    <?php
} 
else 
{
    # Mail send; 
    if (isset($_POST['try'])) 
    {
        $data = $_POST; 

        $data['text'] = $Filter->clearString($data['text']);

        if (empty($data['text'])) 
        {
            errorNoExit('Обнаружено пустое поле');
        } 
        else if (mb_strlen($data['text']) < 4 || mb_strlen($data['text'] > 1000)) 
        {
            errorNoExit('Сообщение должно быть в диапазоне [4-1000]');
        } 
        else 
        {
            # Add kontakt;
            $kontakt = DB::$dbs->queryFetch("SELECT * FROM ".MAIL_KONT." WHERE `id_user` = ? and `id_kont` = ? LIMIT 1", [$user['id'], $profile['id']]); 
            if ($kontakt['id_kont'] != $profile['id']) 
            {
                DB::$dbs->query("INSERT INTO ".MAIL_KONT." (`id_user`, `id_kont`, `time`) VALUES (?, ?, ?)", [$user['id'], $profile['id'], time()]);
                DB::$dbs->query("INSERT INTO ".MAIL_KONT." (`id_user`, `id_kont`, `time`) VALUES (?, ?, ?)", [$profile['id'], $user['id'], time()]);
            } 
            else 
            {
                DB::$dbs->query("UPDATE ".MAIL_KONT." SET `time` = ? WHERE `id_user` = ? and `id_kont` = ?", [time(), $user['id'], $profile['id']]);
                DB::$dbs->query("UPDATE ".MAIL_KONT." SET `time` = ? WHERE `id_user` = ? and `id_kont` = ?", [time(), $profile['id'], $user['id']]);
            }

            DB::$dbs->query("INSERT INTO ".MAIL." (`sender`, `given`, `text`, `time`) VALUES (?, ?, ?, ?)", [$user['id'], $profile['id'], $_POST['text'], time()]);
            success('Сообщение отправлено', '/modules/mail/index.php?userId=' . $userId, 'К сообщению');
        }
    }
    ?> 
    
    <form action="" method="POST"> 
        <b>Сообщение:</b> <br/> 
        <textarea class="text" name="text" placeholder="Введите сообщение..."></textarea><br/>
        <input type="submit" name="try" value="Отправить">
    </form>

    <?php

    echo '<div class="head">История переписки</div>';

    $all = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM ".MAIL." WHERE `sender` = ? and `given` = ? or `sender` = ? and `given` = ?", [$userId, $user['id'], $user['id'], $userId]);
    $n = new Navigator($all,10,'userId='. $userId . '');
    $sql = DB::$dbs->query("SELECT * FROM ".MAIL." WHERE `sender` = ? and `given` = ? or `sender` = ? and `given` = ? ORDER BY `time` DESC LIMIT {$n->start()}, 10", [$userId, $user['id'], $user['id'], $userId]);

    while ($post = $sql -> fetch()) 
	{
        # Read; 
        if ($post['given'] == $user['id'] && $post['read'] == 1) 
        {
            DB::$dbs->query("UPDATE ". MAIL ." SET `read` = ? WHERE `id` = ? ", [0, $post['id']]);
            header("Location: " . $_SERVER['REQUEST_URI']);
            exit();
        }

		$iduser = userLink($Filter->clearInt($post['sender']));
    	$time   = dataTime($Filter->clearInt($post['time']));
    	$text   = outputText($post['text'], $post['sender']);

		echo '<div class="wrap">'.$iduser .'<font color="#909090">['. $time .']</font><br/> 
            '. $text .'<br/>'. ($post['read'] == 1 ? '[не прочитано]' : null) .'</div>';
	}
    echo $n->navi();
}
$array = ['Почта'];
navPanel($array);
    }
} 
else 
{
    $all = DB::$dbs->querySingle("SELECT COUNT(`id`) FROM ".MAIL_KONT." WHERE `id_user` = ?", [$user['id']]);
    $n = new Navigator($all,10,'');
    $sql = DB::$dbs->query("SELECT * FROM ".MAIL_KONT." WHERE `id_user` = ? ORDER BY `time` DESC LIMIT {$n->start()}, 10", [$user['id']]);
    
    if ($all == 0) 
    {
        ?> 
        Контактов нет. 
        <?php 
    } 
    else 
    {
        while ($kont = $sql -> fetch()) 
        {
            $ank = DB::$dbs->queryFetch("SELECT * FROM ".USERS." WHERE `id` = ? LIMIT 1", [$kont['id_kont']]); 
            $newMess = DB::$dbs->querySingle("SELECT COUNT(*) FROM ".MAIL." WHERE `sender` = ? and `given` = ? and `read` = ?", [$ank['id'], $user['id'], 1]);
            $mail = DB::$dbs->queryFetch("SELECT * FROM ".MAIL." WHERE `sender` = ? and `given` = ? and `read` = ? ORDER BY `id`", [$ank['id'], $user['id'], 1]);
            ?> 
        <a href="<?=HOME?>/modules/mail/index.php?userId=<?=$ank['id']?>" class="linkPanel"><?=$Filter->output($ank['login'])?><?=($newMess > 0 ? ' <font color="green">[+ '.$newMess.']</font>' : NULL)?><?=(!empty($mail) ?  ':' . mb_substr(outputText($mail['text'], $ank['id']), 0, 40, 'utf-8') . '...' : NULL)?></a>
        <?php
        } 
        ?> 
        <?=$n->navi()?> 
        <?php
    } 
} 
require_once '../../core/foot.php';