<?php defined('ACCESS') OR die('No direct script access...');
/**
 * Author - koder_alex
 * ISQ - 669906617
 * VK - https://vk.com/koder_alex
 * It is forbidden to give, sell, modify.
 */
$dataExecute = array(':id_kont' => $user['id'], ':id_user' => $peer['id']);
DB::$pdo->query("UPDATE `mail` SET `read` = '1' WHERE `id_kont` = :id_kont AND `id_user` = :id_user", $dataExecute);
thead('Диалоги');
$mess = "";
$hash = md5(mt_rand() . (int)$_GET['to'] . mt_rand());
$_SESSION['attachments' . $peer['id']] = array(
    'to' => $peer['id'],
    'hash' => $hash,
);
?>
 <div class="app-block">
    <div class="head_actions_wrap<?= (isset($_GET['menu_opened']) ? ' head_actions_opened' : '') ?>">
        <a class="link_header"
           href="/mail/?act=show&amp;peer=<?= $peer['id'] . (isset($_GET['menu_opened']) ? '' : '&amp;menu_opened') ?>"
           onclick="MessagesActions.actionsOpened(this, event);"><h4 class="sub_header clearfix"><span
                        class="sub_header_label"><?= $peer['online'] . $peer['group'] . $peer['login'] . $peer['Medals'] ?> </span>
                <span class="sub_header_rl"><i class="i_actions">&nbsp;</i></span></h4></a>
        <ul class="context_menu head_actions">
            <?if($peer['id']){?>
	    <li><a href="/mail/?act=show_medias&amp;peer=<?= $peer['id'] ?>" class="cm_item bli"><span class="cm_label">Показать вложения</span></a></li>
	<?}?>
            <li><a href="/mail/?act=flush_history&amp;peer=<?= $peer['id'] ?>" class="cm_item bli"
                   onclick="return confirm('Вы действительно хотите удалить всю переписку с данным пользователем?  Отменить это действие будет невозможно.');"><span
                            class="cm_label">Очистить диалог</span></a></li>
        </ul>
    </div>
<?
if ($peer['id']) {
    ?>
    <div class="create_post create_post_extra create_message">
    <form action="/mail/?act=send&amp;to=<?= $peer['id'] ?>&amp;from=dialog" method="POST">
        <input id="data-text" type="hidden" data-min="<?= $config['min_length_text'] ?>"
               data-max="<?= $config['max_length_text'] ?>"/>
        <div class="iwrap"><textarea name="message" class="textfield" rows="3"
                                     onkeyup="mail.keyup(this, <?= $peer['id'] ?>);"><?= $mess ?></textarea></div>
        <div class="ibwrap append-atach"><div id="attachments" class="cp_attached_wrap"><div class="pi_medias">
            <?php
            $execSQL = ['image', 'prepare', '0', $user['id'], $peer['id']];
            $q = DB::$pdo->prepare("SELECT folder, name, tmp_name, extension FROM mail_files_vk WHERE `folder` = ? AND `action` = ? AND `id_mail` = ? AND `id_user` = ? AND `id_kont` = ? ORDER BY time DESC LIMIT " . $config['max_uploads_file']);
            $q->execute($execSQL);
            if($q->rowCount() > 0)
            {
                $q->closeCursor();
                $q->execute($execSQL);
                $config['attachments'] = true;
                    while ($post = $q->fetch())
                    {
                            ?>
                            <div class="medias_thumb thumb_item" data-attachments="image">
                                <img class="ph_img" src="/mail/file/<?= $post['folder'] ?>/<?= $post['tmp_name'] ?>">
                                <a href="/mail/?act=files&amp;type=delete&amp;hash=<?= $post['tmp_name'] ?>&amp;ajax" class="tu_cancel_wrap" onclick="return mediaUpload.reset(this, event, '/');">
                                    <div class="tu_cancel"></div>
                                </a>
                            </div>
                            <?
                    }
            }
            unset($post, $q);
            ?></div></div>
            <div class="cp_buttons_block">
                <input class="main-btn" type="submit" value="Отправить" id="write_submit"
                       onclick="return mail.send(this, <?= $peer['id'] ?>);">
                <span id="attach_photo_btn" class="ms_attachments_label<?= ($config['attachments'] ? ' cp_attach_btn_sel' : '') ?>">
                    <input data-nostyle="" class="inline_upload" type="file" data-upload="/mail/?act=dataSend&func=attachments&amp;peer=<?= $peer['id'] ?>&amp;hash=<?= $hash ?>" onchange="return mediaUpload.start(this, event);" name="attachments" accept="image/*" multiple="multiple">
                </span>
                <i class="SmileButton" id="SmileButton"></i>
                <div class="near_btn">
                    <span class="di_current_peer"></span>
                    <div class="di_typing"><i class="i_typing"></i><?= $peer['login'] ?> пишет..</div>
                </div>
            </div>
        </div>
    </form></div><?php }
