<?php
class ModEss_XenForo_ControllerPublic_InlineMod_Thread extends XFCP_ModEss_XenForo_ControllerPublic_InlineMod_Thread
{
    public function actionModessTag()
    {
        if (!XenForo_Visitor::getInstance()->hasPermission('general', 'modess_manageTags'))
        {
            throw $this->getErrorOrNoPermissionResponseException();
        }
        if ($this->isConfirmedPost())
        {
            $threadIds = $this->getInlineModIds();

            /* @var XenForo_Model_Forum $forumModel */
            $forumModel = $this->getModelFromCache('XenForo_Model_Forum');

            $threads = $this->_getThreadModel()->getThreads(array('thread_id' => $threadIds));

            $nodeIds = array();

            if (!empty($threads))
            {
                foreach ($threads as $thread)
                {
                    $nodeIds[$thread['node_id']] = true;
                }
            }

            $nodeIds = array_keys($nodeIds);
            if (empty($nodeIds))
            {
                throw $this->getErrorOrNoPermissionResponseException();
            }

            $nodes = $forumModel->getForumsByIds($nodeIds);

            /** @var XenForo_Model_Tag $tagModel */
            $tagModel = $this->getModelFromCache('XenForo_Model_Tag');

            foreach ($threadIds as $threadId)
            {
                $tagger = $tagModel->getTagger('thread');
                $tagger->setContent($threadId)->setPermissionsFromContext($nodes[$threads[$threadId]['node_id']]);
                $tags = $this->_input->filterSingle('tags', XenForo_Input::STRING);
                $tagger->addTags($tagModel->splitTags($tags));
                $errors = $tagger->getErrors();
                if ($errors)
                {
                    return $this->responseError($errors);
                }
                $cache = $tagger->save();
            }

            $this->clearCookie();

            return $this->responseRedirect(
                XenForo_ControllerResponse_Redirect::SUCCESS,
                $this->getDynamicRedirect(false, true)
            );
        }
        else // show confirmation dialog
        {
            return $this->responseView('ModEss_ViewPublic_InlineMod_Thread_Tag', 'modess_inline_mod_thread_tag', array(
                'tags' => array(
                    'editable' => array()
                )
            ));
        }
    }
}