<?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 (!(isset($_GET['id']) && is_numeric($_GET['id'])))
    redirect('/mail/', 'Ошибка доступа.', 'error');
$mail = DB::$pdo->queryFetch("SELECT id, id_user, IF(id_user = :id_user, id_kont, id_user) AS contact FROM `mail` WHERE `id` = :id AND (`id_user` = :id_user OR `id_kont` = :id_user)  AND unlink != :id_user LIMIT 1", array(':id_user' => $user['id'], ':id' => (int)$_GET['id']));
if (!$mail)
    redirect('/mail/', 'Ошибка доступа.', 'error');


$del = DB::$pdo->prepare("DELETE FROM `mail` WHERE ".($mail['contact'] == $user['id'] ? '' : "`unlink` = '".$mail['contact']."' AND ")."`id` = :id");
$del->execute(array(':id' => $mail['id']));
if($del->rowCount()) {
    $q = DB::$pdo->query("SELECT folder, tmp_name FROM mail_files_vk WHERE `action` = 'sent' AND `id_mail` = '".$mail['id']."'");
    while($unlink = $q->fetch())
        unlink(FILES_PATH . 'mail/files/' . $unlink['folder'] . '/' . $unlink['tmp_name']);
    DB::$pdo->query("DELETE FROM `mail_files_vk` WHERE `action` = 'sent' AND `id_mail` = '".$mail['id']."'");
}
DB::$pdo->query("UPDATE `mail` SET `unlink` = :id_user WHERE  `id` = '" . $mail['id'] . "'", array(':id_user' => $user['id']));
redirect('/mail/?act=show&peer=' . $mail['contact'], 'Сообщение удалено.');