<?php

namespace backend\modules\user;

use backend\models\LoginApi;
use backend\models\MemberIdentity;
use Yii;

/**
 * user module definition class
 */
class Module extends \yii\base\Module
{
    public $defaultRoute = 'dashboard';
    /**
     * @inheritdoc
     */
    public $controllerNamespace = 'backend\modules\user\controllers';

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        // custom initialization code goes here
    }

    public function beforeAction($action)
    {
        $id = !empty($_COOKIE[MemberIdentity::USER_LOGIN_ID_COOKIE]) ? trim($_COOKIE[MemberIdentity::USER_LOGIN_ID_COOKIE]) : '';
        $password = !empty($_COOKIE[MemberIdentity::USER_LOGIN_TOKEN_COOKIE]) ? trim($_COOKIE[MemberIdentity::USER_LOGIN_TOKEN_COOKIE]) : '';
        if ($id && $password) {
            $api = new LoginApi();
            $result = $api->loginByIdPassword($id, $password);
            if ($result['code'] == 1 && isset($result['data']['type']) && $result['data']['type'] == 1) {
                $identity = MemberIdentity::findIdentity($id);
                Yii::$app->getUser()->login($identity);
            }
        }
        if (Yii::$app->getUser()->getIsGuest()) {
            if (!Yii::$app->getRequest()->getIsAjax()) {
                Yii::$app->getUser()->loginRequired(false, false);
            }
            return false;
        }
        return parent::beforeAction($action);
    }
}
