<?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.
 */
$id_mail = 0;
if (!(isset($_POST['to']) && is_numeric($_POST['to']) && (int)$_POST['to'] != 0) || !array_key_exists($from, $config['url']))
    setData(array('msg_box' => 'Ошибка доступа.', 'type' => 'error'));
$_POST['message'] = system::check($_POST['message']);
$dataExecute = array(':id_user' => $user['id'], ':id_kont' => (int)$_POST['to'], ':msg' => $_POST['message']);
$cnt_files = DB::$pdo->querySingle("SELECT COUNT(id) FROM mail_files_vk WHERE `action` = 'prepare' AND `id_mail` = '0' AND `id_user` = '" . $user['id'] . "' AND `id_kont` = '" . (int)$_POST['to'] . "'");
if (!$cnt_files) {
    if (empty($_POST['message']) || !empty($_POST['message']) && system::utf_strlen($_POST['message']) > $config['max_length_text'])
        setData(array('msg_box' => 'Сообщение должно быть длиной не менее ' . des2num($config['min_length_text'], array('-го', '-х', '-ти')) . ' и не более ' . des2num($config['max_length_text'], array('-го', '-х', '-ти')) . ' символов.', 'type' => 'warning'));

    if (DB::$pdo->querySingle("SELECT COUNT(*) FROM `mail` WHERE `id_user` = :id_user AND `id_kont` = :id_kont AND `time` > '" . (time() - 60) . "' AND `msg` = :msg", $dataExecute))
        setData(array('msg_box' => 'Ваше сообщение повторяет предыдущие.', 'type' => 'warning'));
}
if ($config['url'][$from] != 'peer')
    setData(array('msg_box' => 'Ошибка доступа.', 'type' => 'error'));
if (admin :: getAccess($user, array('a' => 3)) === false && $user['id'] != (int)$_POST['to']) {
    $uSet = DB::$pdo->queryFetch("SELECT us.*, IF (pf.id_user, 1, 0) AS frends FROM `privatMail` as us
			LEFT JOIN friends AS pf ON (pf.id_user = '$user[id]' AND pf.id_friend = '" . (int)$_POST['to'] . "') OR (pf.id_user = '" . (int)$_POST['to'] . "' AND pf.id_friend = '$user[id]')
			WHERE us.id_user = '" . (int)$_POST['to'] . "' LIMIT 1");
    if ($uSet !== false) {
        if ($uSet['privat_mail'] == 2 && !$uSet['frends'])
            setData(array('msg_box' => 'По соображениям приватности, пользователю могут писать только друзья.', 'type' => 'warning'));
        if (admin :: getAccess($user, array('a' => 3)) === false && $uSet['admin_mail'] == 1) {
            $aMess = DB::$pdo->queryFetch("SELECT `id` FROM `mail` WHERE `id_kont` = :id_kont AND `id_user` = :id_user OR `id_kont` = :id_user AND `id_user` = :id_kont ORDER BY `id` DESC LIMIT 1", array(':id_kont' => $user['id'], ':id_user' => (int)$_POST['to']));
            if ($aMess === false) {
                setData(array('msg_box' => 'По соображениям приватности, администратор запретил чтоб ему писали.', 'type' => 'warning'));
            }
        }
    }
}
$sql = array('', "");
$mi_unread = " mi_unread";
if ($user['id'] == (int)$_POST['to']) {
    $sql = array(', `read`', ", '1'");
    $mi_unread = "";
}
if($cnt_files >= 1) {
    DB::$pdo->query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `attachments`, `time`" . $sql[0] . ") values(:id_user, :id_kont, :msg, '1', '" . time() . "'" . $sql[1] . ")", $dataExecute);
    $id_mail = DB :: $pdo -> lastInsertId();
    DB::$pdo->query("UPDATE `mail_files_vk` SET `action` = 'sent', `id_mail` = '".$id_mail."' WHERE `action` = 'prepare' AND `id_mail` = '0' AND `id_user` = '". $user['id'] ."' AND `id_kont` = '". (int)$_POST['to'] ."'");
} else {
    DB::$pdo->query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`" . $sql[0] . ") values(:id_user, :id_kont, :msg, '" . time() . "'" . $sql[1] . ")", $dataExecute);
    $id_mail = DB :: $pdo -> lastInsertId();
}
/*if(!empty($_SESSION['attachments' . (int)$_POST['to']]))
    unset($_SESSION['attachments' . (int)$_POST['to']]);
*/
DB::$pdo->query("UPDATE `users` SET `vkTypingId` = '0', `vkTypingLastTime` = '0' WHERE `id` = '$user[id]'");

$dataContent = '';
if ($id_mail > 0) {
    ob_start();
    $d = d_user($user['id'], true, 'mi_img');
    $qF = DB::$pdo->prepare("SELECT id,folder, name, tmp_name, extension, type FROM mail_files_vk WHERE `action` = 'sent' AND `id_mail` = ?");
    ?>
    <div
    class="msg_item<?= $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(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($cnt_files >= 1) {
                        $qF->execute([$id_mail]);
                        ?>
                        <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 } ?>
                            </div>
                        </div>

                    <?php }  ?>
            <div class="mi_text"><?= system::BBcode(system::textOut($_POST['message'])) ?></div>
            <span style="float: right;margin-top: -10px;text-decoration: underline;">
                                <a href="/mail/?act=delete&amp;id=<?= $id_mail ?>"><span
                                            class="ico ico-dell"></span></a>
                            </span>
        </div>
    </div></div><?
    $dataContent = ob_get_contents();
    ob_end_clean();
}
setData(array('type' => 'ok', 'mail' => $dataContent, 'id_mail' => $id_mail));