<?php

class PostReplace_ControllerAdmin_PostReplace extends XenForo_ControllerAdmin_Abstract
{
	public function actionIndex()
	{
		return $this->responseView('PostReplace_ViewAdmin_PostReplace_Index', 'postreplace_index');
	}

	public function actionReplace()
	{
		$this->_assertPostOnly();

		$input = $this->_input->filter(array(
			'find' => XenForo_Input::STRING,
			'regex' => XenForo_Input::STRING,
			'replace' => XenForo_Input::STRING,
			'commit' => XenForo_Input::UINT,
			'page' => XenForo_Input::UINT,
		));

		$posts = $this->_getPRPostModel()->getPostsContaining($input['find']);

		foreach ($posts AS $postId => &$post)
		{
			if (preg_match_all($input['regex'], $post['message'], $matches))
			{
				$post['found'] = $matches[0];
				$post['replaced'] = preg_replace($input['regex'], $input['replace'], $post['found']);

				$message = preg_replace($input['regex'], $input['replace'], $post['message']);

				if ($input['commit'])
				{
					$dw = XenForo_DataWriter::create('XenForo_DataWriter_DiscussionMessage_Post');

					$dw->setOption(XenForo_DataWriter_DiscussionMessage::OPTION_IS_AUTOMATED, true);
					$dw->setExistingData($post, true);

					$dw->set('message', $message);

					$dw->save();
				}
			}
			else
			{
				unset($posts[$postId]);
			}
		}

		$viewParams = array(
			'input' => $input,
			'posts' => $posts
		);

		return $this->responseView('PostReplace_ViewAdmin_PostReplace_Replace', 'postreplace_index', $viewParams);
	}

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