<?php
require_once 'Plugg/RoutingController.php';

class Plugg_Admin extends Plugg_RoutingController
{
    public function __construct()
    {
        parent::__construct('Index', 'Plugg_Admin_', dirname(__FILE__) . '/Admin');
        $this->addFilters(array('isAuthenticated', 'isAdmin'));
        $this->_eventNamePrefix = 'PluggAdmin';
    }

    public function isAuthenticatedBeforeFilter(Sabai_Application_Context $context)
    {
        if (!$context->user->isAuthenticated()) {
            if ($this->pluginManager->getPlugin('user')) {
                // Redirect to the user plugin login page if the plugin is active
                $context->response
                    ->setError(
                        sprintf(
                            $this->gettext->_('You must <a href="%s">login</a> to perform this operation'),
                            $this->url->create(array(
                                'script_alias' => 'main',
                                'base' => '/user/login',
                                'params' => array('return' => 1))
                            )
                        ),
                        array(
                            'script_alias' => 'main',
                            'base' => '/user/login',
                            'params' => array('return' => 1)
                        )
                    )
                    ->send($this->_application);
            } else {
                $context->response
                    ->setError($this->gettext->_('Invalid request'), array('script_alias' => 'main'))
                    ->send($this->_application);
            }
        }
    }

    public function isAuthenticatedAfterFilter(Sabai_Application_Context $context){}

    public function isAdminBeforeFilter(Sabai_Application_Context $context)
    {
        if (!$context->user->isSuperUser()) {
            $context->response
                ->setError($this->gettext->_('Access denied'), $this->url->create(array(
                    'script' => 'index.php'
                )))
                ->send($this->_application);
        }
    }

    public function isAdminAfterFilter(Sabai_Application_Context $context){}
}