<?php

/**
 * Controller for post-related actions.
 *
 * @package XenForo_Post
 */
class ConversationPost_ControllerPublic_Post extends XFCP_ConversationPost_ControllerPublic_Post 
{




	/**
	 * Displays a form to create a conversation.
	 *
	 * @return XenForo_ControllerResponse_Abstract
	 */
	public function actionConversation()
	{

		$postId = $this->_input->filterSingle('post_id', XenForo_Input::UINT);

		$ftpHelper = $this->getHelper('ForumThreadPost');
		list($post, $thread, $forum) = $ftpHelper->assertPostValidAndViewable($postId);
		
		if ($this->_request->isPost())
		{
			$this->_assertPostOnly();

			if (!$this->_getConversationModel()->canStartConversations($errorPhraseKey))
			{
				throw $this->getErrorOrNoPermissionResponseException($errorPhraseKey);
			}

			$input = $this->_input->filter(array(
				'recipients' => XenForo_Input::STRING,
				'title' => XenForo_Input::STRING,
				'open_invite' => XenForo_Input::UINT,
				'conversation_locked' => XenForo_Input::UINT,
				'attachment_hash' => XenForo_Input::STRING
			));
			$input['message'] = $this->getHelper('Editor')->getMessageText('message', $this->_input);
			$input['message'] = XenForo_Helper_String::autoLinkBbCode($input['message']);

			$visitor = XenForo_Visitor::getInstance();

			$conversationDw = XenForo_DataWriter::create('XenForo_DataWriter_ConversationMaster');
			$conversationDw->setExtraData(XenForo_DataWriter_ConversationMaster::DATA_ACTION_USER, $visitor->toArray());
			$conversationDw->setExtraData(XenForo_DataWriter_ConversationMaster::DATA_MESSAGE, $input['message']);
			$conversationDw->set('user_id', $visitor['user_id']);
			$conversationDw->set('username', $visitor['username']);
			$conversationDw->set('title', $input['title']);
			$conversationDw->set('open_invite', $input['open_invite']);
			$conversationDw->set('conversation_open', $input['conversation_locked'] ? 0 : 1);
			$conversationDw->addRecipientUserNames(explode(',', $input['recipients'])); // checks permissions

			$messageDw = $conversationDw->getFirstMessageDw();
			$messageDw->set('message', $input['message']);
			$messageDw->setExtraData(XenForo_DataWriter_ConversationMessage::DATA_ATTACHMENT_HASH, $input['attachment_hash']);

			$conversationDw->preSave();

			if (!$conversationDw->hasErrors())
			{
				$this->assertNotFlooding('conversation');
			}

			$conversationDw->save();
			$conversation = $conversationDw->getMergedData();

			$this->_getConversationModel()->markConversationAsRead(
				$conversation['conversation_id'], XenForo_Visitor::getUserId(), XenForo_Application::$time
			);

			$controllerResponse = $this->getPostSpecificRedirect($post, $thread);
			$controllerResponse->redirectMessage = new XenForo_Phrase('your_conversation_has_been_created');
			return $controllerResponse;
		}
		else
		{
			if (!$this->_getConversationModel()->canStartConversations($errorPhraseKey))
			{
				throw $this->getErrorOrNoPermissionResponseException($errorPhraseKey);
			}
			
			$options = XenForo_Application::getOptions();
			$quote_post = $options->quote_post;
			if ($quote_post )
			{					
				$quote = $this->_getPostModel()->getQuoteTextForPost($post); // quote post in conversation
			}
			else
			{
				$quote = '';
			}
	

			$to = $this->_input->filterSingle('to', XenForo_Input::STRING);
			if ($to !== '')
			{
				$toUser = $this->getModelFromCache('XenForo_Model_User')->getUserByName($to, array(
					'join' => XenForo_Model_User::FETCH_USER_FULL
				));
				if (!$toUser)
				{
					return $this->responseError(new XenForo_Phrase('requested_user_not_found'), 404);
				}

				if (!$this->_getConversationModel()->canStartConversationWithUser($toUser, $errorPhraseKey))
				{
					if ($errorPhraseKey)
					{
						$error = new XenForo_Phrase($errorPhraseKey);
					}
					else
					{
						$error = new XenForo_Phrase('you_may_not_start_conversation_with_x_privacy_settings', array('name' => $toUser['username']));
					}
					return $this->responseError($error, 403);
				}

				$to = $toUser['username'];
			}

			$attachmentParams = $this->_getConversationModel()->getAttachmentParams();

			if ($attachmentParams)
			{
				$attachmentModel = $this->_getAttachmentModel();

				$quickReplyAttachmentHash = $this->_input->filterSingle('attachment_hash', XenForo_Input::STRING);

				$attachments = $attachmentModel->prepareAttachments(
					$attachmentModel->getAttachmentsByTempHash($quickReplyAttachmentHash)
				);

				if ($attachments)
				{
					$attachmentParams['hash'] = $quickReplyAttachmentHash;
				}
			}
			else
			{
				$attachments = array();
			}

			$viewParams = array(
				'to' => $to,
				'remaining' => $this->_getConversationModel()->allowedAdditionalConversationRecipients(array()),
				'quote' => $quote,
				'attachmentParams' => $attachmentParams,
				'attachments' => $attachments,
				'attachmentConstraints' => $this->getModelFromCache('XenForo_Model_Attachment')->getAttachmentConstraints(),
				'post_id' => $postId,
				 'message_title' => $thread['title'] 
			);

			return $this->responseView('XenForo_ViewPublic_Conversation_Add', 'conversationpost_add', $viewParams);
		}
	}



	/**
	 * @return XenForo_Model_Conversation
	 */
	protected function _getConversationModel()
	{
		return $this->getModelFromCache('XenForo_Model_Conversation');
	}	


}