<?php
/**
 * Разработал Максим Руденко
 * email: rudenko.programmer@gmail.com
 * Дата: 15.11.2017
 */

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * Class UserNotifications
 * @package common\models
 * @property integer id
 * @property integer user_id
 * @property string title
 * @property string text
 * @property string redirect_url
 * @property string params
 * @property mixed created_at
 * @property mixed updated_at
 */
class UserNotifications extends ActiveRecord
{
	const TYPE_UTC_BASIC = 'UTC_BASIC';

	const TYPE_OPPORT_CREATE = 'OPPORT_CREATE';
	const TYPE_OPPORT_CHANGE = 'OPPORT_CHANGE';
	const TYPE_OPPORT_REJECT = 'OPPORT_REJECT';
	const TYPE_OPPORT_APPROVE = 'OPPORT_APPROVE';
	const TYPE_TEAM_USER_INVITED = 'USER_INVITED';//Добавление пользователя в команду

	const TYPE_TEAM_ACCEPT_INVIT_TO_OWNER = 'ACCEPT_INVIT_TO_OWNER';//User has accepted invitation sent notification to owner
	const TYPE_TEAM_ACCEPT_INVIT_TO_USER = 'ACCEPT_INVIT_TO_USER';//User has accepted invitation sent notification to user
	const TYPE_TEAM_CANCEL_INVIT_TO_OWNER = 'CANCEL_INVIT_TO_OWNER';//User has canceled invitation sent notification to owner
	const TYPE_TEAM_CANCEL_INVIT_TO_USER = 'CANCEL_INVIT_TO_USER';//User has canceled invitation sent notification to user
	const TYPE_TEAM_OWNER_CANCEL_INVIT_TO_OWNER = 'OWNER_CANCEL_INVIT_TO_OWNER';//Owner has canceled user's invitation sent notification to owner
	const TYPE_TEAM_OWNER_CANCEL_INVIT_TO_USER = 'TYPE_TEAM_OWNER_CANCEL_INVIT_TO_USER';//Owner has canceled user's invitation sent notification to owner
	const TYPE_TEAM_USER_LEAVE = 'USER_LEAVE';//User has leaved the team
	const TYPE_TEAM_OWNER_REMOVE_USER = 'OWNER_REMOVE_USER';//owner has removed user from the team

	const TYPE_TEAM_USER_LEAVE_FEEDBACK = 'TEAM_USER_LEAVE_FEEDBACK';//A user received a feedback from a Team Member

	const TYPE_TEAM_USER_REQUEST_JOIN = 'TEAM_USER_REQUEST_JOIN';//A user request to join an opportunity


	const TYPE_TEAM_USER_SEND_INVITATION = 'USER_SEND_INVITATION';//Добавление пользователя в команду

	/**
	 * @return array
	 */
	public function behaviors()
	{
		return [
			[
				'class' => TimestampBehavior::className(),
				'attributes' => [
					ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
					ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
				],
			],
		];
	}

    public static function tableName()
    {
        return 'user_notifications';
    }

    public function attributeLabels()
    {
        return [
            'id' => 'Unique ID',
            'user_id' => 'User ID',
            'title' => 'Title',
            'text' => 'User ID',
            'redirect_url' => 'Redirect url',
            'created_at' => 'Create at',
            'updated_at' => 'Update at'
        ];
    }

    public function rules()
    {
        return [
            [['user_id', 'title', 'text', 'redirect_url'], 'required'],
            [['params', 'created_at', 'updated_at'], 'safe']
        ];
    }

	/**
	 * Set additional params
	 * @param array|string $array
	 */
    public function setParams($array){
		if(is_array($array)){
			$this->params = json_encode($array);
		}else{
			$this->params = '';
		}
    }

	/**
	 * Get additional params
	 * @return mixed|string
	 */
    public function getParams(){
    	if($this->params != ''){
		    /**
		     * class => for js
		     */
    		return json_decode($this->params);
	    }
	    return '';
    }

    public function isShow(){
        return $this->created_at >= $this->updated_at;
    }

    public function setRead(){
        $this->updated_at = time();
        $this->save();
    }

