<?php
/*======================================================================*\
|| #################################################################### ||
|| # New User Notification System  2.1
|| # Build: 25
|| # ---------------------------------------------------------------- # ||
|| #################################################################### ||
\*======================================================================*/


/**
 *  Model for new user notifications
 *
 */
class Ragtek_NUNS_Model_Notifications extends XenForo_Model
{
    /**
     * @var new user data
     */
    protected $_user = null;

    /**
     * @var welcome thread data (needed for the welcome conversation)
     */
    protected $_welcomeThread = null;

    /**
     * @var XenForo Options
     */
    protected $_options = null;

    /** @var Ragtek_NUNS_Phrase */
    protected $_NUNSPHrase = null;

    /**
     * initialize the object ( had to do it this way, because xenforo models doesn't provide an constructor
     * @param Ragtek_NUNS_Phrase $ph
     * @param array $newUser
     */
    public function init(Ragtek_NUNS_Phrase $ph, array $newUser)
    {
        $this->_NUNSPHrase = $ph;
        $this->_NUNSPHrase->setPrefix('ragtek_NUNS_text_');
        $this->_user = $newUser;
    }

    /**
     * @return array options
     */
    public function getOptions()
    {
        if (!$this->_options) {
            $this->_options = XenForo_Application::get('options');
        }
        return $this->_options;
    }

    /**
     * setter method for options, to be able to inject own options
     * @param array $options
     */
    public function _setOptions(array $options)
    {
        $this->_options = $options;
    }

    /**
     * set the welcome thread data and tebuild my phrase cache to include the new thread data
     * @param array $thread
     */
    public function setWelcomeThread(array $thread)
    {
        $this->_welcomeThread = $thread;

        // rebuild the phrase cache
        $this->_NUNSPHrase->setParams($this->getPhraseParams());
    }

    /**
     * returns the available phrase params
     * other addons can extend this and add there own variables
     * @return array
     */
    public function getPhraseParams()
    {
        $options = $this->getOptions();

        $params = array(
            'boardname' => $options->boardTitle,
            'homeUrl' => $this->_getStartUrl(),
            'eMail' => $this->_user['email'],
            'username' => $this->_user['username'],
            'profileurl' => XenForo_Link::buildPublicLink('full:members', $this->_user),
            'ip' => (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false)
        );

        if ($this->_welcomeThread) {
            $params['threadId'] = $this->_welcomeThread['thread_id'];
            $params['welcomeThread'] = XenForo_Link::buildPublicLink('full:threads', $this->_welcomeThread);
        }
        return $params;
    }

    /**
     * do we really need this?
     * @return string
     */
    protected function _getStartUrl()
    {
        $options = $this->getOptions();
        return ($options->homePageUrl ? $options->homePageUrl : XenForo_Link::buildPublicLink('full:index'));
    }


    /**
     * @param array $threadCreater
     * @return array | datawriter return
     */
    public function createWelcomeThread(array $threadCreater)
    {
        $options = $this->getOptions();
        $subject = $this->_NUNSPHrase->getPhrase('welcomethread_subject');

        $message = $this->_NUNSPHrase->getPhrase('welcomethread_message');
        $thread = Ragtek_NUNS_Helper::createThread($threadCreater,
            $options->ragtek_NUNS_newUserThreadForum,
            $subject,
            $message);

        return $thread;
    }

    /**
     * @param array $sender
     * @return array
     */
    public function sendWelcomeConversation(array $sender)
    {
        // this will be cool once 5.3 is necessary, => use invoke for this! $sub = $ph('welcomethread_subject');
        $subject = $this->_NUNSPHrase->getPhrase('conversation_subject');
        $message = $this->_NUNSPHrase->getPhrase('conversation_message');

        $options = XenForo_Application::get('options');
        $close = false;
        if ($options->ragtek_NUNS_welcomeConversationClosed) {
            $close = true;
        }

        $recipient = array($this->_user['user_id']);
        $conv = Ragtek_NUNS_Helper::createConversation($sender, $recipient, $subject, $message, true, $close);

        if ($options->ragtek_NUNS_autoLeaveConv) {

            $this->_getConversationModel()->deleteConversationForUser(
                $conv['conversation_id'], $sender['user_id'], 'deleted'
            );
        }
        return $conv;
    }

    /**
     *
     * sends a notification (mail to the forum team (misaddresses are safed in the options)
     *
     * @param array $recivers
     */
    public function sendNewUserMails(array $recivers)
    {
        foreach ($recivers AS $reciver) {

            $mail = XenForo_Mail::create('ragtek_nuns_teammail',
                $this->getPhraseParams(),
                $reciver['language_id']);
            $mail->enableAllLanguagePreCache();
            $mail->send($reciver['email'], $reciver['username']);
        }
    }


    public function initWelcomeThread()
    {
        $options = $this->getOptions();

        if ($options->ragtek_NUNS_newUserThreadActive
            AND
            $threadCreater = $this->_getUserModel()->getUserByName($options->ragtek_NUNS_newUserThreadCreater)
        ) {
            $thread = $this->createWelcomeThread($threadCreater);
            $this->setWelcomeThread($thread);
        }

    }

    public function initWelcomeConversation()
    {
        $options = $this->getOptions();
        $userModel = $this->_getUserModel();
        if (
            $options->ragtek_NUNS_welcomeConversationActive
            AND
            $sender = $userModel->getUserByName($options->ragtek_NUNS_welcomeConversationSender)
        ) {
            $this->sendWelcomeConversation($sender);
        }
    }

    public function initTeamNotification()
    {
        $options = $this->getOptions();
        $userModel = $this->_getUserModel();
        if (
            $options->ragtek_NUNS_TeamNotificationActive
            AND
            $recivers = $userModel->getUsersByNames(explode(',', $options->ragtek_NUNS_teamNotification))
        ) {
            $this->sendNewUserMails($recivers);
        }
    }


    public function initWelcomePostMessage()
    {
        $options = $this->getOptions();
        $usrModel = $this->_getUserModel();

        if ($options->ragtek_NUNS_newUserProfilePostActive AND
            $sender = $usrModel->getUserByName($options->ragtek_NUNS_ProfilePostCreater)
        ) {
            $this->_createProfilePost($sender);
        }
    }

    protected function _createProfilePost(array $sender)
    {
        $post = $this->_NUNSPHrase->getPhrase('profilepost');
        Ragtek_NUNS_Helper::createProfilePost($sender, $this->_user, $post);
    }

    public function initWelcomePost()
    {
        $options = $this->getOptions();
        $threadId = $options->ragtek_NUNS_newuserThreadId;
        if ($options->ragtek_NUNS_welcomeThreadPostActive AND
            $threadId != 0
                AND
                $sender = $this->_getUserModel()->getUserByName($options->ragtek_NUNS_welcomePostCreater)
        ) {
            $post = $this->_NUNSPHrase->getPhrase('welcomePost');
            $post = Ragtek_NUNS_Helper::createPost($sender, $threadId, $post);
        }
    }

    /**
     * check and run all methods
     * @return void
     */
    public function notify()
    {
        $this->initWelcomeThread();
        $this->initWelcomeConversation();
        $this->initTeamNotification();
        $this->initWelcomePostMessage();
        $this->initWelcomePost();
    }

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

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