<?php
require '../modules/vendor/autoload.php';
require '../../database/db_tdauth.php';
require '../../fonctions/general.php';
require '../variables.php';

$login_existant = "FALSE";

use Stevenmaguire\OAuth2\Client\Provider\Microsoft;

$provider = new Microsoft([
	'clientId' => $AuthMicrosoft_clientID,
	'clientSecret' => $AuthMicrosoft_secretID,
	'redirectUri' => site() . '/assets/auth/microsoft/login.php',
]);

if (!isset($_GET['code'])) {
	$authUrl = $provider->getAuthorizationUrl();
	$_SESSION['oauth2state'] = $provider->getState();
	header('Location: ' . $authUrl);
	exit;
} else {
	$token = $provider->getAccessToken('authorization_code', [
		'code' => $_GET['code']
	]);

	try {
		$user = $provider->getResourceOwner($token);
		//var_dump($user->toArray());

		// Use these details to create a new profile

		$MS_userid = $user->getId();
		$MS_username = $user->getFirstName();
		$MS_mail = $user->getEmail();

		$requete = 'SELECT * FROM auth WHERE MicrosoftID = "' . $MS_userid . '"';
		// print_r($requete);
		$liste_resultat = $tdauth_mysqli->query($requete) or die('<p>Échec lors de la consultation : (' . $tdauth_mysqli->errno . ') ' . $tdauth_mysqli->error . '</p>');
		while (($ligne = $liste_resultat->fetch_assoc()) <> NULL) {
			$login_existant = "TRUE";
			if ($ligne['Platform'] == 'Microsoft') {
				$reqUpdate = 'UPDATE `auth` SET `Pseudo` = "' . $MS_username . '", `Email` = "' . $MS_mail . '", `MicrosoftEmail` = "' . $MS_mail . '" WHERE `idAuth` = "' . $ligne['idAuth'] . '"';
				$resultatUpdate = $tdauth_mysqli->query($reqUpdate) or die('<p>Échec lors de la consultation : (' . $tdauth_mysqli->errno . ') ' . $tdauth_mysqli->error . '</p>');
			}
			$_SESSION['auth'] = array(
				"etat" => 1,
				"pseudo" => $retVal = ($ligne['Platform'] == 'Microsoft') ? $MS_username : $ligne['Pseudo'],
				"platform" => $ligne['Platform'],
				"email" => $retVal = ($ligne['Platform'] == 'Microsoft') ? $MS_mail : $ligne['Email'],
				"id" => $ligne['idAuth'],
				"statut" => $ligne['Statut'],
				"discordID" => $ligne['DiscordID'],
				"microsoftID" => $ligne['MicrosoftID'],
				"discordEmail" => $ligne['DiscordEmail'],
				"microsoftEmail" => $ligne['MicrosoftEmail'],
				"image" => $ligne['Image']
			);
		}
		$liste_resultat->close();

		if ($login_existant == "TRUE") {
			header('Location: ' . site() . '/?p=microsoft-session&id=' . $MS_userid);
		} else {
			$pseudo_existant = "FALSE";
			$email_existant = "FALSE";

			$requete = 'SELECT * FROM auth WHERE Pseudo = "' . $MS_username . '"';
			$liste_resultat = $tdauth_mysqli->query($requete) or die('<p>Échec lors de la consultation : (' . $tdauth_mysqli->errno . ') ' . $tdauth_mysqli->error . '</p>');
			while (($ligne = $liste_resultat->fetch_assoc()) <> NULL) {
				$pseudo_existant = "TRUE";
			}
			$liste_resultat->close();
			$requete = 'SELECT * FROM auth WHERE Email = "' . $email_inscription . '"';
			$liste_resultat = $tdauth_mysqli->query($requete) or die('<p>Échec lors de la consultation : (' . $tdauth_mysqli->errno . ') ' . $tdauth_mysqli->error . '</p>');
			while (($ligne = $liste_resultat->fetch_assoc()) <> NULL) {
				$email_existant = "TRUE";
			}
			$liste_resultat->close();

			if ($pseudo_existant == "FALSE" and $email_existant == "FALSE") {
				$requete = 'INSERT INTO auth (idAuth, Platform, Pseudo, Email, MicrosoftID, MicrosoftEmail) VALUES (NULL, "Microsoft", "' . $MS_username . '", "' . $MS_mail . '", "' . $MS_userid . '", "' . $MS_mail . '")';
				// echo $requete;
				$liste_resultat = $tdauth_mysqli->query($requete) or die('<p>Échec lors de la consultation : (' . $tdauth_mysqli->errno . ') ' . $tdauth_mysqli->error . '</p>');
				$requete = 'SELECT * FROM auth WHERE MicrosoftID = "' . $MS_userid . '"';
				// print_r($requete);
				$login_existant = "FALSE";
				$liste_resultat = $tdauth_mysqli->query($requete) or die('<p>Échec lors de la consultation : (' . $tdauth_mysqli->errno . ') ' . $tdauth_mysqli->error . '</p>');
				while (($ligne = $liste_resultat->fetch_assoc()) <> NULL) {
					$login_existant = "TRUE";
					$_SESSION['auth'] = array(
						"etat" => 1,
						"pseudo" => $ligne['Pseudo'],
						"platform" => $ligne['Platform'],
						"email" => $ligne['Email'],
						"id" => $ligne['idAuth'],
						"statut" => $ligne['Statut'],
						"discordID" => $ligne['DiscordID'],
						"discordEmail" => $ligne['DiscordEmail'],
						"microsoftID" => $ligne['MicrosoftID'],
						"microsoftEmail" => $ligne['MicrosoftEmail'],
						"image" => $ligne['Image']
					);
				}
				$liste_resultat->close();
				if ($login_existant == "TRUE") {
					header('Location: ' . site() . '/?p=microsoft-session&id=' . $MS_userid);
				} else {
					header('Location: ' . site() . '/signup');
				}
			} else {
				header('Location: ' . site() . '/login');
			}
		}

		echo '
	    <!DOCTYPE html>
	    <html lang="fr">
	    <!--=======================-->
	    <!--====== HTML HEAD ======-->
	    <!--=======================-->
	    <head>
	    	<meta name="robots" content="noindex, nofollow">
	     	<meta name="author" content="Azerxim">
	     	<meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>
	     	<meta name="description" content="Accueil de TopazDev"/>
	     	<meta name="keywords" content=""/>
	     	<meta name="viewport" content="width=device-width, initial-scale=1">
	     	<title>TopazDev Auth Microsoft</title>
		
	     	<link rel="shortcut icon" href="https://spinelle.eu/images/favicon_red.ico"/>
	    </head>
	    <body>';
		echo '<br>' . $login_existant;
		echo '
		</body>';

	} catch (Exception $e) {
		// Failed to get user details
		exit('Oh dear...');
	}

	// Use this to interact with an API on the users behalf
	// echo $token->getToken();
}

?>