<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Controller;

use Admin\Data\Common;
use Admin\Service\AuthManager;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\MvcEvent;
use Laminas\Validator\AbstractValidator;

class AdminActionController extends AbstractActionController
{
    protected function attachDefaultListeners()
    {
        $events = $this->getEventManager();
        $events->attach(MvcEvent::EVENT_DISPATCH, [$this, 'checkAdminFilterAccess'], 99);
        parent::attachDefaultListeners();
    }

    /**
     * 检查管理登录状态及权限
     * @param MvcEvent $event
     * @return bool
     */
    public function checkAdminFilterAccess(MvcEvent $event)
    {
        //后台语言包
        $baseConfig = Common::configValue('base', 'config');
        if (isset($baseConfig['a_language']) && !empty($baseConfig['a_language']) && $baseConfig['a_language'] != 'zh_CN') {
            $translator = $event->getApplication()->getServiceManager()->get('MvcTranslator');
            $translator->setLocale($baseConfig['a_language']);
            //服务器端验证进行语言设置
            AbstractValidator::setDefaultTranslator($translator);
        }

        $controller     = $event->getTarget();
        $controllerName = $event->getRouteMatch()->getParam('controller', null);

        $actionName     = $event->getRouteMatch()->getParam('action', null);
        $actionName = str_replace('-', '', lcfirst(ucwords($actionName, '-')));

        $authManager= $event->getApplication()->getServiceManager()->get(AuthManager::class);

        if($controllerName != IndexController::class) {
            $status = $authManager->filterAccess($controllerName, $actionName);
            if($status == -1) {
                return $controller->redirect()->toRoute('login');
            }elseif($status == -2) {
                return $controller->redirect()->toRoute('home/default', ['action' => 'notAuthorized']);
            }
        }

        return true;
    }
}