<?
class chat extends Controller {

        function chat()
        {
                parent::Controller();
        }


/**
 * @author: Md. Golam Rabbany
 * @email: mgrnahid@gmail.com
 * @description: This function Default Page
 * @copyright 2011
 */
 

function index()
{

	if($this->clogin->is_logged_in())
	{

		redirect("admin/cpanel/index", "Location");

    }
    else
    {

		redirect("login/login_first", "Location");

	}

}




/**
 * @author: Md. Golam Rabbany
 * @email: mgrnahid@gmail.com
 * @description: This function Input Chat Type
 * @copyright 2011
 */
 

function getChatType($chatType = 'chatheartbeat')
{

	if($this->clogin->is_logged_in())
	{
			    	
		$_SESSION['username'] = $this->session->userdata('user_name');
		if($chatType == 'chatheartbeat')
		{
			$this->chatHeartbeat();
		}
		if($chatType == 'sendchat')
		{
			$this->sendChat();
		}
		if($chatType == 'closechat')
		{
			$this->closeChat();
		}
		if($chatType == 'startchatsession')
		{
			$this->startChatSession();
		}
		
		
		if (!isset($_SESSION['chatHistory']))
		{
			$_SESSION['chatHistory'] = array();
		}

		if (!isset($_SESSION['openChatBoxes'])) 
		{
			$_SESSION['openChatBoxes'] = array();
		}
							
    }
    else
    {

		redirect("login/login_first", "Location");

	}
}


/**
 * @author: Md. Golam Rabbany
 * @email: mgrnahid@gmail.com
 * @description: This function return chatHeartbeat
 * @copyright 2011
 */
 


function chatHeartbeat() 
{

	$this->clogin->is_logged_in();
	$_SESSION['username'] = $this->session->userdata('user_name');
	$user_name = $_SESSION['username'];
	$sql = "select * from chat_history where receiver = 'root' AND recd = 0 order by sent ASC";
	$items = '';

	$chatBoxes = array();

	while ($chat = mysql_fetch_array($query)) {

		if (!isset($_SESSION['openChatBoxes'][$chat['sender']]) && isset($_SESSION['chatHistory'][$chat['sender']])) {
			$items = $_SESSION['chatHistory'][$chat['sender']];
		}

		$chat['message'] = $this->sanitize($chat['message']);

		$items .= <<<EOD
					   {
			"s": "0",
			"f": "{$chat['sender']}",
			"m": "{$chat['message']}"
	   },
EOD;

	if (!isset($_SESSION['chatHistory'][$chat['sender']])) {
		$_SESSION['chatHistory'][$chat['sender']] = '';
	}

	$_SESSION['chatHistory'][$chat['sender']] .= <<<EOD
						   {
			"s": "0",
			"f": "{$chat['sender']}",
			"m": "{$chat['message']}"
	   },
EOD;

		unset($_SESSION['tsChatBoxes'][$chat['sender']]);
		$_SESSION['openChatBoxes'][$chat['sender']] = $chat['sent'];
	}


	if (!empty($_SESSION['openChatBoxes'])) {
	foreach ($_SESSION['openChatBoxes'] as $chatbox => $time) {
		if (!isset($_SESSION['tsChatBoxes'][$chatbox])) {
			$now = time()-strtotime($time);
			$time = date('g:iA M dS', strtotime($time));

			$message = "Sent at $time";
			if ($now > 180) {
				$items .= <<<EOD
{
"s": "2",
"f": "$chatbox",
"m": "{$message}"
},
EOD;

	if (!isset($_SESSION['chatHistory'][$chatbox])) {
		$_SESSION['chatHistory'][$chatbox] = '';
	}

	$_SESSION['chatHistory'][$chatbox] .= <<<EOD
		{
"s": "2",
"f": "$chatbox",
"m": "{$message}"
},
EOD;
			$_SESSION['tsChatBoxes'][$chatbox] = 1;
		}
		}
	}
}

	$sql = "update chat_history set recd = 1 where receiver = '$user_name' and recd = 0";
	$query = mysql_query($sql);

	if ($items != '') {
		$items = substr($items, 0, -1);
	}
	
	
header('Content-type: application/json');
?>
{
		"items": [
			<?php echo $items;?>
        ]
}

<?php
			exit(0);
}


/**
 * @author: Md. Golam Rabbany
 * @email: mgrnahid@gmail.com
 * @description: This function return chatBoxSession
 * @copyright 2011
 */
 

function chatBoxSession($chatbox) {

	$this->clogin->is_logged_in();
	$items = '';

	if (isset($_SESSION['chatHistory'][$chatbox])) {
		$items = $_SESSION['chatHistory'][$chatbox];
	}

	return $items;
}



/**
 * @author: Md. Golam Rabbany
 * @email: mgrnahid@gmail.com
 * @description: This function return startChatSession
 * @copyright 2011
 */
 
function startChatSession() {
	$this->clogin->is_logged_in();
	$_SESSION['username'] = $this->session->userdata('user_name');
	$items = '';
	if (!empty($_SESSION['openChatBoxes'])) {
		foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
			$items .= $this->chatBoxSession($chatbox);
		}
	}


	if ($items != '') {
		$items = substr($items, 0, -1);
	}

header('Content-type: application/json');
?>
{
		"username": "<?php echo $_SESSION['username'];?>",
		"items": [
			<?php echo $items;?>
        ]
}

<?php


	exit(0);
}



/**
 * @author: Md. Golam Rabbany
 * @email: mgrnahid@gmail.com
 * @description: This function return sendChat
 * @copyright 2011
 */
 
function sendChat() {
	$this->clogin->is_logged_in();
	$from = $_SESSION['username'];
	$to = $_POST['to'];
	$message = $_POST['message'];

	$_SESSION['openChatBoxes'][$_POST['to']] = date('Y-m-d H:i:s', time());

	$messagesan = $this->sanitize($message);

	if (!isset($_SESSION['chatHistory'][$_POST['to']])) {
		$_SESSION['chatHistory'][$_POST['to']] = '';
	}

	$_SESSION['chatHistory'][$_POST['to']] .= <<<EOD
					   {
			"s": "1",
			"f": "{$to}",
			"m": "{$messagesan}"
	   },
EOD;


	unset($_SESSION['tsChatBoxes'][$_POST['to']]);
	
	$sql = "insert into chat_history (sender,receiver,message,sent) values ('".mysql_real_escape_string($from)."', '".mysql_real_escape_string($to)."','".mysql_real_escape_string($message)."',NOW())";
	$query = mysql_query($sql);
	
	echo "1";
	exit(0);
}


/**
 * @author: Md. Golam Rabbany
 * @email: mgrnahid@gmail.com
 * @description: This function return closeChat
 * @copyright 2011
 */
 

function closeChat() {

	unset($_SESSION['openChatBoxes'][$_POST['chatbox']]);

	echo "1";
	exit(0);
}

	

function sanitize($text) {
	$text = htmlspecialchars($text, ENT_QUOTES);
	$text = str_replace("\n\r","\n",$text);
	$text = str_replace("\r\n","\n",$text);
	$text = str_replace("\n","<br>",$text);
	return $text;
}



}
?>