<?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\Service\AuthManager;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\MvcEvent;

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)
    {
        $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;
    }
}