<?php
// Setting up Content Type header
header('Content-Type: application/json');

// Triming URL
$urlParts = explode('/', $_SERVER['REQUEST_URI']);
array_shift($urlParts);
array_shift($urlParts);

if (!function_exists('getallheaders')) {
    function getallheaders() {
        $headers = [];
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

// Getting all Request headers and Request body
$headers = getallheaders();
$request_body = json_decode(file_get_contents('php://input'));

// Imploding URL
$endpoint = implode("/", $urlParts);
$base = 'https://graph.microsoft.com/'.$endpoint;

// Access Token
$sharepoint_tokens_data = get_option( 'o365_wp_ms_search_access_token_search_item','' );

// POST request
if( ! empty( $request_body ) && (is_array( $request_body ) || is_object( $request_body )) && count( $request_body ) > 0 ) {
    if(isset($base) && $base !="")
    {
        $response = wp_remote_post(
            $base, 
            array(
                'body' => json_encode($request_body),
                "headers" => array(
                    'Authorization' => 'Bearer '.$sharepoint_tokens_data,
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                )
            )
        );
        $responseBody = wp_remote_retrieve_body( $response );
        $curl = json_decode( $responseBody );
        if ( (is_object( $curl ) || is_array( $curl )) && ! is_wp_error( $curl ) ) {
            echo json_encode($curl);
            die();
        } else {
            print_r($curl->error->message);
            return false;
            die();
        }
    }
} else if( ! empty( $endpoint ) ) {
    if(isset($base) && $base !="")
    {
        $response = wp_remote_get(
            $base, 
            array(
                "headers" => array(
                    'Authorization' => 'Bearer '.$sharepoint_tokens_data,
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                )
            )
        );
        $responseBody = wp_remote_retrieve_body( $response );
        $curl = json_decode( $responseBody );

        if ( (is_object( $curl ) || is_array( $curl )) && ! is_wp_error( $curl ) ) {
            echo json_encode($curl);
            die();
        } else {
            print_r($curl->error->message);
            return false;
            die();
        }
    }
}