<?php

$paginate = 1;
$title = 'Почта';
$load = array('f_smiles','user');
include_once '../protected/sys.php';

if (!$user)
{
	header("Location:/");
	exit;
}

if ($user['save'] == 0)
{
	$_SESSION['error'] ='Сохранитесь для общения в почте!';
	header("location:/");
	exit;
}

if(isset($_GET['get'])){
	$id = intval($_GET['id']);
	$c = $db->rows('SELECT * FROM `mail_group` WHERE (`u1` = ? OR `u2` = ?) AND (`u1` = ? OR `u2` = ?) LIMIT 1', array($user['id'],$user['id'],$id,$id));
	if(!empty($id)){
		if($c == 0){
			$db->query('INSERT INTO `mail_group` SET `u1` = ?, `u2` = ?, `time` = ?',array($user['id'],$id,time()));
			header('location: /mail/index.php?get&id='.$id);
		} else {
			$g = $db->fetch('SELECT * FROM `mail_group` WHERE (`u1` = ? OR `u2` = ?) AND (`u1` = ? OR `u2` = ?) LIMIT 1', array($user['id'],$user['id'],$id,$id));
			header('location: /mail/index.php?group='.$g['id']);
		}
	}
}



if(isset($_GET['group'])){
	$id = intval($_GET['group']);
	$g = $db->fetch("SELECT * FROM `mail_group` WHERE `id`=? LIMIT 1",array($id));
	if($g['u1'] != $user['id'] AND $g['u2'] != $user['id']) {
		header('locaion: /mail/index.php');
	}


	if(isset($_GET['set'])){
		$mail = smiles(htmlspecialchars($_POST['msg']));
		$db->query('INSERT INTO `mail` SET `text` = ?, `id_g` = ?, `user` = ?, `time` =?',array($mail,$id,$user['id'],time()));
		
		$db->query('UPDATE `mail_group` SET `time` = ?, `read` = ? WHERE `id` = ? ',array(time(),1,$id));
		
		if($g['u1'] == $user['id']){
			$colum = 'u2';
		} else {
			$colum = 'u1';
		}
		$us = $db->fetch('SELECT `id`,`read_id` FROM `users` WHERE `id`=? LIMIT 1',array($g[$colum]));
		if (preg_match("/,".$id.",/", $us['read_id'])) {
    		$set = $us['read_id'];
		} else {
    		$set = $us['read_id'].','.$id.',';
		}

		$db->query('UPDATE `users` SET `read` = ?, `read_id`=? WHERE `id`=?',array(1,$set,$us['id']));
		



	}

	$c = 10;
	$k_post = $db->rows("SELECT * FROM `mail` WHERE `id_g` = ?",array($id));
	$k_page = k_page($k_post,$c);
	$page = page($k_page);
	$start = $c*$page-$c;


	$db->offEmulate();

	$mails = $db->fetchAll('SELECT * FROM `mail` WHERE `id_g` = ?  ORDER BY `id` DESC LIMIT ?,?',array($id,$start,$c));
	?> 
	<center> 
	<div id="smilles" style="display:none;">
<div style="text-align: center;" class="close">Скрыть</div>
<?

	$smilesAll = array(
  array('id' => '1','name' => '','mark' => ':ag'),
  array('id' => '2','name' => '','mark' => ':beee'),
  array('id' => '3','name' => '','mark' => ':dance'),
  array('id' => '4','name' => '','mark' => ':grust'),
  array('id' => '5','name' => '','mark' => ':krutoi'),
  array('id' => '6','name' => '','mark' => ':nono'),
  array('id' => '7','name' => '','mark' => ':rzhu'),
  array('id' => '8','name' => '','mark' => ':super'),
  array('id' => '9','name' => '','mark' => ':ulibka'),
  array('id' => '10','name' => '','mark' => ':vsemprivet')
);


	foreach ($smilesAll as $sm) {
	 echo '<img style="padding:5px;" src="/imgData/smiles/'.$sm['id'].'.png" data-mark="'.$sm['mark'].'" id="smile">';
	}

?>	
</div>
<div class="menu">


	<form action="?set&group=<?=$id?>" method="POST">
		<textarea name="msg" placeholder="Ваше сообщение"></textarea><br>
		<button class="button green">Отправить</button>
		<img id="bt" src="/imgData/smiles/9.png">
	</form></center></div>
 	<div class='menu'>
   <?
   foreach ($mails as $m) {
   if($m['read'] == 0){
   		$read = 'no-read';
   		if($m['user'] != $user['id']){
   			$db->query('UPDATE `mail` SET `read`= ? WHERE `id` = ? ',array(1,$m['id']));
   			
   			$set = str_replace(','.$id.',','',$user['read_id']);
   			$db->query('UPDATE `users` SET `read` = ?, `read_id` = ? WHERE `id`=?',array(0,$set,$user['id'])); 
   		}
   } else {
   		$read = 'read';
   }
   if($m['user'] == $user['id']){
   		$align = 'right';
   		$color = '#ff0';
   	} else {
   		$align = 'left';
   		$color = '#00F742';
   	}
   	$us = $db->fetch('SELECT `id`,`login` FROM `users` WHERE `id`=?',array($m['user']));
   	?>
   		<div class='<?=$read?>' style="text-align: <?=$align?>;"><a href='/user?id=<?=$us['id']?>'><?=$us['login']?><a><div style='color: <?=$color?> !important;'> <?=$m['text']?></div> </a></div>
	<?
   	}
   	?> </div> <?
str('?group='.$id.'&',$k_page,$page,NULL);
} else {
$c = 10;
$k_post = $db->rows("SELECT * FROM `mail_group` WHERE `u1` = ? OR `u2` = ?",array($user['id'],$user['id']));
$k_page = k_page($k_post,$c);
$page = page($k_page);
$start = $c*$page-$c;

$db->offEmulate();
$mail_groups = $db->fetchAll("SELECT * FROM `mail_group` WHERE `u1` = ? OR `u2` = ? ORDER BY `time` DESC LIMIT ?,?", array($user['id'],$user['id'],$start,$c));
echo '<div class="menu">';
foreach($mail_groups as $mg){
		if (preg_match("/,".$mg['id'].",/", $user['read_id'])) {
    		$div = '<font color="red">[Не прочитано]</font>';
		} else {
    		$div = NULL;
		}

	if($mg['u1'] == $user['id']){
		$colum = 'u2';
	} else {
		$colum = 'u1';
	}
	
	$us = $db->fetch('SELECT `id`,`login` FROM `users` WHERE `id` = ? LIMIT 1',array($mg[$colum])); 
	

	echo '<a class="menu" href="?group='.$mg['id'].'">'.$us['login'].'</a> '.$div.' </li>';
}
echo "</div>";
str('',$k_page,$page,NULL);

}
?>
<script type="text/javascript">
	$('#bt').click( function() {
		$('#smilles').css('display','block');
	});

	$('.close').click( function() {
		$('#smilles').css('display','none');
	});

	$('img#smile').click( function(){

		var sm = $(this).data('mark');
		var val = $('textarea').val()+' '+sm;
		$('textarea').val(val);
	});

</script>
<?
include_once $config['root'].'/protected/footermain.php';