<?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.
 */

if ($_SERVER['REQUEST_METHOD'] != 'POST' || !(isset($_GET['to']) && is_numeric($_GET['to']) && (int)$_GET['to'] != 0) || !array_key_exists($from, $config['url']))
    redirect('/mail/', 'Ошибка доступа.', 'error');

if (isset($_POST['attachments']) && $_POST['attachments'] == 'attachments') {
    $hash = md5(mt_rand() . (int)$_GET['to'] . mt_rand());
    $_SESSION['attachments' . (int)$_GET['to']] = array(
        'to' => (int)$_GET['to'],
        'hash' => $hash,
        'type' => $config['url'][$from],
        'text' => (!empty($_POST['message']) ? system::check($_POST['message']) : false)
    );
    redirect('/mail/?act=attachments&' . $config['url'][$from] . '=' . (int)$_GET['to'] . '&hash=' . $hash);
}
$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)$_GET['to'] . "'");
if (!$cnt_files) {
    if (empty($_POST['message']) || !empty($_POST['message']) && system::utf_strlen($_POST['message']) > $config['max_length_text']) {
        redirect('/mail/?act=show&' . $config['url'][$from] . '=' . (int)$_GET['to'], 'Сообщение должно быть длиной не менее ' . des2num($config['min_length_text'], array('-го', '-х', '-ти')) . ' и не более ' . des2num($config['max_length_text'], array('-го', '-х', '-ти')) . ' символов.', 'warning');
    }
}
if ($config['url'][$from] == 'peer') {
    if (admin:: getAccess($user, array('a' => 3)) === false && $user['id'] != (int)$_GET['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)$_GET['to'] . "') OR (pf.id_user = '" . (int)$_GET['to'] . "' AND pf.id_friend = '$user[id]')
			WHERE us.id_user = '" . (int)$_GET['to'] . "' LIMIT 1");
        if ($uSet !== false) {
            if ($uSet['privat_mail'] == 2 && !$uSet['frends'])
                redirect('/mail/?act=show&' . $config['url'][$from] . '=' . (int)$_GET['to'], 'По соображениям приватности, пользователю могут писать только друзья.', '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)$_GET['to']));
                if ($aMess === false) {
                    redirect('/mail/?act=show&' . $config['url'][$from] . '=' . (int)$_GET['to'], 'По соображениям приватности, администратор запретил чтоб ему писали.', 'warning');
                }
            }
        }
    }
    if($cnt_files >= 1) {
        DB::$pdo->query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`, `attachments`) values(:id_user, :id_kont, :msg, :time, '1')", array(':id_user' => $user['id'], ':id_kont' => (int)$_GET['to'], ':msg' => system::check($_POST['message']), ':time' => time()));
        $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)$_GET['to'] ."'");
    } else {
        DB::$pdo->query("INSERT INTO `mail` (`id_user`, `id_kont`, `msg`, `time`) values(:id_user, :id_kont, :msg, :time)", array(':id_user' => $user['id'], ':id_kont' => (int)$_GET['to'], ':msg' => system::check($_POST['message']), ':time' => time()));
    }
    DB::$pdo->query("UPDATE `users` SET `vkTypingId` = '0', `vkTypingLastTime` = '0' WHERE `id` = :id", array(':id' => $user['id']));
}

redirect('/mail/?act=show&' . $config['url'][$from] . '=' . (int)$_GET['to'], 'Сообщение успешно отправлено.', 'ok');
?>