<?php
/*
+--------------------------------------------------------------------------
|   TanyaCMS - Question and Answer Sofware
|   -----------------------------------------------------------------------
|   by fbschool dev team
|   (c) 2011 - 2012 FBSCHOOL
|   http://www.fbschool.com/tanyacms
|   -----------------------------------------------------------------------
|   This is NOT a freeware, use is subject to license terms
|   Support: 13455n@gmail.com
+--------------------------------------------------------------------------
*/

define('IN_AJAX', TRUE);


if (!defined('IN_TANYACMS'))
{
	die;
}

class ajax extends ASK_CONTROLLER
{
	function setup()
	{
		HTTP::no_cache_header();
	}
	
	public function send_action()
	{
		if ($this->is_post())
		{
			$sender_uid = $this->user_id;
			$message = $_POST['message'];
			$recipient = $_POST['recipient'];
			
			if (trim($message) == '')
			{
				H::ajax_json_output(ASK_APP::RSM(null, '-1', "Please enter message content"));
			}
			
			if (!$recipient_user = $this->model('account')->get_user_info_by_username($recipient))
			{
				H::ajax_json_output(ASK_APP::RSM(null, '-1', "Receive information user does not exist"));
			}
			else
			{
				$recipient_uid = $recipient_user['uid'];
			}
			
			if ($recipient_uid == $sender_uid)
			{
				H::ajax_json_output(ASK_APP::RSM(null, '-1', 'Cannot sent message to yourself'));
			}
			
			//Determine whether the person concerned is set to send a message
			if (! $this->model('message')->check_recv($recipient_user['uid'], $sender_uid))
			{
				H::ajax_json_output(ASK_APP::RSM(null, '-1', 'The user has set only to receive message from persons she or he has followed'));
			}
			
			if ($this->model('message')->send_message($sender_uid, $recipient_uid, null, $message, 0, 0))
			{
				if ($_POST['return_url'])
				{
					$rsm = array(
						'url' => get_js_url(strip_tags($_POST['return_url']))
					);
				}
				else
				{
					$rsm = array(
						'url' => get_js_url('/inbox/')
					);
				}
				
				if($_GET['type'] == 'clickEve')
				{
					H::ajax_json_output(ASK_APP::RSM($rsm, 1, 'Private letter sent successfully'));
				}
				else
				{
					H::ajax_json_output(ASK_APP::RSM($rsm, 1, null));
				}
			}
			else
			{
				H::ajax_json_output(ASK_APP::RSM(null, '-1', 'Failed to send private messages, please contact your administrator'));
			}
		}
	}
}