<?php

include "../../connection.php";


/*
 * vymysliet anieco aby to nemohol natlacit nico ine!
*/
if (isset($_POST['primatel'])  ) {
	if ( isset($_POST['odosielatel']) && !empty($_POST['odosielatel']))  nacitaj($_POST['primatel'],$_POST['odosielatel']);
	else nacitaj($_POST['primatel']);
}

if (isset($_POST['odosli'])  ) {
	send_message($_POST['id'], $_POST['komu'] , "" ,$_POST['text']); 
}


function nacitaj($primatel, $odoslietatel=null){
	
	if ($odoslietatel!=null){
		//TODO add order by time...
		$q="SELECT * FROM `spravy` WHERE primatel=? AND odosielatel=?";
		$q2 = queryWithBids($q, array($primatel,$odoslietatel));
	}
	else {
		$q = "SELECT * FROM `spravy` WHERE primatel=? AND precitane<0;";
		$q2 = queryWithBids($q, array($primatel));
	}
	
	/*
	 * zober neprecitane spravy
	*/

	$res=$q2->fetchAll();
	echo json_encode($res);

	/*
	 * oznac ich ako precitane
	*/
	$q = "UPDATE `spravy` SET `precitane`=1 WHERE primatel=? AND precitane<0;";
	$q2 = queryWithBids($q, array($primatel));
}


function send_message($id,$komu, $predmet,$text){
	$sql= "INSERT INTO `spravy`
			( `id` , `odosielatel` , `predmet` , `text` , `precitane` , `primatel` , `datum_odoslania`)
			VALUES ( NULL , ?, ?, ?, -1, ?, ?); ";

	queryWithBids($sql, array($id,$predmet,$text,$komu,date('Y-m-d H:i:s') ) );
}

?>
