<?php
/**
 * The model file of notify module of ZDOO.
 *
 * @copyright   Copyright 2009-2020 青岛易软天创网络科技有限公司(QingDao Nature Easy Soft Network Technology Co,LTD, www.cnezsoft.com)
 * @license     ZPL (http://zpl.pub/page/zplv12.html)
 * @author      Gang Liu <liugang@easycorp.ltd>
 * @package     notify
 * @version     $Id$
 * @link        http://www.zdoo.com
 */
class notifyModel extends model
{
    /**
     * Get notify list.
     *
     * @param  string $status
     * @access public
     * @return array
     */
    public function getList($status = '')
    {
        return $this->dao->select('*')->from(TABLE_NOTIFY)
            ->beginIF($status)->where('status')->eq($status)->fi()
            ->fetchAll('id');
    }

    /**
     * Get objectTypes.
     *
     * @access public
     * @return array
     */
    public function getObjectTypes()
    {
        $objectTypes = array();
        foreach($this->config->notify->objectTypes as $objectType => $actions)
        {
            $appName = zget($this->config->action->objectAppNames, $objectType, '');
            if(!$appName) continue;

            $objectTypes[$appName][$objectType] = $this->lang->action->objectTypes[$objectType];
        }
        return $objectTypes;
    }

    /**
     * Get object actions.
     *
     * @access public
     * @return array
     */
    public function getObjectActions()
    {
        $objectActions = array();
        foreach($this->config->notify->objectTypes as $objectType => $actions)
        {
            foreach($actions as $action)
            {
                $objectActions[$objectType][$action] = str_replace($this->lang->webhook->trimWords, '', $this->lang->action->label->$action);
            }
        }
        return $objectActions;
    }

    /**
     * Get toList.
     *
     * @param  object    $object
     * @param  string    $objectType
     * @access public
     * @return string
     */
    public function getToList($object, $objectType)
    {
        $toList = '';
        if(!empty($object->assignedTo)) $toList = $object->assignedTo;
        if(empty($toList) and $objectType == 'todo') $toList = $object->account;

        if($toList == 'closed') $toList = '';
        return $toList;
    }

    /**
     * Check send.
     *
     * @param  string $objectType
     * @param  int    $objectID
     * @param  string $actionType
     * @param  int    $actionID
     * @param  string $actor
     * @access public
     * @return void
     */
    public function send($objectType, $objectID, $actionType, $actionID, $actor = '')
    {
        $notifySetting = $this->config->notify->setting;
        if(is_string($notifySetting)) $notifySetting = json_decode($notifySetting, true);

        if(isset($notifySetting['mail']))
        {
            $actions = $notifySetting['mail']['setting'];
            if(isset($actions[$objectType]) and in_array($actionType, $actions[$objectType]))
            {
                $moduleName = $objectType == 'case' ? 'testcase' : $objectType;
                $this->loadModel($moduleName);
                if(method_exists($this->$moduleName, 'sendmail')) $this->$moduleName->sendmail($objectID, $actionID);
            }
        }

        if(isset($notifySetting['webhook']))
        {
            $actions = $notifySetting['webhook']['setting'];
            if(isset($actions[$objectType]) and in_array($actionType, $actions[$objectType]))
            {
                $this->loadModel('webhook')->send($objectType, $objectID, $actionType, $actionID, $actor);
            }
        }

        if(isset($notifySetting['message']))
        {
            $actions = $notifySetting['message']['setting'];
            if(isset($actions[$objectType]) and in_array($actionType, $actions[$objectType]))
            {
                $this->saveNotice($objectType, $objectID, $actionType, $actionID, $actor);
            }
        }
    }

    /**
     * Save notice.
     *
     * @param  string $objectType
     * @param  int    $objectID
     * @param  string $actionType
     * @param  int    $actionID
     * @param  string $actor
     * @access public
     * @return void
     */
    public function saveNotice($objectType, $objectID, $actionType, $actionID, $actor = '')
    {
        if(empty($actor)) $actor = $this->app->user->account;
        if(empty($actor)) return false;

        $this->loadModel('action');
        $user   = $this->loadModel('user')->getByAccount($actor);
        $table  = $this->config->objectTables[$objectType];
        $app    = $this->config->action->objectAppNames[$objectType];
        $field  = $this->config->action->objectNameFields[$objectType];
        $object = $this->dao->select('*')->from($table)->where('id')->eq($objectID)->fetch();
        $toList = $this->getToList($object, $objectType);
        if(empty($toList)) return false;

        $clientLang = $this->app->getClientLang();

        $space   = ($clientLang == 'zh-cn' or $clientLang == 'zh-tw') ? '' : ' ';
        $sysURL  = commonModel::getSysURL();
        $data    = $user->realname . $space . $this->lang->action->label->$actionType . $space . $this->lang->action->objectTypes[$objectType];
        $data   .= ' ' . html::a($sysURL . helper::createLink($app . $objectType, 'view', "id=$objectID"), "[#{$objectID}::{$object->$field}]");

        $notify = new stdclass();
        $notify->objectType  = 'message';
        $notify->action      = $actionID;
        $notify->toList      = $toList;
        $notify->data        = $data;
        $notify->status      = 'wait';
        $notify->createdBy   = $actor;
        $notify->createdDate = helper::now();

        $this->dao->insert(TABLE_NOTIFY)->data($notify)->exec();
    }
}
