<?php

class ModEss_XenForo_Model_InlineMod_Post extends XFCP_ModEss_XenForo_Model_InlineMod_Post
{
	public function canConvertPostsToConversation(array $postIds, &$errorKey = '', array $viewingUser = null)
	{
		list($posts, $threads, $forums) = $this->getPostsAndParentData($postIds, $viewingUser);

		return $this->canConvertPostsToConversationData($posts, $threads, $forums, $errorKey, $viewingUser);
	}

	public function canConvertPostsToConversationData(array $posts, array $threads, array $forums, &$errorKey = '', array $viewingUser = null)
	{
		if (count($posts) <= 1)
		{
			$errorKey = 'modess_please_select_more_than_one_post_to_convert_to_conversation';

			return false;
		}

		$userNames = array();

		foreach ($posts as $post)
		{
			$userNames[] = $post['username'];
		}

		$userNames = array_unique($userNames);

		if (count($userNames) < 2)
		{
			$errorKey = 'modess_please_select_at_least_two_posts_by_different_users_to_convert_to_conversation';

			return false;
		}

		return $this->_checkPermissionOnPosts('canConvertPostToConversation', $posts, $threads, $forums, $errorKey,
			$viewingUser);
	}

	public function convertPostsToConversation(array $postIds, array $options = array(), &$errorKey = '', array $viewingUser = null)
	{
		$postModel = $this->_getPostModel();

		/** @var XenForo_Model_User $userModel */
		$userModel = $this->getModelFromCache('XenForo_Model_User');

		/** @var XenForo_Model_Attachment $attachmentModel */
		$attachmentModel = $this->getModelFromCache('XenForo_Model_Attachment');

		$fetchOptions = array(
			'join' => XenForo_Model_Post::FETCH_USER
		);
		$posts = $postModel->getPostsByIds($postIds, $fetchOptions);

		ksort($posts);

		$initialPost = reset($posts);
		$convStarter = $userModel->getFullUserById($initialPost['user_id'],
			array('join' => XenForo_Model_User::FETCH_USER_PERMISSIONS));
		$convStarter['permissions'] = XenForo_Permission::unserializePermissions($convStarter['global_permission_cache']);
		unset($posts[reset($postIds)]);

		$thread = $this->_getThreadModel()->getThreadById($initialPost['thread_id']);

		$messages = array();
		$userIds = array();

		foreach ($posts as $post)
		{
			$userIds[] = $post['user_id'];

			$messages[] = array(
				'post_id' => $post['post_id'],
				'user_id' => $post['user_id'],
				'username' => $post['username'],
				'message' => $post['message'],
				'message_date' => $post['post_date'],
				'sender' => $userModel->getFullUserById($post['user_id'])
			);
		}

		$visitor = XenForo_Visitor::getInstance();

		if (!empty($options['mod_message']))
		{
			$userIds[] = $visitor['user_id'];
		}

		$userIds = array_unique($userIds);

		$titlePhrase = new XenForo_Phrase('modess_posts_moved_from_x', array('title' => $thread['title']));

		$masterData = array(
			'user_id' => $initialPost['user_id'],
			'username' => $initialPost['username'],
			'title' => $titlePhrase->render(),
			'start_date' => $initialPost['post_date']
		);

		XenForo_Db::beginTransaction();

		/** @var XenForo_DataWriter_ConversationMaster $conversationMasterDw */
		$conversationMasterDw = XenForo_DataWriter::create('XenForo_DataWriter_ConversationMaster');
		$conversationMasterDw->bulkSet($masterData);
		$conversationMasterDw->setExtraData(XenForo_DataWriter_ConversationMaster::DATA_ACTION_USER, $convStarter);
		$conversationMasterDw->setExtraData(XenForo_DataWriter_ConversationMaster::DATA_MESSAGE,
			$initialPost['message']);
		$conversationMasterDw->addRecipientUserIds($userIds);

		$firstMessageDw = $conversationMasterDw->getFirstMessageDw();

		$firstMessageDw->setOption(XenForo_DataWriter_ConversationMessage::OPTION_SET_IP_ADDRESS, false);
		$firstMessageDw->set('message', $initialPost['message']);
		$firstMessageDw->set('message_date', $initialPost['post_date']);

		if ($attachments = $attachmentModel->getAttachmentsByContentId('post', $initialPost['post_id']))
		{
			$tempHash = md5(uniqid('', true));

			foreach ($attachments as $attachment)
			{
				$newAttachment = array(
					'data_id' => $attachment['data_id'],
					'attach_date' => $initialPost['post_date'],
					'temp_hash' => $tempHash
				);

				$firstMessageAttachDw = XenForo_DataWriter::create('XenForo_DataWriter_Attachment');
				$firstMessageAttachDw->bulkSet($newAttachment);
				$firstMessageAttachDw->save();
			}

			$firstMessageDw->setExtraData(XenForo_DataWriter_ConversationMessage::DATA_ATTACHMENT_HASH, $tempHash);
		}

		$conversationMasterDw->save();

		$conversationId = $conversationMasterDw->get('conversation_id');

		foreach ($messages as $message)
		{
			/** @var XenForo_DataWriter_ConversationMessage $dw */
			$messageDw = XenForo_DataWriter::create('XenForo_DataWriter_ConversationMessage');
			$messageDw->setOption(XenForo_DataWriter_ConversationMessage::OPTION_SET_IP_ADDRESS, false);
			$messageDw->set('conversation_id', $conversationId);
			$messageDw->setExtraData(XenForo_DataWriter_ConversationMessage::DATA_MESSAGE_SENDER, $message['sender']);

			if ($attachments = $attachmentModel->getAttachmentsByContentId('post', $message['post_id']))
			{
				$tempHash = md5(uniqid('', true));

				foreach ($attachments as $attachment)
				{
					$newAttachment = array(
						'data_id' => $attachment['data_id'],
						'attach_date' => $message['message_date'],
						'temp_hash' => $tempHash
					);

					$messageAttachDw = XenForo_DataWriter::create('XenForo_DataWriter_Attachment');
					$messageAttachDw->bulkSet($newAttachment);
					$messageAttachDw->save();
				}

				$messageDw->setExtraData(XenForo_DataWriter_ConversationMessage::DATA_ATTACHMENT_HASH, $tempHash);
			}

			unset($message['sender'], $message['post_id']);

			$messageDw->bulkSet($message);
			$messageDw->save();
		}

		if (!empty($options['mod_message']))
		{
			/** @var XenForo_DataWriter_ConversationMessage $dw */
			$dw = XenForo_DataWriter::create('XenForo_DataWriter_ConversationMessage');
			$dw->set('conversation_id', $conversationId);
			$dw->setExtraData(XenForo_DataWriter_ConversationMessage::DATA_MESSAGE_SENDER, $visitor->toArray());

			$dw->set('user_id', $visitor['user_id']);
			$dw->set('username', $visitor['username']);
			$dw->set('message', $options['mod_message']);

			$dw->save();
		}

		if ($this->deletePosts($postIds, $options))
		{
			XenForo_Db::commit();
		}
		else
		{
			XenForo_Db::rollbackAll();

			return false;
		}

		return true;
	}
}

if (false)
{
	class XFCP_ModEss_XenForo_Model_InlineMod_Post extends XenForo_Model_InlineMod_Post
	{
	}
}