<?php
// Prevent direct access
defined('ABSPATH') OR die('Sorry');

/*
 * Creating token URL for all the plugins
 * @params 
 * multisite_support = Yes|No 
 * state = plugin state
 * token_key = all token keys
 */
function o365_get_token_url( $state = null, $token_key = '', $multisite_support = 'no' ) {

    $o365_settings = get_site_option('o365_settings');
    if ( is_multisite() && isset($o365_settings['shared_settings']) && $o365_settings['shared_settings'] == "yes" && $multisite_support == 'yes' )
    {
        $o365_settings = get_site_option('o365_settings');
        $access_token = get_site_option( $token_key,'' );
    }
    else
    {
        $o365_settings = get_option('o365_settings');
        $access_token = get_option( $token_key,'' );
    }
    
    if(isset($o365_settings['client_id']))
    {
        $client_id = $o365_settings['client_id'];
    }

    if(isset($o365_settings['tenant_name']))
    {
        $tenant_name = $o365_settings['tenant_name'];
    }

    $redirect_uri = admin_url();
    $realm = m365_get_tenant_id_by_tenant_name( $tenant_name );
    if( empty( $access_token ) ) {
        $admin = 'https://login.microsoftonline.com/'.$realm.'/adminconsent?client_id='.$client_id.'&state='.$state.'&redirect_uri='.$redirect_uri;
        return $admin;
    }
}