<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

// +----------------------------------------------------------------------+
// | This page is for user section management. Login checking , new user registration, user listing etc.                                      |
// | File name : index.php                                                  |
// | PHP version >= 5.2                                                   |
// | Created On	: 	Nov 17 2011                                               |
// +----------------------------------------------------------------------+
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems ? 2010                                      |
// | All rights reserved                                                  |
// +------------------------------------------------------

class ControllerChat extends BaseController {

    public function init() {
        parent::init();

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

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

    public function chatheartbeat() {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        $chatLog = Chat::getChatlog($_SESSION['default_user_id']);
        $usersList = Chat::getUsersList();

        $items = '';
        $chatBoxes = array();
        $userArray = array();
        
        if(!empty($usersList)) {
            foreach($usersList as $user) {
                $userArray[$user->user_id] = $user->user_alias;
            }
        }
        
        if (!empty($chatLog)) {
            foreach ($chatLog as $chatLogEntity) {

                if (!isset($_SESSION['openChatBoxes'][$userArray[$chatLogEntity->from]]) && isset($_SESSION['chatHistory'][$userArray[$chatLogEntity->from]])) {
                    $items = $_SESSION['chatHistory'][$userArray[$chatLogEntity->from]];
                }

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

                $items .= <<<EOD
					   {
			"s": "0",
			"f": "{$userArray[$chatLogEntity->from]}",
			"m": "{$chatLogEntity->message}"
	   },
EOD;

                if (!isset($_SESSION['chatHistory'][$userArray[$chatLogEntity->from]])) {
                    $_SESSION['chatHistory'][$userArray[$chatLogEntity->from]] = '';
                }

                $_SESSION['chatHistory'][$userArray[$chatLogEntity->from]] .= <<<EOD
						   {
			"s": "0",
			"f": "{$userArray[$chatLogEntity->from]}",
			"m": "{$chatLogEntity->message}"
	   },
EOD;

                unset($_SESSION['tsChatBoxes'][$userArray[$chatLogEntity->from]]);
                $_SESSION['openChatBoxes'][$userArray[$chatLogEntity->from]] = $chatLogEntity->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;
                    }
                }
            }
        }

        Chat::chatStatusUpdate($_SESSION['default_user_id']);

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

    public function startchatsession() {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        $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['default_user_alias']; ?>",
        "items": [
        <?php echo $items; ?>
        ]
        }
        <?php
        exit();
    }

    public function sendchat() {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

        $from = $_SESSION['default_user_id'];
        $to = $_POST['to'];
        $message = $_POST['message'];
        
        $usersList = Chat::getUsersList();
        $userArray = array();
        $userIDArray = array();
        
        if(!empty($usersList)) {
            foreach($usersList as $user) {
                $userArray[$user->user_alias] = $user->user_alias;
                $userIDArray[$user->user_alias] = $user->user_id;
            }
        }

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

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

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

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


        unset($_SESSION['tsChatBoxes'][$userArray[$to]]);

        Chat::addChatlog($from, $userIDArray[$to], $message);

        echo "1";
        exit();
    }

    public function closechat() {
        PageContext::$full_layout_rendering = false;
        $this->view->disableLayout();

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

        echo "1";
        exit();
    }

    private 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;
    }

    private function chatboxsession($chatbox) {
        $items = '';

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

        return $items;
    }

}
?>