<?php
	header('X-Frame-Options: DENY');
	header('X-XSS-Protection: 1; mode=block');
	header('Content-Type: text/html; charset=utf-8');

	include('../../../inc/start.php');
	include('../../../inc/protect.php');

	if(!isset($_POST['token']) || $_SESSION['token'] != clean($_POST['token'], null))
		exit(json_encode(array('status' => 'error', 'text' => 'Неверный токен')));

	$conf->time_zone = isset($conf->time_zone) ? $conf->time_zone : 'Europe/Moscow';

	date_default_timezone_set($conf->time_zone);

	$tpl = new Template;
	$tpl->dir = '../tpl/ajax/chat/';

	function msglist($msgs)
	{
		global $tpl, $pdo;

		$users_groups = get_groups($pdo);

		$tpl->result['content'] = '';

		foreach($msgs as $i => $msg)
		{
			$users = $pdo->query('SELECT `login`, `avatar`, `rights` FROM `users` WHERE `id`="'.$msg->user_id.'" LIMIT 1'); 
				$users->setFetchMode(PDO::FETCH_OBJ);

			$user = $users->fetch();

			$date = expand_date($msg->message_date, 8);

			$tpl->load_template('msg.tpl');
				$tpl->set('{id}', $msg->id);
				$tpl->set('{user}', $msg->user_id);
				$tpl->set('{date}', $date['full']);
				$tpl->set('{time}', $date['short']);
				$tpl->set('{text}', $msg->message_text);
				$tpl->set('{login}', $user->login);
				$tpl->set('{avatar}', $user->avatar);
				$tpl->set('{gp_name}', $users_groups[$user->rights]['name']);
				$tpl->set('{gp_color}', $users_groups[$user->rights]['color']);
				$tpl->set('{gp_rights}', $users_groups[$_SESSION['rights']]['rights']);
			$tpl->compile('content');
		}

		if(count($msgs) != 50)
			$tpl->result['content'] .= '<script>$("#load_val").val(0)</script>';

		$tpl->show($tpl->result['content']);
	}

	if(isset($_POST['lastmsg']))
	{
		$msgs = $pdo->query('SELECT * FROM `chat` ORDER BY `id` DESC LIMIT 50');
				$msgs->setFetchMode(PDO::FETCH_OBJ);

		msglist(array_reverse($msgs->fetchAll()));
	}

	if(isset($_POST['topmsg']))
	{
		$start = isset($_POST['start']) ? intval($_POST['start'])*50 : 0;

		if(!$start)
			exit;

		$msgs = $pdo->query('SELECT * FROM `chat` ORDER BY `id` DESC LIMIT '.$start.', 50');
				$msgs->setFetchMode(PDO::FETCH_OBJ);

		msglist(array_reverse($msgs->fetchAll()));
	}

	if(isset($_POST['sendmsg']))
	{
		if(!$_SESSION['id'])
			exit;

		$text = check($_POST['text'], null);

		if(!$text || $text == 'undefined')
			exit;

		include('../../../inc/protect.php');

		$query = $pdo->query('SELECT `rights` FROM `users` WHERE `id`="'.$_SESSION['id'].'" LIMIT 1');
				 $query->setFetchMode(PDO::FETCH_OBJ);

		$sender = $query->fetch();

		$users_groups = get_groups($pdo);

		if((strripos($users_groups[$sender->rights]['rights'], 'z') !== false) || (strripos($users_groups[$sender->rights]['rights'], 'x') !== false))
			exit;

		$text = find_img_mp3($text, $_SESSION['id']);

		$pdo->query('INSERT INTO `chat` set `user_id`="'.$_SESSION['id'].'", `message_text`="'.addslashes($text).'", `message_date`="'.date('Y-m-d H:i:s').'"');

		exit;
	}

	exit;
?>