<?php

	require_once 'config.php';

	// IF A SESSION ALREADY EXISTS, USE EXISTING TOKEN
	// ELSE IF THERE'S NO SESSION BUT $_GET HAS USER AUTHCODE, OBTAIN NEW TOKEN
	// ELSE REDIRECT TO ERROR PAGE
	if(isset($_SESSION['token'])) {
		$client->setAccessToken($_SESSION['token']);
	}
	else if(isset($_GET['code'])) {
		$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
		
		// IF 'code' IS NOT AUTHENTIC, TOKEN IS AN ARRAY WITH 'error' SET TO SOMETHING (i.e. 'invalid_grant')
		if(isset($token['error'])) {
			header('Location: ./logout.php');
			die();
		}
		
		$_SESSION['token'] = $token;
	}
	else {
		header('Location: ../home.php');
		exit();
	}
	
// 	var_dump($_GET);
// 	var_dump($_SESSION);
		
	$oAuth = new Google_Service_Oauth2($client);
	$userData = $oAuth->userinfo_v2_me->get();
	
	/*
			Algunos keys de los datos que se pueden extraer:
			
			(USADOS)
			-SCOPE 'profile': name, picture
			-SCOPE 'email': email
			
			(NO USADOS)
			*-SCOPE 'profile': gender, familyName, givenName, hd, id, link*, locale, verifiedEmail
			*-SCOPE 'profile': internal_gapi_mappings, modelData, processed

			Lista completa de scopes: https://developers.google.com/identity/protocols/googlescopes
	*/
	
	require_once 'dbh.inc.php';
	
	$query = 'SELECT * FROM `researcher` WHERE `email` = "'.$userData['email'].'";';
	$result = mysqli_query($connection, $query);
	$dbUserData = mysqli_fetch_assoc($result);
	
	$_SESSION['result'] = $result;
	
	// IF DB CAN'T FETCH USER DATA, IT MUST BE BECAUSE USER IS UNAUTHORIZED
	// ELSE KEEP RETRIEVING USER DATA FROM DB
	if($dbUserData == NULL) {
		$_SESSION['error'] = 'unauthorized';
	}
	else {
	
		// NECESSARY FOR RETRIEVING DATA FROM DB ON LATER PAGES
		$_SESSION['email'] = $userData['email'];
		
		//### OPTIONAL ###
		$_SESSION['newUser'] = false;
	
		// IF USER IS NEW, UPDATE DB WITH USER INFO FROM GOOGLE
		if($dbUserData['name'] == NULL && $dbUserData['picture'] == NULL) {
			$query = 'UPDATE `researcher` SET `name`="'.$userData['name'].'", `picture`="'.$userData['picture'].'" WHERE `email`="'.$userData['email'].'";';
			mysqli_query($connection, $query);
			
			//### OPTIONAL ###
			$_SESSION['newUser'] = true;
		}
		
	}

	//### FOR DEBUGGING ###
	$_SESSION['dbUserData'] = $dbUserData;
	$_SESSION['error_set'] = isset($_SESSION['error']);
	//### FOR DEBUGGING ###
	
	header('Location: ../home.php');
	exit();

























	/*
			Additional links that helped:
			
			Google Developers Tutorial (Javascript): https://developers.google.com/identity/sign-in/web/sign-in
			Sample Code: https://github.com/GoogleChromeLabs/google-sign-in
			Branding Guidelines: https://developers.google.com/identity/branding-guidelines
			Developer's Console: https://console.developers.google.com
			
			Tutorials:
				-Login With Google Account Using PHP & Client API: https://www.youtube.com/watch?v=hazMyK_cnzk
				-Login with Google Account using PHP: https://www.codexworld.com/login-with-google-api-using-php/
	*/