<?php
include_once("class/class.MySQL.php");
include_once("class/class.Message.php");
$db	=new MySQL();
$msg = new messaging();
//test 
$action = $_GET['action'];


if($action == "listEmp"):
	$search = $_GET['search'];
	$employees = $msg->listEmployee($search);
	

	echo '{"employees":'.json_encode($employees).'}';

elseif($action == "updateStatus"):

	//Update user online status	

elseif($action == 'getMessages'): // get All messages from selected employees

	$fromid = $_POST['fromid'];
	$toid	= $_POST['toid'];
	$lastid = $_POST['lastid'];
	$conversationid    = $_POST['cid'];
	
	if(!isset($_POST['cid']) || $_POST['cid']==''){
		$conversationid = $msg->getConversation($fromid,$toid,''); // get conversation id for get all messages.
 	}
	
	$messages = $msg->getMessages($fromid,$conversationid,10,$lastid); // fetch all messages. to $messages
	//$messages = sort($messages);
	foreach($messages as $mssg){
		if($mssg['user_id_fk']!=$fromid){
			$msg->updateStatus($mssg['cr_id']);	
		}
	}	
	if(!isset($_POST['cid']) || $_POST['cid']==''){
		$messages = array_reverse($messages);
	}else{
		$messages = $messages;
	}
	echo '{"messages":'.json_encode($messages).'}';


elseif($action == 'getNewMsg'): // get new message. 

	$user		 = $_POST['fromid'];

	if($latest){
		$latest	=$latest;
	}else{
		$latest='';
	}
			
	$messages = $msg->getMessagesNew($user);
	
	foreach($messages as $mssg){
		if($mssg['user_id_fk']!=$user){
			$msg->updateStatus($mssg['cr_id']);	
		}
	}	
	
	
	$userOnline = $msg->userOnline($user);
	if(count($messages) > 0){
	$messages[count($messages)-1]["useronline"] =$userOnline; 
	}else{
	$messages[0]["useronline"] =$userOnline; 
	}
	echo '{"messages":'.json_encode($messages).'}';	

elseif($action =='sendReply'): // Send reply.
	
	$data['from'] = $_POST['from'];
	$data['to'] = $_POST['toid'];
	$data['message'] = $_POST['message'];
	$messages = $msg->createConversation($data);
	
	

	$messages[0]['user_one'] = $data['to'];
	$messages[0]['reply']	 = $data['message'];
	$messages[0]['user_id_fk'] = $data['from'];
	$messages[0]['msgtime'] = time();
	echo '{"messages":'.json_encode($messages).'}';	

elseif($action == 'deleteMsg'):



endif;












	
?>