<?php

if (!empty($_POST['text']))
{

	if ($array_user['access_mail'] == 1) if (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `friends` WHERE `user_id` = '".$id."' AND `friend_id` = '".$user_id."' LIMIT 1"),0) == false) exit;

	if ($array_user['ban'] == 1) go(URL.'/?id='.$array_user['id']);
	
	$text = check($_POST['text']);
	$text = substr($text, 0, 10000);
	if (empty($text)) go(URL.'/mail/?id='.$id);

	$create_dialog = false;
	if (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `mail_dialog` WHERE `for_id` = '".$user_id."' AND `from_id` = '".$id."' LIMIT 1"),0) == false)
	{
		if (mysql_query("INSERT INTO `mail_dialog` SET
		`for_id` = '".$id."',
		`from_id` = '".$user_id."',
		`text` = '".mb_substr($text, 0, 100, 'UTF-8')."',
		`from` = '".$user_id."',
		`np` = 1,
		`count` = 1,
		`dir` = '".$user_id.$id."',
		`time` = '".time()."'") == true)
		{
			if (mysql_query("INSERT INTO `mail_dialog` SET
			`for_id` = '".$user_id."',
			`from_id` = '".$id."',
			`text` = '".mb_substr($text, 0, 100, 'UTF-8')."',
			`from` = '".$user_id."',
			`np` = 1,
			`dir` = '".$user_id.$id."',
			`time` = '".time()."'") == true)
			{
				$create_dialog = true;
			}
		}
	}
	else
	{
		$create_dialog = true;
		mysql_query("UPDATE `mail_dialog` SET `text` = '".mb_substr($text, 0, 100, 'UTF-8')."', `from` = '".$user_id."', `np` = 1, `time` = '".time()."', `del` = 0 WHERE `for_id` = '".$user_id."' AND `from_id` = '".$id."' LIMIT 1");
		mysql_query("UPDATE `mail_dialog` SET `text` = '".mb_substr($text, 0, 100, 'UTF-8')."', `from` = '".$user_id."', `np` = 1, count=count+1, `time` = '".time()."', `del` = 0 WHERE `for_id` = '".$id."' AND `from_id` = '".$user_id."' LIMIT 1");
	}

	if ($create_dialog == true)
	{

		$array_dialog = mysql_fetch_array(mysql_query("SELECT * FROM `mail_dialog` WHERE `for_id` = '".$user_id."' AND `from_id` = '".$id."' LIMIT 1"));
		if ($array_dialog['count_cache'] > 0) mysql_query("UPDATE `mail_dialog` SET `count_cache` = 0, `cache_photos` = '' WHERE `for_id` = '".$user_id."' AND `from_id` = '".$id."' LIMIT 1");

		if (mysql_query("INSERT INTO `mail_msg` SET
		`for_id` = '".$id."',
		`from_id` = '".$user_id."',
		`text` = '".$text."',
		`photos` = '".$array_dialog['cache_photos']."',
		`time` = '".time()."',
		`np` = 1
		") == true)
		{
			mysql_query("UPDATE `users` SET `notifications` = 1, notifications_mail=notifications_mail+1 WHERE `id` = '".$id."'");
		}
	}
}

?>