<?php
require_once "sql.php";

$where = "";
$array = array();

if(isset($_GET['ids']))
{
	$ids = explode(",", $_GET['ids']);
	$where = "WHERE id=0";
	foreach($ids as $id)
	{
		$id = trim($id);
		if($id != "")
		{
			$id = intval($id);
			if($id <= 0)
				error("Invalid ids");
			$array[] = $id;
			$where = $where." OR id=?";
		}
	}
	if(count($array) == 0)
		$where = "";
}
else if(isset($_GET['lastMessages']))
{
	$l = intval($_GET['lastMessages']);
	if($l <= 0)
		error("Invalid last messages");
	$where = "ORDER BY id DESC LIMIT $l OFFSET 0";
}
else if(isset($_GET['lastMessagesTime']))
{
	$l = intval($_GET['lastMessagesTime']);
	if($l <= 0)
		error("Invalid last time messages");
	$where = "WHERE time>=:time";
	$array = array(":time" => date("Y-m-d H:i:s", time() - $l));
}

$select = $db->prepare("SELECT * FROM sent ".$where);

if(!$select->execute($array))
	error("Unable to read messages");
$messages = array();
while($msg = $select->fetch())
	$messages[] = array("id" => intval($msg['id']), "recipient" => $msg['recipient'],
		"text" => $msg['text'], "time" => strtotime($msg['time']),
		"status" => intval($msg['status']), "gate" => intval($msg['gate']),
		"timeStatus" => $msg['timeStatus'] ? strtotime($msg['timeStatus']) : 0);

echo json_encode(array("timestamp" => time(), "messages" => $messages));
?>