<?php
/**
 * @package     Sven.Bluege
 * @subpackage  com_eventgallery
 *
 * @copyright   Copyright (C) 2005 - 2019 Sven Bluege All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

jimport( 'joomla.application.component.controllerform' );


class EventgalleryControllerGooglephotosaccount extends JControllerForm
{
    public function googlecallback() {

        $app = \Joomla\CMS\Factory::getApplication();
        $id = $app->input->getInt('state', null);
        $code = $app->input->getRaw('code', null);

        if ($code == null || $id == null) {
            $app->close('invalid request');
        }

        /**
         * @var EventgalleryLibraryFactoryGooglephotosaccount $factory
         */
        $factory = EventgalleryLibraryFactoryGooglephotosaccount::getInstance();
        $account = $factory->getGooglePhotosAccountById($id);

        $callbackUrl = \Joomla\CMS\Router\Route::_('index.php?option=com_eventgallery&task=googlephotosaccount.googlecallback', false, 1, true);
        $data = [
            'code' => $code,
            'client_id' => $account->getClientId(),
            'client_secret' => $account->getSecret(),
            'grant_type' => 'authorization_code',
            'redirect_uri' => $callbackUrl,
        ];

        $response = \Joomla\CMS\Http\HttpFactory::getHttp()->post('https://oauth2.googleapis.com/token', $data, ['Content-Type' => 'application/x-www-form-urlencoded'], 3);
        if ($response->code == 200) {
            $response_body = json_decode($response->body);
            echo '
            <script>
                window.opener.document.getElementsByClassName("google-photos-api-oauth-input")[0].value = \''. $response_body->refresh_token .'\';
                window.close();
            </script>
            ';
        } else {
            echo "An error has occured: " . $response->body;
        }

        $app->close();

    }
}
