<?PHP

include_once '../sys/inc/home.php';
include_once H.'sys/inc/start.php';
include_once H.'sys/inc/compress.php';
include_once H.'sys/inc/sess.php';
include_once H.'sys/inc/settings.php';
include_once H.'sys/inc/db_connect.php';

/**
* Классы для работы с почтой
*/
require 'classes/PHPMailerAutoload.php';

include_once H.'sys/inc/ipua.php';
include_once H.'sys/inc/fnc.php';
include_once H.'sys/inc/user.php';

only_reg();

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

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

if (isset($_GET['s']) && array_key_exists($_GET['s'], $listFlagged)) {
    $listSort[] = " IF(`id_kont` = '$user[id]', `flaggedTo`, `flaggedFrom`) = '" . my_esc($_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'");
    $_SESSION['message'] = 'Корзина успешно очищена';
  } 
  
  elseif (array_key_exists($_POST['action'], $listFlagged) && isset($actionTrue)) {
    mysql_query("UPDATE `mail` SET `flaggedFrom` = '" . my_esc($_POST['action']) . "' WHERE $paramsTo AND (" . implode(' OR ', $listSort) . ") ");
    mysql_query("UPDATE `mail` SET `flaggedTo` = '" . my_esc($_POST['action']) . "' WHERE $paramsFrom AND (" . implode(' OR ', $listSort) . ") ");

    $_SESSION['message'] = 'Контакты перенесены в ' . $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` = '" . my_esc($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 '%" . my_esc($search) . "%' AND `id_kont` = '$user[id]'";
  $querySearch[] = "`id_kont` like '%" . my_esc($search) . "%' AND `id_user` = '$user[id]'";
  $querySearch = ' AND ('. implode(' OR ', $querySearch) . ')';
} else {
  $search = null;
  $querySearch = null;
}

$set['title'] = ($flagged != 'inbox' ? $listFlagged[$flagged] . '/' : '') . 'Почта/' . $user['nick'];
include_once H.'sys/inc/thead.php';
title();
aut();
err();
?>
<ol class="breadcrumb">
  <li><a href="/"><img src="/mail/style/icons/home.png" /></a></li>
  <li><a href="/id<?= $user['id']?>"><?= $user['nick']?></a></li>
  <? if ($search != null) { ?>
    <li><a href="?">Почта</a></li>
    <? if ($flagged != 'inbox') { ?>
      <li><a href="?s=<?= $flagged?>"><?= $listFlagged[$flagged]?></a></li>
    <? } ?>
    <li class="active">Поиск</li>
  <? } elseif ($flagged == 'inbox') { ?>
    <li class="active">Почта</li>
  <? } else { ?>
    <li><a href="?">Почта</a></li>
    <li class="active"><?= $listFlagged[$flagged]?></li>
  <? } ?>
</ol>
<?
$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) {
  ?>
  <div class="email-search">
    <form action="?" method="GET">
      <input type="hidden" name="s" value="<?= $flagged?>" />
      <table cellpadding="0" cellspacing="0">
        <tr>
          <td class="search-input"><input type="search" name="q" placeholder="Поиск контакта" value="<?= text($search)?>"/></td> 
          <td class="search-submit"><button type="submit">Поиск</button></td>
        </tr>
      </table>
    </form>
  </div>
  <?
}
?>
<div class="email-panel overflow">
  <? if ($k_post > 0) { ?>
     <label class="js_not pull-left"><input id="select_all" type="checkbox"> <span class="overflow">Отметить все</span></label>
  <? } ?>
  <a class="pull-right" href="messageList.php"><img src="style/icons/mail.png" /> Новое сообщение</a>
</div>
<?
if ($k_post == 0) {
    ?>
    <div class="mess">Список контактов пуст</div>
    <?
} 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]"); 
                      
    ?>
    <form class="email" action="?s=<?= $flagged?>" method="POST">
      <?
      while ($post = mysql_fetch_assoc($q))
      {
          $EmailUser = new EmailUser($post['contact']);
          $ank = $EmailUser->getUser();
          ?>
          <div class="email <?= ($post['read'] == 0 && $post['id_user'] != $user['id'] ? 'email-read' : '')?>">
            <div class="email-checkbox pull-left">
              <input class="check_box" type="checkbox" name="cnt<?= $post['id']?>" value="<?= text($post['contact'])?>" >
            </div>
            <a href="messageList.php?s=<?= $flagged?>&amp;contact=<?= urlencode($post['contact'])?>" class="email-link">
              <div class="overflow">
                <span class="email-avatar pull-left"><?= $ank['avatar']?></span> 
                <div class="email-login overflow">
                  <?= $ank['icon']?> <span class="<?= ($ank['ban'] == true ? 'user-ban' : '')?>"><?= text($ank['nick'])?></span>
                  <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 ? '<img src="style/icons/paper-clip.png">' : '')?> 
                    <img src="style/icons/<?= ($post['id_kont'] != $user['id'] ? 'out' : 'in')?>.png" />
                    <?= text($post['msg'])?>
                  </div>
                </div>
              </div>
            </a>
          </div>
          <?
      }
      ?>
      <div class="email-button">
      <? 
      if ($flagged != 'deleted') {
        if ($flagged != 'spam') { ?>
          <button type="submit" name="action" value="spam">спам</button> 
        <? } 
        
        if ($flagged != 'archive') { ?>
          <button type="submit" name="action" value="archive">архив</button> 
        <? } else {
          ?><button type="submit" name="action" value="inbox">из архива</button><?
        }
      }
      
      if ($flagged == 'deleted') { ?>
        <button type="submit" name="action" value="inbox">восстановить</button> 
        <button type="submit" name="action" value="truncate">очистить корзину</button> 
      <? } else { ?>
      <button type="submit" name="action" value="deleted">удалить</button>
      <? } ?>
      </div>
    </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")); 

?>
<div class="email email-panel">
<?
if ($flagged == 'inbox' && $search == null) { 
  foreach($listInbox AS $key => $value) {
      ?>
      <a href="?s=<?= $key?>">
        <img src="style/icons/<?= $key?>.png" /> <?= $listFlagged[$key]?>
      </a> 
      <span class="email-count">(<?= ($value ? $value : 0)?>)</span><br />
      <?
  }
  ?>
  <a href="settings.php">
    <img src="style/icons/gear.png" /> Настройки почты
  </a> 
  <?
} else {
  ?>
  <a href="?"><img src="style/icons/in.png" /> Назад</a>
  <?
}
?>
</div>

<? if ($flagged == 'deleted' && isset($set['mail_clear_time'])) { 
$setnamed = array(
    '86400' => '1 дня',
    '604800' => '1 недели',
    '2419200' => '1 месяца',
    '7257600' => '3 месяцев',
    '14515200' => '6 месяцев',
    '29030400' => '1 года',
);
?>
<div class="email email-panel">
Внимание. Контакты хранятся в корзине не более <?= $setnamed[$set['mail_clear_time']]?>. После этого они полностью удаляются.
</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>
<?
include_once H.'sys/inc/tfoot.php';
