<?php
	require_once("../system.engine/system.core.php");
	$l->setPrefix("ajax.handle.notifications.messages");
	
	$mPong = array();
	$a = &$mPong;
	$p = &$_POST;
	
	global $systemHandler;
	$systemExecution = $systemHandler->loadHandler("EXECUTION");
	$systemHash = $systemHandler->loadHandler("HASH");
	/* ### DO YOUR CODES ONLY FROM HERE ### */
	$a["containerHTML"] = null;
	$mCount = 0;
	
	$mQuery = $systemExecution->runQuery("SELECT id, user_one, user_two FROM web_messages WHERE user_one = '%s' OR user_two = '%s' ORDER BY id DESC LIMIT 10", array($systemHandler->loadHandler("USER")->mUserId, $systemHandler->loadHandler("USER")->mUserId));
	$mChatMessageCollection = array();
	while($mRow = $mQuery->fetch_assoc()) {
		$mSenderUserId = $mRow["user_one"] == $systemHandler->loadHandler("USER")->mUserId ? $mRow["user_two"] : $mRow["user_one"];
		if(!array_key_exists($mSenderUserId, $mChatMessageCollection))
			$mChatMessageCollection[$mSenderUserId] = array();
		array_push($mChatMessageCollection[$mSenderUserId], $mRow["id"]);
	}
	
	foreach($mChatMessageCollection as $mKey => $mValue) {
		$mSenderUser = new systemUSER($mKey);
		$mChatMessage = $systemExecution->runQuery("SELECT * FROM web_messages WHERE id = '%s'", $mValue)->fetch_assoc();
		$a["containerHTML"] .= '<li>
								<a href="javascript:;" data-event="initialize-chat" data-parameter="'.$mSenderUser->mUserId.'">
									<div class="row black">
										<div class="col-md-2 col-xs-2">
											<img src="'.$mSenderUser->mProfilePicture.'" class="notificationPicture thumbnail" />
										</div>
										<div class="col-md-10 col-xs-10 textWrap">
											<b>'.$mSenderUser->mFullname.'</b>
												<br />
											'.htmlspecialchars(strlen($mChatMessage["message"]) < 85 ? $mChatMessage["message"] : substr($mChatMessage["message"], 0, 85)."..").'
												<br />
											<span class="timeAgo">'.$systemCore->timeAgo($mChatMessage["submit_date"]).'</span>
										</div>
									</div>
								</a>
							</li>';
		$mCount++;
	}
	
	if($mCount == 0)
		$a["containerHTML"] .= "<li><center>".$l->getValue("nomessages")."</center></li>";
	
	/* ### DO NOT CHANGE ANYTHING FROM HERE ### */
	header("Content-Type: application/json");
	echo json_encode($mPong);
?>