<?php
	session_start();
	$url = 'https://adfs.alanyeung.co/adfs/oauth2/token';
    $fields = array(
        'grant_type' => 'authorization_code',
		'client_id' => 'c5c68c24-153c-4bf5-90e7-7552baea7f39',
		'redirect_uri' => 'https://aroz.alanyeung.co/AOB/oauth.php',
		'code' => $_POST["code"],
    );
    $postvars = http_build_query($fields);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
	$data = json_decode($result,true);
	$jwt = explode('.',  $data['id_token']);
	$userinfo = [];
	$userinfo = json_decode(base64_decode($jwt[1]), true);
	if($userinfo == []){
		echo "Error!";
		//header('Location: https://adfs.alanyeung.co/adfs/oauth2/authorize?client_id=c5c68c24-153c-4bf5-90e7-7552baea7f39&redirect_uri=https%3A%2F%2Faroz.alanyeung.co%2FAOB%2Foauth.php&scope=openid&response_type=code&response_mode=form_post&nonce=tacv8wxjk5');
	}else{
		//print_r($userinfo);
		header('aoAuth: oAUTH');
		$_SESSION["method"] = "ADFS";
		$_SESSION["login"] = $userinfo["upn"];
		setcookie("username",$userinfo["upn"],time()+ 172800 );
		setcookie("password","OAuthADFS",time()+ 172800 );
		//print_r($userinfo);
		echo '<script>localStorage.ArOZusername = "'.$userinfo["upn"].'";window.location = "./index.php"</script>';
	}
?>