<?php
namespace PortalPeople\oauth2\controllers;

use Yii;
use yii\web\Controller;

use yii\filters\{AccessControl, VerbFilter};

/**
 * UserController implements the CRUD actions for Visitors model.
 */
class UserController extends Controller
{
    public $defaultAction = 'login';
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'actions' => ['login'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['authorize'],
                        'allow' => true,
                        'roles' => ['@'],
                        'matchCallback' => function ($rule, $action) {
                            return !Yii::$app->user->isGuest;
                        }
                    ],
                ],
                
                'denyCallback' => function ($rule, $action) {
                    if (Yii::$app->user->isGuest) {
                      return $this->redirect(['user/login']);                    
                    } 
                }
            ],
        ];
    }
    

    public function actionAuthorize()
    {
        $module = Yii::$app->getModule('oauth2');
        $request = \OAuth2\Request::createFromGlobals();
        $response = new \OAuth2\Response();
/*
        // Validate the authorize request
        if (!$module->server->validateAuthorizeRequest($request, $response)) {
            $response->send();
            Yii::$app->end();
        }*/

        // Display the authorization form
        if (Yii::$app->request->isPost) {
            $isAuthorized = !Yii::$app->user->isGuest;
            $module->server->handleAuthorizeRequest($request, $response, $isAuthorized, Yii::$app->user->identity->user_id);
            $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
            if(!empty($request->query('redirect_uri'))){

                $client = new \yii\httpclient\Client();
                
                $redirect = $client->createRequest()
                ->setMethod('POST')
                ->setUrl($request->query('redirect_uri'))
                ->setData([
                    'grant_type' => 'authorization_code', 
                    'code' => $code,
                    'redirect_uri' => $request->query('redirect_uri'),
                    ])
                    ->addHeaders(['authorization' => 'basic '.base64_encode($request->query('client_id').':' .Yii::$app->user->identity->oauthSecrets->client_secret)])
                    ->send();
                    
                    Yii::$app->response->format = 'json';
                    return json_decode($redirect->content);
                } else {
                    return $code;
                }
            //$response->send();
            
        } else {
            $this->layout = '@backend/views/layouts/prelogin';
            // Render the authorization form
            return $this->render('authorize', [
                'client_id' => $request->query('client_id'),
                'response_type' => $request->query('response_type'),
                'redirect_uri' => $request->query('redirect_uri'),
                'state' => $request->query('state'),
            ]);
        }
    }
    # region Default Yii login action with added support for OpenID Connect reauthentication
    /**
     * Allow the user to login
     * @param bool $reauthenticate
     * @param string|null $clientAuthorizationRequestId
     * @return string|\yii\web\Response
     */
    public function actionLogin()
    {
        $this->layout = '@backend/views/layouts/prelogin';
        if (!Yii::$app->user->isGuest) {
            return $this->goBack();
        }

        $model = new \backend\models\Loginform();
		if(Yii::$app->request->isPost){
			$model->load(Yii::$app->request->post());
			Yii::warning($model);
			$result = $model->login();
		} else {
			$result = false;
		}
        if ($result) {
            if(Yii::$app->request->get('redirect')){
                return $this->redirect(Yii::$app->request->get('redirect'));
            }
            if(array_key_exists('enable_mfa', Yii::$app->params) && Yii::$app->params['enable_mfa'] == true){
                if (Yii::$app->user->identity->adv->firstlogin == true){
                    return  $this->redirect(['user/mfa']);
                } elseif(Yii::$app->user->identity->adv->firstlogin == false && empty(Yii::$app->user->identity->tfa_code) == true ) {
                    return $this->redirect(['user/mfa']);
                }
            } 
            $user = Yii::$app->user->identity;
            return $this->redirect(['authorize', 
                'response_type' => 'code',
                'client_id' => $user->oauthSecrets->client_id,
                'state' => 'auth',
                'redirect_uri' => $user->oauthSecrets->redirect_uri,
            ]);
        }

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

}