$k_post = DB::$pdo->querySingle("SELECT COUNT(*) FROM mail WHERE `unlink` != :id_kont AND (`id_kont` = :id_kont AND `id_user` = :id_user OR `id_kont` = :id_user AND `id_user` = :id_kont)", $dataExecute);
$k_page = 0;
if (isset($_GET['p']) && $_GET['p'] != NULL && is_numeric($_GET['p']) && $_GET['p'] > 1) {
    $p = abs(intval($_GET['p']));
} else {
    $p = 1;
}
$start = 0;
if ($k_post > 10) {
    $pagination = new pagination(10, $k_post, $p);
    $total_lin = $pagination->limit;
    $k_page = $pagination->pages;
    $start = abs($p * 10) - 10;
} else {
    $total_lin = '';
}

?>
<?= ($peer['last_time'] < (time() - $config['TIME_ONLINE']) ? '<div id="di_activity" class="di_activity">' . $peer['login'] . ' был' . ($peer['info_sex'] == 0 ? 'а' : '') . ' в сети ' . timeleft($peer['last_time']) . '</div>' : '') ?>
    <script type="text/javascript">
        $(document).ready(function () {
            var match = location.search.match(/p=(\d+)/i);
            if (match !== null && match[1] !== null)
                request.page = parseInt(match[1]) + 1;
            $('.vk_mail #pagination').hide();
            $('.show_more_wrap').show();
            // Enable infinite scrolling when on desktop
            if (/Mobi/.test(navigator.userAgent) === false) {
                $(window).scroll(function (e) {
                    if ($(window).scrollTop() + $(window).height() == $(document).height()) {
                        $('#show_more').click();
                    }
                });
            }
        });
    </script>
<div id="messages" class="messages bl_cont" data-peer="<?= $peer['id'] ?>" data-limit="10" data-update="<?= UPDATE ?>" data-page="<?= $p ?>" data-offset="<?= ($start + 10) ?>">
<?
if ($k_post) {
    $q = DB::$pdo->query("SELECT * FROM mail WHERE `unlink` != :id_kont AND (`id_kont` = :id_kont AND `id_user` = :id_user OR `id_kont` = :id_user AND `id_user` = :id_kont) ORDER BY `id` DESC $total_lin", $dataExecute);
    $qF = DB::$pdo->prepare("SELECT id,folder, name, tmp_name, extension, type FROM mail_files_vk WHERE `action` = 'sent' AND `id_mail` = ?");
    while ($post = $q->fetch()) {
        $d = d_user($post['id_user'], true, 'mi_img');
        ?>
        <div
        class="msg_item<?= ($post['read'] == 0 ? ' mi_unread' : '') . ($user['id'] == $d['id'] ? ' message_outbox' : ' message_inbox') ?>">
        <div class="mi_iwrap"><a href="/id<?= $d['id'] ?>"><?= $d['avatar'] ?></a></div>
        <div class="mi_cont">
            <div class="mi_head">
                <span class="mi_date"><?= system::times($post['time']) ?></span>
                <a class="mi_author"
                   href="/id<?= $d['id'] ?>"><?= $d['online'] . $d['group'] . $d['login'] . $d['Medals'] ?></a>
            </div>
            <div class="mi_body">
                    <?php if($post['attachments']) {
                        $qF->execute([$post['id']]);
                        ?>
                        <div class="cp_attached_wrap">
                            <div class="pi_medias">
                                <?php while($file = $qF->fetch()) { ?>
                                    <a class="medias_thumb thumb_item mr_x_wrap" href="/mail/file/<?= $file['folder'] ?>/<?= $file['tmp_name'] ?>" target="_blank">
                                        <img class="ph_img" src="/mail/file/<?= $file['folder'] ?>/<?= $file['tmp_name'] ?>"></a>
                            <?php } $qF->closeCursor();?>
                            </div>
                        </div><div class="mi_text">
                            <?= system::BBcode(system::textOut($post['msg'])) ?>
                        </div>

                    <?php } else if($post['gifts'] > 0) {
                        $gifts = DB :: $pdo -> queryFetch("SELECT * FROM `user_gifts` WHERE `id` = '".$post['gifts']."' LIMIT 1");
                        ?><div class="mi_text"><div class="mi_medias_plain">
                        <?= ($user['id'] == $d['id'] ? "Вы отправили" : "Вам прислали") ?> подарок
                        </div>
                        </div>
                        <a href="/gifts?id=<?= $user['id'] ?>">
                            <img src="<?=(FILES_SERVER."gifts/{$gifts['id_gift']}.jpg")?>">
                        </a>
                        <div class="mi_text"><?= $gifts['komment'] ?></div>
                    <?php } else { ?>
                        <div class="mi_text">
                            <?= system::BBcode(system::textOut($post['msg'])) ?>
                        </div>
                    <?php } ?>
                <span style="float: right;margin-top: -10px;text-decoration: underline;">
                                <a href="/mail/?act=delete&amp;id=<?= $post['id'] ?>"><span class="ico ico-dell"></span></a>
                            </span>
            </div>
        </div></div><?
    }
    if ($k_page > $p) {
        ?>
        <div class="show_more_wrap">
        <a class="show_more" id="show_more" onclick="mail.loadMess('<?= $peer['id'] ?>')">Показать ещё сообщения</a>
        </div><?
    }
} else
    show('История сообщений пуста.', 'null');
?></div><?
if ($k_post && $k_page > 1)
    str_vk('/mail/?act=show&amp;peer=' . $peer['id'] . '&amp;', $k_page, $p);