<?php

include 'jaxconfig.php';
include 'class/JaxChat.php';


$error = '';
$message = '';
$json = array();


// determine the ajax action to perform
if( !empty($_GET['ajaxAction']) ) $action = $_GET['ajaxAction'];
else $action = '';

// process action
switch($action) {
	
	// user name request
	case 'requestName':
	// get name value
	if( !empty($_GET['name']) ) $name = trim($_GET['name']);//trim(htmlspecialchars(strip_tags($_GET['name'])));
	else $name = '';
	
	
	// if provided name is not valid then return error
	if( empty($name) ) {
		$error = 'Nome inválido!';
	}
	else {
		// create a jax chat object and request the name
		$jc = new JaxChat;
		$request = $jc->requestName($name, $_SERVER['REMOTE_ADDR']);
		
		if( $request === FALSE ) {
			// request failed, get the error message
			$error = $jc->getError();
		}
		else {
			// send back the name returned by the jax chat object
			$json['name'] = $request['name'];
			$json['id'] = $request['id'];
			
			// get welcome messages
			$messagesList = $jc->getMessagesTemplate('hello');
			if ($messagesList === FALSE) {
				$error = 'Falha ao obter o template!';
			}
			else {
				$json['appendMessages'] = $messagesList;
			}
		}
	}
	break;
	
	
	// chat message get
	case 'getMessages':
	$jc = new JaxChat;
	
	// a chat message may be included
	if (!empty($_GET['message'])) {
		if (($userDetails = $jc->validateClient($_GET['name'], $_GET['id'])) !== FALSE) {
			// client is valid, record message if acceptable
			$message = trim(base64_decode($_GET['message']));
			if (!empty($message)) {
				$saved = $jc->saveMessage($_GET['name'], $_GET['id'], $message, $userDetails['cssClass'], $_GET['messageNonce']);
				if ($saved === FALSE) $error = $jc->getError();
				else $json['messageReceived'] = TRUE;
			}
			else $saved = FALSE;
			
			// if saved is an object then assume a message list was returned
			if (is_object($saved)) {
				// assuming a message list returned by a user command
				$json['appendMessages'] = $saved;
			}
			else {
				// get messages
				if( isset($_GET['lastTime']) && isset($_GET['lastId']) ) {
					// client is requesting append from last message
					$messages = $jc->getMessages($_GET['lastTime'], $_GET['lastId']);
					if( $messages === FALSE) {
						$error = 'Falha ao obter mensagens!';
					}
					else {
						$json['appendMessages'] = $messages;
					}
				}
				else {
					// client requesting full messages
					$messages = $jc->getMessages();
					if( $messages === FALSE) {
						$error = 'Falha ao obter mensagens!';
					}
					else {
						$json['appendMessages'] = $messages;
					}
				}
				
				// get names
				$names = $jc->getNamesList();
				if ($names === FALSE) {
					$error = 'Falha ao obter nomes!';
				}
				else {
					$json['names'] = array('names' => $names->names, 'classes' => $names->classes);
				}
			}
		}
		else {
			// client is not valid, send timeout
			$json['timeout'] = 1;
			$error = $jc->getError();
		}
	}
	elseif (!empty($_GET['getWelcome'])) {
		// welcome message requested
		$messages = $jc->getMessagesTemplate('welcome');
		if ($messages !== FALSE) {
			$json['appendMessages'] = $messages;
		}
		else {
			$error = $jc->getError();
		}
	}
	else {
		$valid = TRUE;
		
		// if name and id provided then validate client
		if( !empty($_GET['name']) && !empty($_GET['id']) ) {
			$valid = $jc->validateClient($_GET['name'], $_GET['id']);
		}
		
		if( $valid ) {
			if( isset($_GET['lastTime']) && isset($_GET['lastId']) ) {
				// client is requesting append from last message
				$messages = $jc->getMessages($_GET['lastTime'], $_GET['lastId']);
				if( $messages === FALSE) {
					$error = 'Falha ao obter mensagens!';
				}
				else {
					$json['appendMessages'] = $messages;
				}
			}
			else {
				// client requesting full messages
				$messages = $jc->getMessages();
				if( $messages === FALSE) {
					$error = 'Falha ao obter mensagens!';
				}
				else {
					$json['appendMessages'] = $messages;
				}
			}
			
			// get names
			$names = $jc->getNamesList();
			if ($names === FALSE) {
				$error = 'Falha ao obter nomes!';
			}
			else {
				$json['names'] = array('names' => $names->names, 'classes' => $names->classes);
			}
		}
		else {
			// client is not valid, send timeout
			$json['timeout'] = 1;
			$error = $jc->getError();
		}
	}
	break;
	
	
	// ajax request unknown
	default:
	$error = 'Comando desconhecido!';
	break;	
}


// make sure json is not cached
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

$json['error'] = $error;
$json['message'] = $message;
echo json_encode($json);


