<?php defined('ABSPATH') OR die('Access denied!');
/**
 * Returns all post staus or user role associated with posts or users. This is filter. Which information user
 * wants to synchronize
 * @global object $wpdb
 */
function o365_action_wp_ajax_o365_setings_page_save_data(){

	if ( ! function_exists( 'is_plugin_active' ) )
	{
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
	}

	$delete_settings = "";
	$shared_settings = "";
	$o365_graph_version = '';
	$b2b_shared_settings = "";
	$o365_graph_endpoints = '';
	$o365_national_endpoints = '';
	$network_shared_settings = '';

	if( isset( $_POST['delete_settings'] ) )
	{
		 $delete_settings = sanitize_text_field( $_POST['delete_settings'] );
	}
	
	if( isset( $_POST['shared_settings'] ) )
	{
		$shared_settings = sanitize_text_field( $_POST['shared_settings'] );
	}

	/* User auth shared settings checkbox save code. */
	
	if( isset( $_POST['b2b_shared_settings'] ) )
	{
		$b2b_shared_settings = sanitize_text_field( $_POST['b2b_shared_settings'] );
	}

	
	$network_shared_settings = o365_get_setting('shared_settings');
	
	if( $network_shared_settings != $shared_settings )
	{
		if ( is_multisite() ) {
			update_site_option( 'o365_base_plugin_is_verify', '0' );
		}
		$subsites = get_sites();
		foreach( $subsites as $subsite ) {
			update_blog_option( $subsite->blog_id, "o365_base_plugin_is_verify", '0' );
			delete_blog_option( $subsite->blog_id, 'sp_calendar_access_token' );
			delete_blog_option( $subsite->blog_id, 'sp_video_access_token' );
			delete_blog_option( $subsite->blog_id, 'crm_view_access_token' );
			delete_blog_option( $subsite->blog_id, 'onedrive_search_access_token' );
			delete_blog_option( $subsite->blog_id, 'outlook_search_access_token' );
			delete_blog_option( $subsite->blog_id, 'ms_booking_access_token' );
			delete_blog_option( $subsite->blog_id, 'o365_wp_sp_access_token' );
			delete_blog_option( $subsite->blog_id, 'o365_embed_access_token' );
			delete_blog_option( $subsite->blog_id, 'o365_user_auth_access_token' );
			delete_blog_option( $subsite->blog_id, 'search_access_token' );
		}
	}
	$client_id = o365_get_setting( "client_id" );
	$client_secret = o365_get_setting( "client_secret" );
	$tenant_name = o365_get_setting( "tenant_name" );
	if( $tenant_name != sanitize_text_field( $_POST['tenant_name'] ) )
	{
		$temp_tenent_name = sanitize_text_field( $_POST['tenant_name'] );
		$tenant_id = m365_get_tenant_id_by_tenant_name( $temp_tenent_name );
	}
	else
	{
		$tenant_id = o365_get_setting( "tenant_id" );
	}
	$o365_username = "";
	$o365_password = "";
	if( isset( $_POST['o365_username'] ) )
	{
		$o365_username = $_POST['o365_username'];
	}
	if( isset( $_POST['o365_password'] ) )
	{
		$o365_password = $_POST['o365_password'];
	}

	$client_object = '';
	$o365_dynamic_crm_url = '';
	$o365_display_user_id = '';
	if( isset( $_POST['client_object'] ) )
	{
		$client_object = sanitize_text_field($_POST['client_object']);
	}
	if( isset( $_POST['o365_display_user_id'] ) )
	{
		$o365_display_user_id = sanitize_text_field($_POST['o365_display_user_id']);
	}
	if( isset( $_POST['o365_dynamic_crm_url'] ) )
	{
		$o365_dynamic_crm_url = sanitize_text_field($_POST['o365_dynamic_crm_url']);
	}

	$client_id = '';
	$tenant_name = '';
	$client_secret = '';
	if( isset( $_POST['tenant_name'] ) )
	{
		$tenant_name = sanitize_text_field( $_POST['tenant_name'] );
	}
	if( isset( $_POST['client_id'] ) )
	{
		$client_id = sanitize_text_field( $_POST['client_id'] );
	}
	if( isset( $_POST['client_secret'] ) )
	{
		$client_secret = sanitize_text_field( $_POST['client_secret'] );
	}
	
	##Yammer CI AND CS
	$o365_yammer_ci = '';
	$o365_yammer_cs = '';
	if( isset( $_POST['o365_yammer_ci'] ) )
	{
		$o365_yammer_ci = sanitize_text_field( $_POST['o365_yammer_ci'] );
	}
	if( isset( $_POST['o365_yammer_cs'] ) )
	{
		$o365_yammer_cs = sanitize_text_field( $_POST['o365_yammer_cs'] );
	}

	/**
	 * Checking Enpoints
	*/
	if( isset( $_POST['o365_national_endpoints'] ) )
	{
		$o365_national_endpoints = sanitize_text_field( $_POST['o365_national_endpoints'] );
	}
	if( isset( $_POST['o365_graph_endpoints'] ) )
	{
		$o365_graph_endpoints = sanitize_text_field( $_POST['o365_graph_endpoints'] );
	}

	o365_save_settings(array(
        'client_id' => $client_id,
		'tenant_id' => $tenant_id,
		'o365_username'=>$o365_username,
		'o365_password'=>$o365_password,
		'tenant_name'    => $tenant_name,
        'client_secret' => $client_secret,
		'client_object' => $client_object,
		'o365_yammer_ci' => $o365_yammer_ci,
		'o365_yammer_cs' => $o365_yammer_cs,
		'shared_settings' => $shared_settings,
		'delete_settings' => $delete_settings,
		'b2b_shared_settings' =>  $b2b_shared_settings,
		'o365_display_user_id' => $o365_display_user_id,
		'o365_dynamic_crm_url' => $o365_dynamic_crm_url,
		'o365_graph_endpoints' => $o365_graph_endpoints,
		'o365_national_endpoints' => $o365_national_endpoints,
        'redirect_uri' => admin_url()."admin.php?page=o365_settings",
		'sharePoint_tenant_domain_name' => $tenant_name.".sharepoint.com",
		'application_tenant_domain_name'    => $tenant_name.".onmicrosoft.com",		
    ));
	if ( is_plugin_active( 'o365-user-auth/o365-user-auth.php' ) )
	{
		do_action( 'delete_access_token_on_base_setting_changed' );
		do_action( 'save_user_auth_settings' );
	}
	$tenant = o365_get_setting( 'application_tenant_domain_name' );
	$application_tenant_domain_name = $tenant;
	$appPrincipalId = $_POST['client_id'];
	$password = $_POST['client_secret'];
	$clientSecret = urlencode($password);
	$graphId = 'https://graph.windows.net';
	$protectedResourceHostName = 'graph.windows.net';
	$graphPrincipalId = urlencode($graphId);
	$clientPrincipalId = urlencode($appPrincipalId);
	$authenticationRequestBody = 'grant_type=client_credentials&client_secret='.$clientSecret.'&'.'resource='.$graphPrincipalId.'&'.'client_id='.$clientPrincipalId;
	$ch = curl_init();
	$stsUrl = 'https://login.windows.net/'.$application_tenant_domain_name.'/oauth2/token?api-version=1.0';
	curl_setopt($ch, CURLOPT_URL, $stsUrl);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,  $authenticationRequestBody);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	$output = curl_exec($ch);
	curl_close($ch);
	$tokenOutput = json_decode($output);
	
	$network_shared_settings = o365_get_setting('shared_settings');
	
	if( isset( $tokenOutput->access_token ) )
	{
		if ( is_multisite() && $network_shared_settings == 'yes' ) {
			update_site_option( 'o365_base_plugin_is_verify', '1' );
		}
		else
		{
			update_option( 'o365_base_plugin_is_verify', '1' );
		}
		echo $_SERVER['HTTP_REFERER'];
	}
	else
	{
		if ( is_multisite() && $network_shared_settings == 'yes' )
		{
			update_site_option( 'o365_base_plugin_is_verify', '0' );
		}
		else
		{
			update_option( 'o365_base_plugin_is_verify', '0' );
		}
		echo $_SERVER['HTTP_REFERER'];
	}


	die();
}