<?php
include_once ('core/base.php');
falseauth();

$header = 'Отправить сообщение';
include_once ('core/head.php');

$id = fl($_GET['id']);
$mess = $base -> query("SELECT * FROM `users` WHERE `id` = '".$id."' LIMIT 1") -> fetch_assoc();

if($id == $u['id']){
$_SESSION['message'] = 'Ошибка.';
header("Location: /mail/");
exit;
}

if(isset($mess['id']) or $u['id'] != $mess['id']) {
$contact = $base -> query("SELECT * FROM `message_c` WHERE `kogo` = '".$mess['id']."' and `kto` = '".$u['id']."' LIMIT 1")->num_rows;

if(isset($_POST['insert'])){
$msg = fl($_POST['msg']);
$tim = $base -> query("SELECT * FROM `message` WHERE `kto` = '".$u['id']."' ORDER BY `time` DESC")->fetch_assoc();

if(mb_strlen($msg) < '3' or mb_strlen($msg) > '500'){ $_SESSION['message'] = 'Сообщение должно содержать от 3 до 500 символов.';}
elseif((time()-$tim['time']) < 5) { $_SESSION['message'] = 'Сообщения можно писать один раз в 5 секунд.';}
else{

if($contact == 0) {
$base -> query("INSERT INTO `message_c` SET `kto` = '".$u['id']."', `kogo` = '".$mess['id']."', `time` = '".time()."', `posl_time` = '".time()."'");
$base -> query("INSERT INTO `message_c` SET `kto` = '".$mess['id']."', `kogo` = '".$u['id']."', `time` = '".time()."', `posl_time` = '".time()."'");
}
$base->query("UPDATE `message_c` SET `posl_time`='".time()."' WHERE `kogo` = '".$u['id']."' and `kto`='".$id."' limit 1");
$base->query("UPDATE `message_c` SET `posl_time`='".time()."' WHERE `kto` = '".$u['id']."' and `kogo`='".$id."' limit 1");
$base->query("INSERT INTO `message` SET `text` = '".$msg."', `kto` = '".$u['id']."', `komy` = '".$mess['id']."', `time` = '".time()."', `readlen` = '0'");

header('Location: /dialog/'.$mess['id'].'/');
exit;
}
}

echo '<div class="b">';

echo '<div class="title">Отправить сообщение</div>';

echo '<center><form action="" method="POST">Получатель: '.name($mess['id']).'<br/>
<textarea name="msg"></textarea><br/>
<center><input type="submit" value="Отправить" name="insert"/></center>
</form></center>';

echo '<a class="btn" href="javascript:history.go(-1)"><img src="/images/icons/back.png"> Назад</a>';

echo '</div>';

}else{

$_SESSION['message'] = 'Ошибка.';
header('Location: /mail/');
exit;

}


include_once ('core/foot.php');
?>