<?php
/**
 * Created by PhpStorm.
 * User: shakarim
 * Date: 3/18/16
 * Time: 5:45 PM
 */

namespace common\modules\triggers\components\conditions\conditions;
use common\modules\triggers\components\conditions\vendor\ConditionBase;
use common\modules\triggers\components\conditions\vendor\ConditionInterface;
use common\modules\triggers\models\TriggerLogs;
use common\modules\users\models\User;


class CheckUserToSubscribeToBlog extends ConditionBase implements ConditionInterface{
    const CONDITION_ID = 13;

    public $name = 'Пользователь подписался на блог';

    /**
     * @param null|string $conditionName
     * @return $this mixed
     */
    public static function init($conditionName=__CLASS__){
        return parent::init($conditionName);
    }

    /**
     * @param null $message
     * @param array $params
     * @return bool
     */
    public function check($message=null, $params = array()){
        $email = null;
        if (!is_null($message))
            $email = $message->email;
        elseif(array_key_exists('email', $params)) {
            $email = $params['email'];
        }
        if (!is_null($email)) {
            $user = User::find()->where(['email' => $email])->one();
            if (!is_null($user)) {
                $exists = TriggerLogs::find()->where(['user_id' => $user->getPrimaryKey(), 'action' =>TriggerLogs::USER_SUBSCRIBE_TO_BLOG])->exists();
                return $exists;
            }
        }
        return false;
    }
}