	public static function setNotification($user_id , $type, $title = '', $content='', $url='', $params=''){
		$notification = new self();
		$notification->user_id = $user_id;
		$notification->redirect_url = $url != ''?$url:'#';
		$notification->setParams($params);

		switch ($type){
			case self::TYPE_UTC_BASIC:
				$notification->title = $title!=''?$title:'UTC basic';
				$notification->text  = $content!=''?$content:'Remember to leave a feedback about your UTC, click here and fill the form';
				break;
			case self::TYPE_OPPORT_REJECT:
				$notification->title = $title!=''?$title:'Your opportunity has rejected';
				$notification->text  = $content!=''?$content:'Your opportunity has rejected. Please change.  Click for redirect.';
				break;
			case self::TYPE_OPPORT_APPROVE:
				$notification->title = $title!=''?$title:'Your opportunity has approved';
				$notification->text  = $content!=''?$content:'Congratulation Your opportunity has approved. Click for preview.';
				break;
			case self::TYPE_OPPORT_CREATE:
				$notification->title = $title!=''?$title:'Your opportunity has created';
				$notification->text  = $content!=''?$content:'Congratulation You opportunity has created successfully. Click for preview.';
				break;
			case self::TYPE_OPPORT_CHANGE:
				$notification->title = $title!=''?$title:'Your opportunity has changed';
				$notification->text  = $content!=''?$content:'Congratulation You opportunity has changed successfully.  Click for preview.';
				break;
			case self::TYPE_TEAM_USER_INVITED:
				$notification->title = $title!=''?$title:'You was invited to opportunity team';
				$notification->text  = $content!=''?$content:'You was invited to opportunity team.';
				break;
			case self::TYPE_TEAM_ACCEPT_INVIT_TO_OWNER:
				$notification->title = $title!=''?$title: "User has accepted invitation.";
				$notification->text  = $content!=''?$content:"User has accepted invitation.";
				break;
			case self::TYPE_TEAM_ACCEPT_INVIT_TO_USER:
				$notification->title = $title!=''?$title: "You have accepted invitation.";
				$notification->text  = $content!=''?$content:"You have accepted invitation.";
				break;
			case self::TYPE_TEAM_CANCEL_INVIT_TO_OWNER:
				$notification->title = $title!=''?$title: "User have canceled your invitation.";
				$notification->text  = $content!=''?$content:"User have canceled your invitation.";
				break;
			case self::TYPE_TEAM_CANCEL_INVIT_TO_USER:
				$notification->title = $title!=''?: "You have canceled invitation.";
				$notification->text  = $content!=''?:"You have canceled invitation.";
				break;
			case self::TYPE_TEAM_OWNER_CANCEL_INVIT_TO_OWNER:
				$notification->title = $title!=''?: "You have canceled user invitation.";
				$notification->text  = $content!=''?:"You have canceled user invitation.";
				break;
			case self::TYPE_TEAM_OWNER_CANCEL_INVIT_TO_USER:
				$notification->title = $title!=''?: "Owner have canceled invitation.";
				$notification->text  = $content!=''?:"Owner have canceled invitation.";
				break;
			case self::TYPE_TEAM_USER_LEAVE:
				$notification->title = $title!=''?: "User has left the team.";
				$notification->text  = $content!=''?:"User has left the team.";
				break;
			case self::TYPE_TEAM_OWNER_REMOVE_USER:
				$notification->title = $title!=''?: "Owner has removed your from the team.";
				$notification->text  = $content!=''?:"Owner has removed your from the team.";
				break;
			case self::TYPE_TEAM_USER_LEAVE_FEEDBACK:
				$notification->title = $title!=''?: "A user received a feedback from a Team Member.";
				$notification->text  = $content!=''?:"A user received a feedback from a Team Member.";
				break;
			default:
				$notification->title = $title;
				$notification->text  = $content;
		}

		$res = $notification->save();

		$notification->redirect_url = str_replace('%id', $notification->id, $notification->redirect_url);
		$notification->save();

		return $res;
	}

	public static function sendMailToPost($user_id , $type, $opportunity_id){
		$user = User::findOne($user_id);

		switch ($type){
			case self::TYPE_OPPORT_REJECT:
				$userUrl = 'https://test.connectingtalents.org/opportunities/insert?id='.$opportunity_id;

				self::sendMail("Admin has rejected your opportunity. Please check it here $userUrl", $user->email);
				break;
			case self::TYPE_OPPORT_APPROVE:
				$userUrl = 'https://test.connectingtalents.org/opportunities/insert-b?id='.$opportunity_id;
				self::sendMail("Admin has approved your opportunity. $userUrl", $user->email);
				break;
			case self::TYPE_OPPORT_CREATE:
				$adminUrl = 'https://testadmin.connectingtalents.org/opportunities/check-opportunities?id='.$opportunity_id;
//				self::sendMail("User has created their opportunity. Please approve it here: $adminUrl", Yii::$app->params['adminEmail']);

				self::sendMailByMandrill('opportunitie-create', Yii::$app->params['adminEmail'], ['URL' => $adminUrl]);
				break;
			case self::TYPE_OPPORT_CHANGE:
				$adminUrl = 'https://testadmin.connectingtalents.org/opportunities/check-opportunities?id='.$opportunity_id;
	            self::sendMail("User has changed their opportunity. Please approve it here: $adminUrl", Yii::$app->params['adminEmail']);
				break;
		}
	}

	public static function sendMail($body, $email){
		return Yii::$app->mailer->compose()
	     ->setFrom([Yii::$app->params['adminEmail']=>Yii::$app->params['adminEmail']])
	     ->setTo($email)
	     ->setSubject('From Connecting Talents ' . Yii::$app->params['myApplication'])
		 ->setTextBody($body)
	     ->send();
	}

	public static function sendMailByMandrill($template, $email, $params = []){
		return Yii::$app->mailer
			->compose($template,$params)
			->setTo($email)
			->send();
	}
}