<?php

use System\Response;
use System\Session;
use System\Config;

$provider = new League\OAuth2\Client\Provider\Google([
    'clientId'     => Config::social('google')['clientId'],
    'clientSecret' => Config::social('google')['clientSecret'],
    'redirectUri'  => Config::social('google')['redirectUri'],
    'hostedDomain' => Config::social('google')['hostedDomain']
]);

// if there is an error in get
if(!empty($_GET['error'])) SomethingWrong('login');

if(empty($_GET['code'])) {
    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl();
    Session::put('oauth2state', $provider->getState());
    header('Location: ' . $authUrl);
    exit;
}


if(!isset($_GET['state']) || !Session::exists('oauth2state') || empty($_GET['state']) || ($_GET['state'] !== Session::get('oauth2state'))) {
    // State is invalid, possible CSRF attack in progress
    Session::delete('oauth2state');
    SomethingWrong('login');
}

// delete the cookie anyway now
Session::delete('oauth2state');

// Try to get an access token (using the authorization code grant)
$token = $provider->getAccessToken('authorization_code', [
    'code' => $_GET['code']
]);

// Optional: Now you have a token you can look up a users profile data
try {

    // We got an access token, let's now get the owner details
    $ownerDetails = $provider->getResourceOwner($token);

} catch (Exception $e) {
    SomethingWrong('login');
}


$email = $ownerDetails->getEmail();
$name = $ownerDetails->getName();
$id = $ownerDetails->getId();
$image = $ownerDetails->getAvatar();

// if not complete data
if(!$email && !$name && !$id) SomethingWrong('login');

// if there is count simply login the user
if($usero->login($email, null, 'yes'))
    Response::redirect('/');


// else he's new lets add this one
$userFields = [
    'username' => $id,
    'email' => $email,
    'role' => 'user',
    'status' => 'active'
];

$usero->create($userFields);

// now try to login again
if($usero->login($email, null, 'yes'))
    Response::redirect('/');

SomethingWrong('login');