<?php
/* DCMS Special
 * Дата последнего редактирования 02.10.2016
 * Модифицировал densnet
 */

foreach (array('start', 'compress', 'sess', 'settings', 'db_connect', 'ipua', 'fnc', 'user') as $inc) {
    require_once "../../sys/inc/$inc.php";
}

only_reg();

$listFlagged = array(
    'inbox' => lang('Активные'),
    'favorite' => lang('Избранное'),
    'archive' => lang('Архив'),
    'spam' => lang('Спам'),
    'deleted' => lang('Корзина'),
);

if (isset($_GET['s']) && array_key_exists($_GET['s'], $listFlagged)) {
    $listSort[] = " IF(`id_kont` = '$user[id]', `flaggedTo`, `flaggedFrom`) = '" . mysql_real_escape_string($_GET['s']) . "' ";
    $flagged = $_GET['s'];
} else {
    $listSort[] = " IF(`id_kont` = '$user[id]', `flaggedTo`, `flaggedFrom`) = 'inbox' ";
    $listSort[] = " IF(`id_kont` = '$user[id]', `flaggedTo`, `flaggedFrom`) = 'favorite' ";
    $flagged = 'inbox';
}

if (isset($_POST['action'])) {
    foreach ($_POST AS $key => $value) {
        if (preg_match('/^cnt/i', $key)) {
            $contactsTo[] = "`id_kont` = '$value'";
            $contactsFrom[] = "`id_user` = '$value'";
            $actionTrue = true;
        }
    }

    $paramsTo = '(' . implode(' OR ', $contactsTo) . ") AND `id_user` = '$user[id]'";
    $paramsFrom = '(' . implode(' OR ', $contactsFrom) . ") AND `id_kont` = '$user[id]'";

    if ($_POST['action'] == 'truncate') {
        mysql_query("UPDATE `mail` SET `deleted` = '-1' WHERE (`id_user` = '$user[id]' OR `id_kont` = '$user[id]') AND (" . implode(' OR ', $listSort) . ") AND (`deleted` != '0' OR type = 'email')");
        mysql_query("UPDATE `mail` SET `deleted` = '$user[id]' WHERE (`id_user` = '$user[id]' OR `id_kont` = '$user[id]') AND (" . implode(' OR ', $listSort) . ") AND `deleted` = '0' AND `type` = 'personal'");
        msg('Корзина успешно очищена');
    } elseif (array_key_exists($_POST['action'], $listFlagged) && isset($actionTrue)) {
        mysql_query("UPDATE `mail` SET `flaggedFrom` = '" . mysql_real_escape_string($_POST['action']) . "' WHERE $paramsTo AND (" . implode(' OR ', $listSort) . ") ");
        mysql_query("UPDATE `mail` SET `flaggedTo` = '" . mysql_real_escape_string($_POST['action']) . "' WHERE $paramsFrom AND (" . implode(' OR ', $listSort) . ") ");

        $_SESSION['message'] = lang('Контакты перенесены в') . " " . $listFlagged[$_POST[action]] . "";
    }

    header('Location: ?s=' . $flagged);
    exit;
}

#Поиск контактов по email и нику с id

if (isset($_GET['q'])) {
    $search = $_GET['q'];
    $sAnk = mysql_fetch_assoc(mysql_query("SELECT * FROM `user` WHERE `nick` = '" . mysql_real_escape_string($search) . "' OR `id` = '" . (int) $search . "' LIMIT 1"));

    if (isset($sAnk['id'])) {
        $querySearch[] = "`id_user` = '$sAnk[id]' AND `id_kont` = '$user[id]'";
        $querySearch[] = "`id_kont` = '$sAnk[id]' AND `id_kont` = '$sAnk[id]'";
    }

    $querySearch[] = "`id_user` like '%" . mysql_real_escape_string($search) . "%' AND `id_kont` = '$user[id]'";
    $querySearch[] = "`id_kont` like '%" . mysql_real_escape_string($search) . "%' AND `id_user` = '$user[id]'";
    $querySearch = ' AND (' . implode(' OR ', $querySearch) . ')';
} else {
    $search = null;
    $querySearch = null;
}

$set['title'] = ($flagged != 'inbox' ? $listFlagged[$flagged] . '/' : '') . 'Почта/' . $user['nick'];
require_once H . 'sys/inc/thead.php';

aut();
err();

echo "<link rel='stylesheet' href='/style/css/email.css' type='text/css' />";

#Навигация
echo "<div class='list-group-item-null list-group-item-grey'><small>";
echo "<a href='/' class='hint--right' data-hint='" . lang('На главную') . "'><i class='fa fa-home fa-lg'></i></a> <i class='fa fa-angle-right fa-fw'></i> ";
echo "<a href='/info.php?id=$user[id]'>$user[nick]</a> <i class='fa fa-angle-right fa-fw'></i> ";

