<?php

include 'system/sys.php';
include 'system/funcs.php';

if (!isset ($us)) {
        header ('location: /'); 
        exit;
}

if (!isset ($_GET['u'])) {
        header ('location: /mail.php'); 
        exit;
}

$query = DB :: $dbs -> query ("SELECT * FROM `us` WHERE (`id`=?)", array ((int) $_GET['u']));
if ($query -> rowCount ()==0) {
        header ('location: /mail.php'); 
        exit;
}

$u = $query -> fetch ();

if ($u['id']==$us['id']) {
        header ('location: /mail.php');
        exit;
}

H ('Переписка с ' . $u['nick'], '<a href="/mail.php" style="color: white;">Почта</a>');
echo '<div class="panell"><table width="100%" cellpadding="0" cellspacing="0"><tr>';
                                echo '<td width="25%" align="center"><a href="/kab"><img src="/images/menu/upanel.png"></a></td>';
                                echo '<td width="25%" align="center"><a href="/mail.php"><img src="/images/menu/message.png"> ' . ($n_m != 0 ? '<span class="coun">+' . $n_m . '</span>' : '') . '</a></td>';
                                echo '<td width="25%" align="center"><a href="/action.php"><img src="/images/menu/lenta.png"> ' . ($n_a != 0 ? '<span class="coun">+' . $n_a . '</span>' : '') . '</a></td>';
                                echo '<td width="25%" align="center"><a href="/?exit"><img src="/images/menu/logout.png"></a></td>';
                                echo '</tr></table></div>';
      echo '<div class="menu"><a href="/mail.php" style="color: ffffff;">Почта</a> | Переписка с ' . $u['nick'], '</div>';
if (DB :: $dbs -> querySingle ("SELECT COUNT(*) FROM `poch` WHERE (`us`='" . $us['id'] . "') AND (`kem`='" . $u['id'] . "')") == 0) {
        DB :: $dbs -> query ("INSERT INTO `poch` (`us`,`kem`,`last`) VALUES ('" . $us['id'] . "','" . $u['id'] . "','" . time () . "')");
        echo '<div class="list1">Контакт успешно добавлен...</div>';
}

if (DB :: $dbs -> querySingle ("SELECT COUNT(*) FROM `poch` WHERE (`kem`='" . $us['id'] . "') AND (`us`='" . $u['id'] . "')") == 0) {
        DB :: $dbs -> query ("INSERT INTO `poch` (`us`,`kem`,`last`) VALUES ('" . $u['id'] . "','" . $us['id'] . "','" . time () . "')");
}


