<?php
function o365_shortcode_m365_mgt_login_button( $atts ) {
    ob_start();
	$atts = shortcode_atts( array(
		'id' 				=> 'mycustomid',
		'tenant_id'			=> '',
		'appid'				=> '',
		'redirect_url'		=> '',
		'signed_in_button'	=> 'Private Client Area',
		'client_area_url'	=> '',
		'template'			=> 'mgt_login_button.php',
	), $atts, 'm365_mgt_login_button' );
	
	?><style>.login-search-wrapper, .client-login-wrapper {visibility: hidden;}.top-login {width: 100%;display: flex;flex-direction: row;flex-wrap: wrap;justify-content: space-around;align-items: flex-end;margin-top: 0px;visibility: visible !important;}.login-text-wrapper {visibility: visible;}</style>

		<script src="https://unpkg.com/@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
		<!-- <mgt-msal-provider client-id="<?php //echo $atts['appid'];?>" login-type="redirect" authority="https://login.microsoftonline.com/<?php //echo $atts['tenant_id'];?>" redirect-uri="<?php //echo $atts['redirect_url'];?>" ></mgt-msal-provider> -->
		<mgt-msal-provider client-id="<?php echo $atts['appid'];?>" login-type="redirect" authority="https://login.microsoftonline.com/common" redirect-uri="<?php echo $atts['redirect_url'];?>" ></mgt-msal-provider>
		<div class="mgt-login-logout-button"></div>
		<mgt-login id="login-component">
			<template data-type="signed-in-button-content">
				<div class="login_button_cls">
					<?php if(!empty($atts['signed_in_button'])) {
						echo $atts['signed_in_button'];
					} else {
						echo 'Private Client Area';
					}
					?>
				</div>
			</template>

			<template data-type="flyout-commands">
				<style type="text/css">
					<?php echo $atts['signout_style'];?>
				</style>
				<div>
					<button class="sign_out_button" data-props="@click: handleSignOut">Sign Out</button>
					<?php if( ! empty($atts['client_area_url']) ) {?>
						<a href="<?php echo $atts['client_area_url'];?>" class="private-client-area" >Go to Private Client Area</a>
					<?php } ?>
				</div>
			</template>
		</mgt-login>

		<script type="module">
			<?php
				global $wp;
			?>
			document.querySelector('mgt-login').addEventListener('loginCompleted', e => {
				jQuery(".mgt-login-logout-button").append(
				`<?php if( ! empty($atts['client_area_url']) ) {?>
					<a href="<?php echo $atts['client_area_url'];?>" class="private-client-area" >Go to Private Client Area</a>
				<?php } ?>`);
				jQuery(".mgt-login-logout-button").append(`<a class="signout_button" href="<?php echo wp_logout_url( 'https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=https://wpintegrate.net/my-account-b2b' ); ?>">Sign Out</a>`);
				
				document.querySelector('#login-component').style.display = 'none';
			});

			jQuery(document).on("click", ".signout_button", (e) => {
				e.preventDefault();
				
				// Deleting all the cookies and localStorage when user logged out from Sharepoint template
				localStorage.clear();

				document.cookie = "msal.<?php echo $atts['appid'];?>.idtoken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
				document.cookie = "msal.<?php echo $atts['appid'];?>.error.description=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
				document.cookie = "msal.<?php echo $atts['appid'];?>.client.info=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

				setTimeout(function(){ 
					location.href = '<?php echo wp_logout_url( 'https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri=https://wpintegrate.net/my-account-b2b' ); ?>';
				}, 3000);
			});

			jQuery(document).ready((e) => {
				var loginComponent = document.querySelector("#login-component");

				// Login Component
				loginComponent.addEventListener('templateRendered', (e) => {
					let templateType = e.detail.templateType;
					let dataContext = e.detail.context;
					let element = e.detail.element;

					if(templateType == 'signed-in-button-content') {
						const provider = mgt.Providers.globalProvider;
						console.log(mgt);
						<?php if( ! is_user_logged_in() && is_plugin_active( 'o365-user-auth/o365-user-auth.php' ) ) { ?>
							var token = '';
							if (provider && provider.state === mgt.ProviderState.SignedIn) {
								
								const tokenPromise = provider.getAccessToken({scopes: ['https://graph.microsoft.com/.default']})
								
								tokenPromise.then(function(tok) {
									token = tok;
									console.log(token);
									let data = {
										"action": "o365_calling_authentication_using_user_auth_with_mgt",
										"365_jwt":provider._userAgentApplication.account.idToken,
										xhrFields: {withCredentials: true},
										crossDomain: true,
										"token": token
									};
									
									jQuery.post( '<?php echo admin_url('admin-ajax.php');?>', data, function( response, txtStatus, jqXHR )
									{
										if( response.success )
										{
											setTimeout(function(){
												jQuery('.overlay').hide();
												location.reload();
											},1000);
										}
									})
									.fail(function()
									{
										alert("Error in logging in the user.");
									});
								});
							}

						<?php } ?>
					}
				});
			});
		</script>
		<?php
	//}
	$result = ob_get_clean();
	return $result;
}