<?php
$action = (isset($_GET['action']) ? $_GET['action'] : "");
require '../modules/vendor/autoload.php';
require '../../database/db_tdauth.php';
require '../../fonctions/general.php';
require '../variables.php';

$login_existant = "FALSE";

use Xwilarg\Discord\OAuth2;

// Sample JSON configuration file, contains the following fields:
// clientId: Client ID of the application
// secret: Secret of the application
// url: The redirect URL (URL called after the user is logged in, must be registered in https://discordapp.com/developers/applications/[YourAppId]/oauth)
// $auth = json_decode(file_get_contents('Credentials.json'), true);
$auth = array(
	'clientId' => $AuthDiscord_clientID,
	'secret' => $AuthDiscord_secretID,
	'url' => site() . '/assets/auth/discord/login.php'
);
$oauth2 = new OAuth2($auth["clientId"], $auth["secret"], $auth["url"]);

if ($oauth2->isRedirected() === false) { // Did the client already logged in ?
	// The parameters can be a combination of the following: connections, email, identity or guilds
	// More information about it here: https://discordapp.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes
	// The others parameters are not available with this library
	$oauth2->startRedirection(['identify', 'guilds', 'email']);
} else {
	// We preload the token to see if everything happened without error
	$ok = $oauth2->loadToken();
	if ($ok !== true) {
		// A common error can be to reload the page because the code returned by Discord would still be present in the URL
		// If this happen, isRedirected will return true and we will come here with an invalid code
		// So if there is a problem, we redirect the user to Discord authentification
		$oauth2->startRedirection(['identify', 'email']);
	} else {
		$user = $oauth2->getUserInformation();

		$DISCORD_userid = $user["id"];
		$DISCORD_username = $user["username"];
		$DISCORD_mail = $user["email"];
		$DISCORD_locate = $user["locate"];
		$DISCORD_useravatar = 'https://cdn.discordapp.com/avatars/' . $user["id"] . '/' . $user["avatar"];

		$requete = 'SELECT * FROM auth WHERE DiscordID = "' . $DISCORD_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'] == 'Discord') {
				$reqUpdate = 'UPDATE `auth` SET `Pseudo` = "' . $DISCORD_username . '", `Email` = "' . $DISCORD_mail . '", `DiscordName` = "' . $DISCORD_username . '", `DiscordEmail` = "' . $DISCORD_mail . '", `Image` = "' . $DISCORD_useravatar . '" 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'] == 'Discord') ? $DISCORD_username : $ligne['Pseudo'],
				"platform" => $ligne['Platform'],
				"email" => $retVal = ($ligne['Platform'] == 'Discord') ? $DISCORD_mail : $ligne['Email'],
				"id" => $ligne['idAuth'],
				"statut" => $ligne['Statut'],
				"discordID" => $ligne['DiscordID'],
				"discordEmail" => $ligne['DiscordEmail'],
				"microsoftID" => $ligne['MicrosoftID'],
				"microsoftEmail" => $ligne['MicrosoftEmail'],
				"image" => $retVal = ($ligne['Platform'] == 'Discord') ? $DISCORD_useravatar : $ligne['Image']
			);
		}
		$liste_resultat->close();

		if ($login_existant == "TRUE") {
			header('Location: ' . site() . '/profil');
		} else {
			$pseudo_existant = "FALSE";
			$email_existant = "FALSE";

			$requete = 'SELECT * FROM auth WHERE Pseudo = "' . $DISCORD_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, Image, Email, DiscordID, DiscordName, DiscordEmail) VALUES (NULL, "Discord", "' . $DISCORD_username . '", "' . $DISCORD_useravatar . '", "' . $DISCORD_mail . '", "' . $DISCORD_userid . '", "' . $DISCORD_username . '", "' . $DISCORD_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 DiscordID = "' . $DISCORD_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() . '/profil');
				} else {
					header('Location: ' . site() . '/signup');
				}
			} else {
				header('Location: ' . site() . '/login');
			}
		}

		$html = '
		<!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 Discord</title>

			<link rel="shortcut icon" href="https://spinelle.eu/images/favicon_red.ico"/>
		</head>

		<!--=======================-->
		<!--====== HTML BODY ======-->
		<!--=======================-->

		<body>';
		echo $html;
		echo '<br>' . $login_existant . '<br><br>';

		// var_dump($_SESSION['auth']);
		// var_dump($user);
	}
}

?>