<?php
	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' => 'Неверный токен')));

	$limit = isset($_POST['limit']) ? intval($_POST['limit']) : 4;
	$limit = $limit > 3 ? $limit : 4;

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

	$es = new EventsRibbon();

	$events = $pdo->query('SELECT `id`, `type`, `access`, `date`, `link`, `data_id`, `author` FROM `events` WHERE (`type`="4" OR `type`="5") ORDER BY `date` DESC LIMIT '.$limit); 
			 $events->setFetchMode(PDO::FETCH_OBJ);

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

	while($event = $events->fetch())
	{
		if(!$es->have_rights($event->access))
			continue;

		$users = $pdo->query('SELECT `login` FROM `users` WHERE `id`="'.$event->author.'" LIMIT 1'); 
				$users->setFetchMode(PDO::FETCH_OBJ);

		$user = $users->fetch();

		$query = $event->type == 4 
				 ? 'SELECT `name` FROM `forums__topics` WHERE `id`="'.$event->data_id.'" LIMIT 1'
				 : 'SELECT `forums__topics`.`name` FROM `forums__messages` LEFT JOIN `forums__topics` ON `forums__messages`.`topic`=`forums__topics`.`id` WHERE `forums__messages`.`id`="'.$event->data_id.'" LIMIT 1';

		$topics = $pdo->query($query);
				  $topics->setFetchMode(PDO::FETCH_OBJ);

		$topic = $topics->fetch();

		$tpl->load_template('lastforum.tpl');
			$tpl->set('{id}', $event->id);
			$tpl->set('{user}', $event->author);
			$tpl->set('{login}', $user->login);
			$tpl->set('{name}', $topic->name);
			$tpl->set('{date}', expand_date($event->date, 2));
			$tpl->set('{link}', $event->link);
		$tpl->compile('content');
	}

	echo $tpl->result['content'];
?>