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

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

only_reg();

$config = array(
    'domain' => $set['mail_panel_domain'],
    'aliase' => explode("\n", $set['mail_panel_aliase']),
);

$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`) = '" . $db->safesql($_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') {
        $db->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')");
        $db->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)) {
        $db->query("UPDATE `mail` SET `flaggedFrom` = '" . $db->safesql($_POST['action']) . "' WHERE $paramsTo AND (" . implode(' OR ', $listSort) . ") ");
        $db->query("UPDATE `mail` SET `flaggedTo` = '" . $db->safesql($_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 = $db->get_row($db->query("SELECT * FROM `user` WHERE `nick` = '" . $db->safesql($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 '%" . $db->safesql($search) . "%' AND `id_kont` = '$user[id]'";
    $querySearch[] = "`id_kont` like '%" . $db->safesql($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='/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>";

$arrContacts = $db->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 = $db->get_row($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 list-group-item-grey dop'>";

    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'>\n";
$doc->Link('btn btn-secondary btn-sm', "messageList.php", 'envelope', 'Новое сообщение');
echo "</div>";

if ($k_post > 0) {
    ?>
    <div class="list-group-item-null" style="margin-bottom: -10px; margin-top: -10px;">
        <label class="js_not custom-control custom-checkbox">
            <input type="checkbox" id="select_all" class="custom-control-input">
            <span class="custom-control-indicator"></span>
            <span class="custom-control-description">Отметить все</span>
        </label>
    </div>
    <?php
}

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 = $db->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]");
    ?>
    <form action="?s=<?= $flagged ?>" method="POST">
        <?php
        while ($post = $db->get_row($q)) {
            $EmailUser = new EmailUser($post['contact']);
            $ank = $EmailUser->getUser();
            ?>
            <div class="list-group-item-null dop <?= ($post['read'] == 0 && $post['id_user'] != $user['id'] ? 'list-group-item-info' : 'list-group-item-grey') ?>">
                <div class="email-checkbox pull-left">
                    <label class="js_not custom-control custom-checkbox">
                        <input type="checkbox" class="check_box custom-control-input" name="cnt<?= $post['id'] ?>" value="<?= text($post['contact']) ?>">
                        <span class="custom-control-indicator"></span>
                    </label>
                </div>

                <a href="messageList.php?s=<?= $flagged ?>&amp;contact=<?= urlencode($post['contact']) ?>" class="email-link">

                    <div class="overflow">
                        <span class="email-avatar pull-left"><?= avatar($ank['id'], '50', 'border-radius: 3px;'); ?></span> 
                        <div class="email-login overflow">
                            <?php echo icon_user($ank['id']) . text($ank['nick']); ?>
                            <span class="email-count">
                                (<?= $countArray[$post['contact']]['count_from'] ?>/<?= $countArray[$post['contact']]['count_to'] ?>)
                                <span class="email-count-new <?= ($post['read'] == 0 && $post['id_user'] != $user['id'] ? 'nohidden' : '') ?>">+<?= $countArray[$post['contact']]['count_new'] ?></span>
                            </span>
                        </div> 
                        <div class="email-text overflow">
                            <div class="overflow <?= ($post['read'] == 0 && $post['id_kont'] != $user['id'] ? 'email-text-noread' : '') ?>">
                                <?= ($post['attachments'] == 1 ? '<i class="fa fa-paperclip fa-fw"></i>' : '') ?> 
                                <i class="fa fa-<?= ($post['id_kont'] != $user['id'] ? 'caret-right' : 'caret-left') ?>"></i>
                                <?= text($post['msg']) ?>
                            </div>
                        </div>
                    </div>
                </a>
            </div>

            <?php
        }
        ?>
        <div class="list-group-item-null">
            <?php
            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>";
            }
            ?>
        </div>
    </form>
    <?php
    if ($k_page > 1) {
        str('?s=' . $flagged . '&amp;', $k_page, $page);
    }
}

$listInbox = $db->get_row($db->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='tag tag-info right'>" . ($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';
