<?php

namespace common\behaviors;

use backend\models\MemberIdentity;
use common\helpers\Utils;
use yii\base\Behavior;
use yii\web\User;
use yii\web\UserEvent;

class LoginCookieBehavior extends Behavior
{
    /**
     * @return array
     */
    public function events()
    {
        return [
            User::EVENT_AFTER_LOGIN => 'afterLogin',
        ];
    }

    /**
     * @param UserEvent $event
     */
    public function afterLogin($event)
    {
        /** @var MemberIdentity $identity */
        $identity = $event->identity;
        if ($identity == null) {
            return;
        }
        if ($identity->type == MemberIdentity::MEMBER_TYPE_USER) {
            setcookie(MemberIdentity::USER_LOGIN_ID_COOKIE, null, null, '/', Utils::getTopDomain());
            setcookie(MemberIdentity::USER_LOGIN_TOKEN_COOKIE, null, null, '/', Utils::getTopDomain());
        } elseif ($identity->type == MemberIdentity::MEMBER_TYPE_IB) {
            setcookie(MemberIdentity::IB_LOGIN_ID_COOKIE, null, null, '/', Utils::getTopDomain());
            setcookie(MemberIdentity::IB_LOGIN_TOKEN_COOKIE, null, null, '/', Utils::getTopDomain());
        } else {
            return;
        }
    }
}