<?php
	require_once("../system.engine/system.core.php");
	
	$mPong = array();
	$a = &$mPong;
	$p = &$_POST;
	
	global $systemHandler;
	$systemExecution = $systemHandler->loadHandler("EXECUTION");
	$systemHash = $systemHandler->loadHandler("HASH");
	$systemSmilies = $systemHandler->loadHandler("SMILIES");
	/* ### DO YOUR CODES ONLY FROM HERE ### */

	$mSenderUser = $systemHandler->loadHandler("USER")->mUserId;
	$mReceiverUser = $p["receiverUser"];
	
	$systemExecution->runQuery("UPDATE web_messages SET message_seen_user = '1' WHERE user_two = '%s' AND message_seen_user = '0'", array($mSenderUser, $mSenderUser));
	
	$a["chatContent"] = array();
	
	$mQuery = $systemExecution->runQuery("SELECT * FROM web_messages WHERE (user_one = '%s' AND user_two = '%s') OR (user_two = '%s' AND user_one = '%s') ORDER BY submit_date DESC LIMIT 15", array($mSenderUser, $mReceiverUser, $mSenderUser, $mReceiverUser));
	while($mRow = $mQuery->fetch_assoc()) {
		$mOwnMessage = $mRow["user_one"] == $mSenderUser;
		$mUser = new systemUSER($mOwnMessage ? $mSenderUser : $mRow["user_one"]);

		if($mOwnMessage)
			array_push($a["chatContent"], "<div class=\"row msg_container base_sent\">
							<div class=\"col-md-10 col-xs-10\">
								<div class=\"messages msg_sent\">
									<p data-location=\"chat-message\" class=\"messageContent-".$mReceiverUser."\">".$systemSmilies->initializeSmilies($mRow["message"], true)."<div class=\"tinyTime\">".$systemCore->timeAgo($mRow["submit_date"])."</div></p>
								</div>
							</div>
							<div class=\"col-md-2 col-xs-2 avatar\">
								<a href=\"page.profile.php?profile-id=".$mUser->mUserId."\"><img src=\"".$mUser->mProfilePicture."\" class=\"with-border img-responsive \"></a>
							</div>
						</div>");
		else
			array_push($a["chatContent"], "<div class=\"row msg_container base_receiver\">
							<div class=\"col-md-2 col-xs-2 avatar\">
								<a href=\"page.profile.php?profile-id=".$mUser->mUserId."\"><img src=\"".$mUser->mProfilePicture."\" class=\"with-border img-responsive \"></a>
							</div>
							<div class=\"col-md-10 col-xs-10\">
								<div class=\"messages msg_receive\">
									<p data-location=\"chat-message\" class=\"messageContent-".$mReceiverUser."\">".$systemSmilies->initializeSmilies($mRow["message"], true)."<div class=\"tinyTime\">".$systemCore->timeAgo($mRow["submit_date"])."</div></p>
								</div>
							</div>
						</div>");
	}
	
	$mEPong = null;
	for($i = count($a["chatContent"]); $i > 0; $i--)
		$mEPong .= $a["chatContent"][$i - 1];
	
	/* ### DO NOT CHANGE ANYTHING FROM HERE ### */
	header("Content-Type: application/json");
	echo json_encode(array("chatContent" => $mEPong));
?>