if ($search != null) {
    echo "<a href='/user/mail/'>" . lang('Почта') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";

    if ($flagged != 'inbox') {
        echo "<a href='?s=$flagged'>$listFlagged[$flagged]</a> <i class='fa fa-angle-right fa-fw'></i> ";
    }

    echo lang('Поиск');
} elseif ($flagged == 'inbox') {
    echo lang('Почта');
} else {
    echo "<a href='/user/mail/'>" . lang('Почта') . "</a> <i class='fa fa-angle-right fa-fw'></i> ";
    echo "$listFlagged[$flagged]";
}

echo "</small></div><br />";

$arrContacts = mysql_query("SELECT e.id_user, IF(e.id_user = '$user[id]', e.id_kont, e.id_user) AS nick, SUM(IF (e.read = '0' AND e.id_kont = '$user[id]', 1, 0)) AS count_new, SUM(IF (e.read = '0' AND e.id_user = '$user[id]', 1, 0)) AS count_read, SUM(IF (e.id_kont = '$user[id]', 1, 0)) AS count_to, SUM(IF (e.id_user = '$user[id]', 1, 0)) AS count_from FROM mail AS e WHERE (e.id_kont = '$user[id]' OR e.id_user = '$user[id]') AND (" . implode(' OR ', $listSort) . ") AND `deleted` != '$user[id]' AND `deleted` != '-1' $querySearch GROUP BY IF(e.id_user = '$user[id]', e.id_kont, e.id_user)");
$countArray = array();
while ($count = mysql_fetch_assoc($arrContacts)) {
    $countArray[strtolower($count['nick'])] = $count;
}

$k_post = count($countArray);

if ($k_post > 0 || $querySearch != null) {
    echo "<form action='?' method='GET' class='list-group-item-null'>";

    echo "<input type='hidden' name='s' value='$flagged' />";
    echo "<div class='input-group'>
      <input type='text' name='q' value='" . stripcslashes(htmlspecialchars($search)) . "' class='form-control' placeholder='" . lang('Поиск контакта') . "'>
      <span class='input-group-btn'>
        <button class='btn btn-secondary' type='button'><i class='fa fa-search fa-fw'></i></button>
      </span>
  </div>";

    echo "</form>";
}

echo "<div class='list-group-item-null list-group-item-grey'>\n";
echo "<a href='messageList.php'><i class='fa fa-envelope fa-fw'></i> " . lang('Новое сообщение') . "</a>";
echo "</div>";

