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

	$start = isset($_POST['start']) ? intval($_POST['start']) : 0;
	$status = isset($_POST['status']) ? $_POST['status'] : '1';

	if($status != '1')
		$status = '2';

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

	$query = $status == '1' ? 'author' : 'closed';

	$tickets = $pdo->query('SELECT `tickets`.`id`, `tickets`.`name`, `tickets`.`date`, `tickets`.`last_answer`, `tickets`.`'.$query.'`, `users`.`login` FROM `tickets` LEFT JOIN `users` ON `tickets`.`'.$query.'`=`users`.`id` WHERE `tickets`.`status`="'.$status.'" ORDER BY `tickets`.`last_answer` DESC LIMIT '.($start*20).', 20');
			 $tickets->setFetchMode(PDO::FETCH_OBJ);

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

	$i = $start*20;

	while($ticket = $tickets->fetch())
	{
		$tpl->load_template('tickets.tpl');
			$tpl->set('{i}', ++$i);
			$tpl->set('{id}', $ticket->id);
			$tpl->set('{name}', $ticket->name);
			$tpl->set('{act}', $status == '1' ? $ticket->author : $ticket->closed);
			$tpl->set('{login}', $ticket->login);
			$tpl->set('{last_answer}', expand_date($ticket->last_answer, 7));
			$tpl->set('{date}', expand_date($ticket->date, 7));
		$tpl->compile('content');
	}

	if($status == '2')
	{
		$tickets = $pdo->query('SELECT `id` FROM `tickets` WHERE `status`="2"');
		$all = count($tickets->fetchAll());

		if(($start*20) < $all)
		{
			$tpl->load_template('tickets_next.tpl');
				$tpl->set('{next}', ++$start);
			$tpl->compile('content');
		}

		if($start && $tpl->result['content'] == '')
		{
			$tpl->load_template('tickets_full.tpl');
			$tpl->compile('content');
		}
	}

	if(!$start && $tpl->result['content'] == '')
	{
		$tpl->load_template('content_none.tpl');
			$tpl->set('{text}', 'Список тикетов пуст');
		$tpl->compile('content');
	}

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