if ($us['online']<3600) {
        echo '<div class="list1">Для того, чтобы писать личные сообщение провести на сайте 1 час!</div>';
}
else {

        $query = DB::$dbs->query ("SELECT * FROM `ignor` WHERE (`us`='" . $u['id'] . "') AND (`kem`='" . $us['id'] . "')");
        if ($query -> rowCount () != 0) {
                echo '<div class="list1">Вы не можете писать ' . uNick ($u['id']) . ' т.к он добавил Вас в свой игнор-лист!</div>';
        }
        else {

                $query = DB::$dbs->query ("SELECT * FROM `ignor` WHERE (`us`='" . $us['id'] . "') AND (`kem`='" . $u['id'] . "')");
                if ($query -> rowCount () != 0) {
                        echo '<div class="list1"><b style="red">Пользователь находится в вашем игнор-листе!</b></div>';
                }
            
            
                if (isset ($_GET['ignor'])) {
                        if ($query -> rowCount () != 0) {
                                DB :: $dbs -> query ("DELETE FROM `ignor` WHERE (`us`='" . $us['id'] . "') AND (`kem`='" . $u['id'] . "')");
                                header ('location: /msg' . $u['id']);
                                exit; 
                        }
                        else{
                                echo '<div class="lst">';
                                echo 'Вы уверены что хотите добавить ' . uNick ($u['id']) . ' в игнор-лист?<br/>';
                                echo '<a href="/msg' . $u['id'] . '?ignor=1"><img src="/images/yes.png" alt=""/></a> | <a href="/msg' . $u['id'] . '"><img src="/images/stop_2.png" alt=""/></a>';
                                echo '</div>';

                                if ($_GET['ignor'] == 1) {
                                        DB :: $dbs -> query ("insert into `ignor` (`us`,`kem`) values ('" . $us['id'] . "','" . $u['id'] . "')");
                                        echo '<div class="lst">' . uNick ($u['id']) . ' добавлен в ваш игнор-лист!</div>';
                                }
                        }
                }

                echo '<div class="list1">';
                echo '<form action="/msg' . $u['id'] . '" method="post" enctype="multipart/form-data">';
                echo 'Сообщение: (<a href="/msg' . $u['id'] . '">обн</a>/игнор [<a href="/msg' . $u['id'] . '?ignor">' . ($query -> rowCount () != 0 ? 'выкл' : 'вкл') . '</a>])<br/>';
                echo '<textarea name="text"></textarea><br/>';
                
                if ($us['file']==1) {
                        echo 'Файл:<br/><input type="file" name="filename"/><br/>';
                }
                
                echo '<input type="submit" value="Отправить" name="send"/>';
                echo '</div>';

                if (isset ($_POST['send'])) {
                
                        $_POST['text'] = htmlspecialchars (addslashes (trim ($_POST['text'])));        
                        if (DB :: $dbs -> querySingle ("SELECT COUNT(*) FROM `msg` WHERE (`kem`='" . $us['id'] . "') AND (`time`>'" . (time () - 30) . "')") != 0) {
                                                        echo '<div class="list1">Вы пишите слишком часто!</div>';
                        }
                        elseif (empty ($_POST['text'])) {
                                echo '<div class="list1">Вы не ввели текст сообщения..</div>';
                        }
                        else {
                        
                                $poch = DB :: $dbs -> queryFetch ("SELECT * FROM `poch` WHERE (`us`='" . $us['id'] . "') AND (`kem`='" . $u['id'] . "')");
                    
                                // 
                                $filename = NULL;
                                $ext = substr ($_FILES['filename']['name'], strrpos ($_FILES['filename']['name'], '.') + 1);  
                                if (in_array ($ext, array ('jpg','gif','png','jpeg','bmp','zip','rar','7z','txt','mp3','avi','mp4','3gp'))) {
                                        $filename = $us['id'] . '_' . passgen () . '.' . $ext;
                                        copy ($_FILES['filename']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/files/mail/' . $filename);
                                }
                                
                                if (isset ($_POST['resend'])) {
                                    
                                        if (!is_array ($_POST['resend'])) {
                                                header ('location: /msg.php?u='.$u['id']);
                                                exit;
                                        }   
                                        
                                        if (!isset ($_POST['kom'])) {
                                                header ('location: /msg.php?u='.$u['id']);
                                                exit;
                                        }
                                        
                                        $query = DB :: $dbs -> query ("SELECT * FROM `us` WHERE (`id`=?)", array ((int) $_POST['kom']));
                                        if ($query -> rowCount () ==0 ) {
                                                header ('location: /msg.php?u='.$u['id']);
                                                exit;
                                        }
                                        
                                        $kom = $query -> fetch ();
                                        if ($kom['id']==$us['id']) {
                                                header ('location: /msg.php?u='.$u['id']);
                                                exit;
                                        }
                                                            
                                        DB :: $dbs -> query ("INSERT INTO `msg` (`us`,`kem`,`text`,`time`,`poch`, `file`) VALUES ('" . $kom['id'] . "', '" . $us['id'] . "','" . $_POST['text'] . "', '" . time () . "', '". $poch['id'] . "', '" . $filename . "')");
                                            
                                        $msg = DB :: $dbs -> lastInsertId ();                
                                        
                                        foreach ($_POST['resend'] as $resend) {
                                                DB :: $dbs -> query ("INSERT INTO `msg_resend` (`msg`, `resend`) VALUES ('" . $msg . "', '" . $resend . "')");
                                        }
                                            
                                        header ('location: /msg' . $kom['id']);
                                        exit;
                                    
                                }

                                DB :: $dbs -> query ("INSERT INTO `msg` (`us`,`kem`,`text`,`time`,`poch`, `file`) VALUES ('" . $u['id'] . "', '" . $us['id'] . "','" . $_POST['text'] . "', '" . time () . "', '". $poch['id'] . "', '" . $filename . "')");
                                                
                                DB :: $dbs -> query ("UPDATE `poch` set `last`='" . time () . "' WHERE (`kem`='" . $us['id'] . "') AND (`us`='" . $u['id'] . "')");
                                DB :: $dbs -> query ("UPDATE `poch` set `last`='" . time () . "' WHERE (`us`='" . $us['id'] . "') AND (`kem`='" . $u['id'] . "')");
                                        
                                header ('location: /msg.php?u='.$u['id']);
                                exit;
                    
                        }
                
                }
        
        }

}

$items = DB :: $dbs -> querySingle ("SELECT COUNT(*) FROM `msg` WHERE (`us`='" . $us['id'] . "') AND (`kem`='" . $u['id'] . "') OR (`kem`='" . $us['id'] . "') AND (`us`='" . $u['id'] . "')");

$items_per_page = 10;
$pages = ceil ($items/$items_per_page);
$page = (int) $_GET['page'];

if ($page < 1)
    $page = 1;

if ($page > $pages)
    $page = $pages;
    
$start = $page * $items_per_page - $items_per_page;

if ($items == 0) {
        echo '<div class="lst">Сообщений нет..</div>'; 
}
else {
    
        if (isset ($_POST['resend'])) {

                if ( ! is_array ($_POST['resend'])) {
                        header ('location: /msg.php?u=' . $u['id']);
                        exit;
                }
                
                if (isset ($_POST['del'])) {
                    
                        if ($us['level']<$us['level']) {
                                header ('location: /msg.php?u=' . $u['id']);
                                exit;
                        }
                        
                        foreach ($_POST['resend'] as $resend) {
                                DB :: $dbs -> query ("DELETE FROM `msg` WHERE (`id`='" . $resend . "')");
                        }
                        
                        header ('location: /msg.php?u=' . $u['id']);
                    
                }
            
        }


        $q = DB :: $dbs -> query ("SELECT * FROM `msg` WHERE (`us`='" . $us['id'] . "') AND (`kem`='" . $u['id'] . "') OR (`kem`='" . $us['id'] . "') AND (`us`='" . $u['id'] . "') ORDER BY `time` DESC LIMIT $start, $items_per_page");
        while ($msg = $q -> fetch()) {
            
                echo '<div class="' . ($msg['see']==1?'lst':'list1') . '">';
                echo '<input type="checkbox" name="resend[]" value="' . $msg['id'] . '"/> ' . uNick ($msg['kem']) . ' [' . datef ($msg['time'])  .']<br/>' . bb ($msg['text']) . '<br/>';
                    
                DB :: $dbs -> query ("UPDATE `msg` SET `see`='0' WHERE (`us`='" . $us['id'] . "') AND (`kem`='" . $u['id'] . "') AND (`see`='1')");

                if (DB :: $dbs -> querySingle ("SELECT * FROM `msg_resend` WHERE (`msg`='" . $msg['id'] . "')")!=0) {
                    
                    echo '<div class="cit">';
                    
                    $qq = DB :: $dbs -> query ("SELECT * FROM `msg_resend` WHERE (`msg`='" . $msg['id'] . "') ORDER BY `id` DESC");
                    while ($msg_resend = $qq -> fetch ()) {
                            
                            $qqq = DB :: $dbs -> query ("SELECT * FROM `msg` WHERE (`id`='" . $msg_resend['resend'] . "')");
                            if ($qqq -> rowCount () != 0) {
                            
                                    $resend = $qqq -> fetch ();
                                    
                                    echo uNick ($resend['kem']) . ' (' . datef ($resend['time']) . ')<br/>' . bb ($resend['text']) . '<br/>';
                                    
                                    if (!empty ($resend['file'])) {
                                            echo 'Прикрепленный файл: <a href="/files/mail/' . $resend['file'] . '"><b>' . $resend['file'] . '</b></a> (' . sizef (filesize ('./files/mail/' . $resend['file'])) . ')<br/>';
                                     }
                                 
                            }
                            else {
                                    echo '<b>Сообщение удалено!</b><br/>';
                            }
                        
                    }
                    echo '</div>';
                
                }

                if (!empty ($msg['file'])) {
                    echo 'Прикрепленный файл: <a href="/files/mail/' . $msg['file'] . '"><b>' . $msg['file'] . '</b></a> (' . sizef (filesize ('./files/mail/' . $msg['file'])) . ')';
                }

                echo '</div>';

        }
        
        echo '<div class="lst">' . pages ('/msg' . $u['id']) . '</div>';

        echo '<div class="list1">';
        echo 'С выбранными:<br/>';
        echo 'ID: <input type="text" name="kom"/> <input type="submit" value="Переслать" name="send"/><br/>';

        if ($us['level']>$u['level']) {
                echo '<input type="submit" value="Удалить" name="del"/>';
        }
        
        echo '</div>';

}

echo '</form>';
echo '<div class="list1"><a href="/mail.php">Все диалоги</a></div>';

F ();

