<?php

/**
 * @package     JohnCMS
 * @link        http://johncms.com
 * @copyright   Copyright (C) 2008-2011 JohnCMS Community
 * @license     LICENSE.txt (see attached file)
 * @version     VERSION.txt (see attached file)
 * @author      http://johncms.com/about
 */

defined('_IN_JOHNCMS') or die('Error: restricted access');

if ($id) {
    //Проверка существования пользователя
    $reqs = mysql_query("SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1;");
    if (mysql_num_rows($reqs) == 0) {
        $textl = 'Личная почта';
        require_once('../incfiles/head.php');
        echo display_error('Такого пользователя не существует');
        require_once("../incfiles/end.php");
        exit;
    }
    $res = mysql_fetch_assoc($reqs);

    $out .= '<div class="phdr"><h3>Входящие сообщения от ' . $res['name'] . '</h3></div>';
    //Отображаем список входящих сообщений
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM `cms_mail` WHERE `user_id`='$id' AND `from_id`='$user_id' AND `delete`!='$user_id' AND `sys`='0';"), 0);
    if ($total) {
        $req = mysql_query("SELECT `cms_mail`.*, `cms_mail`.`id` as `mid`, `cms_mail`.`time` as `mtime`, `users`.* FROM `cms_mail` LEFT JOIN `users` ON `cms_mail`.`user_id`=`users`.`id` WHERE `cms_mail`.`user_id`='$id' AND `cms_mail`.`from_id`='$user_id' AND `cms_mail`.`delete`!='$user_id' AND `cms_mail`.`sys`='0' ORDER BY `cms_mail`.`time` DESC LIMIT " . $start . "," . $kmess);
        $mass_read = array();
        for ($i = 0; ($row = mysql_fetch_assoc($req)) !== false; ++$i) {
            $out .= $i % 2 ? '<div class="list1">' : '<div class="list2">';
            if ($row['read'] == 0 && $row['from_id'] == $user_id)
                $mass_read[] = $row['mid'];
            $vrp1 = date("d.m.Y / H:i", $row['mtime'] + $set_user['sdvig'] * 3600);
            $post = $row['text'];
            $post = checkout($post, 1, 1);
            if ($set_user['smileys'])
                $post = smileys($post, $row['rights'] >= 1 ? 1 : 0);
            if ($row['file_name'])
                $post .= '<div class="func">Файл: <a href="index.php?act=load&amp;id=' . $row['mid'] . '">' . $row['file_name'] . '</a> (' . formatsize($row['size']) . ')(' . $row['count'] . ')</div>';
            $subtext = '<a href="index.php?act=delete&amp;id=' . $row['mid'] . '">Удалить</a>';
            $out .= show_user($row, 1, ($rights >= 6 && $rights >= $row['rights'] ? 1 : 0), $vrp1, $post, $subtext);
            $out .= '</div>';
        }
        if ($mass_read) {
            $result = implode(',', $mass_read);
            mysql_query("UPDATE `cms_mail` SET `read`='1' WHERE `from_id`='$user_id' AND `id` IN (" . $result . ")");
        }
        $out .= '<div class="phdr">Всего: ' . $total . '</div>';
        //Навигация
        if ($total > $kmess) {
            $out .= '<p>' . pagenav('index.php?act=input&amp;id=' . $id . '&amp;', $start, $total, $kmess) . '</p>';
            $out .= '<p><form action="index.php" method="get">
			<input type="hidden" name="act" value="input"/>
			<input type="hidden" name="id" value="' . $id . '"/>
			<input type="text" name="page" size="2"/>
			<input type="submit" value="К странице &gt;&gt;"/></form></p>';
        }
    } else {
        $out .= '<div class="rmenu">Сообщений нет</div>';
    }
    $out .= '<div class="menu"><a href="index.php?act=write&amp;id=' . $id . '">Написать</a></div>';
    $out .= '<div class="menu"><a href="index.php?act=input">Входящие</a></div>';
} else {
    $textl = 'Личная почта';
    require_once('../incfiles/head.php');
    $out .= '<div class="phdr"><h3>Входящие сообщения</h3></div>';
    //Групируем по контактам
    $count = mysql_result(mysql_query("SELECT COUNT(*) FROM `cms_mail` WHERE `from_id`='$user_id' AND `delete`!='$user_id';"), 0);
    $total = mysql_result(mysql_query("SELECT COUNT(*) FROM (SELECT DISTINCT `user_id` FROM `cms_mail` WHERE `from_id`='$user_id' AND `sys`='0') a;"), 0);
    if ($total) {
        $req = mysql_query("SELECT `users`.* FROM `cms_mail`
		LEFT JOIN `users` ON `cms_mail`.`user_id`=`users`.`id`
		WHERE `cms_mail`.`from_id`='" . $user_id . "' AND `cms_mail`.`delete`!='$user_id' AND `cms_mail`.`sys`='0' GROUP BY `cms_mail`.`user_id` ORDER BY `cms_mail`.`time` DESC LIMIT "
            . $start . "," . $kmess);
        $i = 1;
        while (($row = mysql_fetch_assoc($req)) !== false) {
            $out .= $i % 2 ? '<div class="list1">' : '<div class="list2">';
            $subtext = '<a href="index.php?act=input&amp;id=' . $row['id'] . '">Входящие</a> | <a href="index.php?act=write&amp;id=' . $row['id'] . '">Переписка</a> | <a href="index.php?act=deluser&amp;id=' . $row['id'] . '">Удалить</a> | <a href="index.php?act=ignor&amp;id=' . $row['id'] . '&amp;add">В игнор</a>';
            $count_message = mysql_result(mysql_query("SELECT COUNT(*) FROM `cms_mail` WHERE `user_id`='{$row['id']}' AND `from_id`='$user_id' AND `delete`!='$user_id';"), 0);
            $new_count_message = mysql_result(mysql_query("SELECT COUNT(*) FROM `cms_mail` WHERE `cms_mail`.`user_id`='{$row['id']}' AND `cms_mail`.`from_id`='$user_id' AND `read`='0' AND `delete`!='$user_id';"), 0);
            $out .= show_user($row, 1, ($rights >= 6 && $rights >= $row['rights'] ? 1 : 0), '(' . $count_message . ($new_count_message ? '/<span class="red">+' . $new_count_message . '</span>' : '') . ')', NULL, $subtext);
            $out .= '</div>';
            ++$i;
        }
        $out .= '<div class="phdr">Всего: ' . $count . '</div>';
        //Навигация
        if ($total > $kmess) {
            $out .= '<p>' . pagenav('index.php?act=input&amp;', $start, $total, $kmess) . '</p>';
            $out .= '<p><form action="index.php" method="get">
			<input type="hidden" name="act" value="input"/>
			<input type="text" name="page" size="2"/>
			<input type="submit" value="К странице &gt;&gt;"/></form></p>';
        }

    } else {
        $out .= '<div class="rmenu">Сообщений нет</div>';
    }
}

$textl = 'Личная почта';
require_once('../incfiles/head.php');
echo $out;
echo '<div class="bmenu"><a href="../index.php?act=cab">Кабинет</a></div>';