<?php

class GoogleLogin_Controller_Auth extends vB5_Frontend_Controller
{
	public function actionStartTokenRefresh()
	{
		$api = Api_InterfaceAbstract::instance();
		$result = $api->callApi('googlelogin:ExternalLogin', 'getTokenRedirect', []);
		if(!empty($result['errors']))
		{
			$this->sendAsJson($result);
			return true;
		}

		header('Location: ' . $result['url']);
	}

	public function actionCallback()
	{
		$api = Api_InterfaceAbstract::instance();
		$code = $_GET['code'] ?? '';
		$state = $_GET['state'] ?? '';
		$error = $_GET['error'] ?? '';
		// https://developers.google.com/identity/oauth2/web/guides/error#oauth_error_responses
		if ($error)
		{
			// This is most likely because the user denied the OAuth request.
			// In that case, it seems like we get $error == 'access_denied'.
			// It's not clear what other errors there are, but we should probably show a
			// error message like "please try again and allow the authorization request"
			// This can happen if the user clicks "cancel" in the popup when they try to either link their account or login with
			// Google.
			if ($error == 'access_denied')
			{
				return $this->showErrorPageBare(['googlelogin_error_access_denied_inside_popup']);
			}
		}

		$result = $api->callApi('googlelogin:ExternalLogin', 'confirmToken', [$code, $state]);

		if(isset($result['errors']))
		{
			return $this->showErrorPageBare($result['errors']);
		}

		//Ping the opener.
		//Due to issues with firefox not allowing us to close the window the html got too
		//complex to hardcode here.  Make into a template but don't use the full page framework.
		$ping = new vB5_Template('googlelogin_confirmresponse');
		echo $ping->render();
	}

	public function actionLogin()
	{
		$url = $_REQUEST['url'] ?? '';
		$userid = $_REQUEST['userid'] ?? null;

		$api = Api_InterfaceAbstract::instance();
		$result = $api->callApi('googlelogin:ExternalLogin', 'verifyAuthAndLogin', [$url, $userid]);
		if ($result['success'])
		{
			vB5_Cookie::setSessionCookies($result['login'], 'external', true);
			$newUserInfo = $api->callApi('user', 'fetchUserinfo', ['nocache' => true], true);
			$result['newtoken'] = $newUserInfo['securitytoken'];
		}
		$this->sendAsJson($result);
	}
}
