<?php
require_once 'includes/config.php';
require_once 'includes/dbcontroller.php';
require_once 'includes/azurecontroller.php';

$db_handle = new DBController();
$obj_azure = new AzureController();

// Check if the authorization code is available
if(isset($_GET['token_url'])){
    $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id='.$obj_azure->client_id.'&response_type=code&redirect_uri='.$obj_azure->redirect_url.'&response_mode=query&scope=Files.ReadWrite offline_access';
	echo '<a href="'.$url.'">'.$url.'</a>';
	die();
}
if(!empty($_GET['code'])){
	// Authorization code received, exchange it for an access token
    $auth_code = $_GET['code'];

    // Prepare paylod for token request
    $payload = [
        'client_id' => $obj_azure->client_id,
        'client_secret' => $obj_azure->client_secret,
        'redirect_uri' => $obj_azure->redirect_url,
        'code' => $auth_code,
        'grant_type' => 'authorization_code'
    ];
    $response = $obj_azure->sendRequest($obj_azure->token_url, $payload);
    
    echo '<pre>';
    print_r($response);
    echo '</pre>';
    
    if(!empty($response['access_token'])){
    	// Save the access token & refresh token in the database for later use
    	$obj_azure->updateMeta('auth_code', $auth_code);
    	$obj_azure->updateMeta('access_token', $response['access_token']);
    	$obj_azure->updateMeta('refresh_token', $response['refresh_token']);
    	
    	$obj_azure->refresh_token = $response['refresh_token'];
    	$obj_azure->access_token = $response['access_token'];
    	
    	die("Handshake Successful! Please close this window!");
    }
	else{
		// Failed to get the access token
		die("Handshake Failed! No response from Azure Token URL.");
	}
}
else{
	die("Handshake Failed! No code found in URL");
}
?>