if ($k_post == 0) {
    $doc->NoResult();
} else {
    $k_page = k_page($k_post, $set['p_str']);
    $page = page($k_page);
    $start = $set['p_str'] * $page - $set['p_str'];
    $q = mysql_query("SELECT *, IF(`id_user` = '$user[id]', `id_kont`, `id_user`) AS contact FROM `mail` AS e , (SELECT MAX(id) AS id FROM `mail` WHERE `deleted` != '$user[id]' AND `deleted` != '-1' AND (" . implode(' OR ', $listSort) . ") AND (`id_kont` = '$user[id]' OR `id_user` = '$user[id]') GROUP BY IF(`id_user` = '$user[id]', `id_kont`, `id_user`))t WHERE e.id = t.id AND (`id_kont` = '$user[id]' OR `id_user` = '$user[id]') AND (" . implode(' OR ', $listSort) . ") AND `deleted` != '$user[id]' AND `deleted` != '-1' $querySearch GROUP BY IF(`id_user` = '$user[id]', `id_kont`, `id_user`) ORDER BY e.id DESC LIMIT $start, $set[p_str]");

    echo "<form action='?s=$flagged' method='POST'>";

    while ($post = mysql_fetch_assoc($q)) {
        $EmailUser = new EmailUser($post['contact']);
        $ank = $EmailUser->getUser();

        echo "<a href='messageList.php?s=$flagged&amp;contact=" . urlencode($post['contact']) . "'>";
        ?>
        <table class='list-group-item-null'  
        <?php
        if ($countArray[$post['contact']]['count_new'] == 0) {
            echo '';
        } else {
            echo 'style="background-color: #edf1f5;"';
        }
        ?>
               ><tr><td class='icon14'>
                    <?php
                    avatar($ank['id'], '50', 'border-radius: 1px;');
                    echo "</td><td class='null'>";
                    ?>

                    <?php
                    if ($countArray[$post['contact']]['count_new'] == 0) {
                        $new = null;
                    } else {
                        $new = "+{$countArray[$post['contact']]['count_new']}";
                    }
                    echo "<span class='badge'>{$countArray[$post['contact']]['count_from']}/{$countArray[$post['contact']]['count_to']}</span> <span class='" . ($post['read'] == 0 && $post['id_user'] != $user['id'] ? 'badge' : '') . "'>$new</span>";

                    echo user($ank['id']);

                    echo " <span style='color:grey;'>" . date::times($post['time']) . "</span><br />";
                    echo "<div class='" . ($post['read'] == 0 && $post['id_kont'] != $user['id'] ? 'dialogs_new_msg' : 'dialogs') . "' style='border-radius: 3px;'>";
                    echo "<span style='float:right;'><label class='c-input c-checkbox'><input type='checkbox' name='cnt$post[id]' value='" . stripcslashes(htmlspecialchars($post['contact'])) . "' />";
                    echo "<span class='c-indicator'></span></label></span>";
                    echo "" . ($post['attachments'] == 1 ? '<i class="fa fa-paperclip fa-fw"></i>' : '') . " " . toOutput(cutStr($post['msg'], 50));
                    echo "</div>";
                    echo "</td></tr></table></a><div class='hr'></div>";
                }

                echo "<div class='list-group-item-null'>\n";
                if ($flagged != 'deleted') {
                    if ($flagged != 'spam') {
                        echo "<button class='btn btn-success btn-sm' type='submit' name='action' value='spam'>" . lang('спам') . "</button> ";
                    }

                    if ($flagged != 'archive') {
                        echo "<button class='btn btn-success btn-sm' type='submit' name='action' value='archive'>" . lang('архив') . "</button> ";
                    } else {
                        echo "<button class='btn btn-success btn-sm' type='submit' name='action' value='inbox'>" . lang('из архива') . "</button> ";
                    }
                }

                if ($flagged == 'deleted') {
                    echo "<button class='btn btn-success btn-sm' type='submit' name='action' value='inbox'>" . lang('восстановить') . "</button> ";
                    echo "<button class='btn btn-success btn-sm' type='submit' name='action' value='truncate'>" . lang('очистить корзину') . "</button> ";
                } else {
                    echo "<button class='btn btn-success btn-sm' type='submit' name='action' value='deleted'>" . lang('удалить') . "</button>";
                }

                echo "</div>";
                echo "</form>";

                if ($k_page > 1) {
                    str('?s=' . $flagged . '&amp;', $k_page, $page);
                }
            }

            $listInbox = mysql_fetch_assoc(mysql_query("SELECT SUM(IF(IF (e.id_kont = '$user[id]', flaggedTo, flaggedFrom) = 'favorite', 1, 0)) AS favorite, SUM(IF(IF (e.id_kont = '$user[id]', flaggedTo, flaggedFrom) = 'archive', 1, 0)) AS archive, SUM(IF(IF (e.id_kont = '$user[id]', flaggedTo, flaggedFrom) = 'spam', 1, 0)) AS spam, SUM(IF(IF (e.id_kont = '$user[id]', flaggedTo, flaggedFrom) = 'deleted', 1, 0)) AS deleted FROM `mail` AS e WHERE (e.id_kont = '$user[id]' OR e.id_user = '$user[id]') AND `deleted` != '$user[id]' AND `deleted` != '-1' LIMIT 1"));

            if ($flagged == 'inbox' && $search == null) {
                foreach ($listInbox AS $key => $value) {
                    if ($key == 'favorite') {
                        $img = 'star';
                    } elseif ($key == 'archive') {
                        $img = 'archive';
                    } elseif ($key == 'spam') {
                        $img = 'ban';
                    } elseif ($key == 'deleted') {
                        $img = 'trash';
                    }

                    echo "<a class='list-group-item-null list-group-item-grey' href='?s=$key'><i class='fa fa-$img fa-fw'></i> $listFlagged[$key] <span class='badge'>" . ($value ? $value : 0) . "</span></a>";
                }

                $doc->Link('list-group-item-null list-group-item-grey', 'settings.php', 'cog', 'Настройки почты');
            } else {
                $doc->Link('list-group-item-null list-group-item-grey', '?', 'arrow-left', 'Назад');
            }

            if ($flagged == 'deleted' && isset($set['mail_clear_time'])) {
                $setnamed = array(
                    '86400' => '1 ' . lang('дня'),
                    '604800' => '1 ' . lang('недели'),
                    '2419200' => '1 ' . lang('месяца'),
                    '7257600' => '3 ' . lang('месяцев'),
                    '14515200' => '6 ' . lang('месяцев'),
                    '29030400' => '1 ' . lang('года'),
                );

                echo "<div class='list-group-item-null list-group-item-warning'>";
                echo "Внимание. Контакты хранятся в корзине не более " . $setnamed[$set['mail_clear_time']] . " После этого они полностью удаляются.";
                echo "</div>";
            }
            ?>

            <script>
                $(document).ready(function () {
                    var select_all = 0;
                    $('#select_all').click(function () {
                        if (select_all == 0) {
                            $('.check_box').prop('checked', true);
                            select_all = 1;
                        } else {
                            $('.check_box').prop('checked', false);
                            select_all = 0;
                        }
                    });

                    $('.js_not').css({'display': 'inline-block'});
                });
            </script>
            <?php
            require_once H . 'sys/inc/tfoot.php';
            