<?php

namespace common\modules\support\controllers;

use Yii;
use yii\filters\AccessControl;

use common\components\FrontendController;
use common\modules\support\models\LoginForm;
use common\modules\users\models\User;

/**
 * Default controller for the `support` module
 */
class DefaultController extends FrontendController
{
	public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'user' => 'support',
                'only' => ['login', 'logout'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['login'],
                        'roles' => ['?'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['logout'],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function actionLogin()
    {
        $this->page_title = 'Техническая поддержка';
		$this->layout = "@backend/views/layouts/blank";
        $model = new LoginForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) 
        {
            if($model->user->role == User::ROLE_SUPPORT)
            {
                $model->login();
                return $this->redirect(['/support']);
            }
            else
            {
                $model->addError('password', 'Доступ запрещен!');
            } 
        }

        return $this->render('@backend/views/site/login', [
            'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        Yii::$app->support->logout();

        return $this->redirect(['/support']);
    }
}
