<?php
require 'vendor/autoload.php';

use Aws\Sts\StsClient;
use Aws\Exception\AwsException;
use GuzzleHttp\Client;

// Create an STS client
$sts = new StsClient([
    'version' => 'latest',
    'region'  => 'us-east-1'
]);

try {
    // Assume a role using the SAML assertion
    $result = $sts->assumeRoleWithSAML([
        'RoleArn' => 'arn:aws:iam::YOUR_ACCOUNT_ID:role/YOUR_ROLE_NAME',
        'PrincipalArn' => 'arn:aws:iam::YOUR_ACCOUNT_ID:saml-provider/YOUR_PROVIDER_NAME',
        'SAMLAssertion' => 'YOUR_SAML_ASSERTION'
    ]);

    $credentials = $result['Credentials'];

    // Create a Guzzle HTTP client
    $client = new Client();

    // Prepare the request
    $method = 'GET';
    $host = 'qbusiness.us-east-1.api.aws';
    $region = 'us-east-1';
    $service = 'qbusiness';
    $endpoint = 'https://' . $host . '/applications/dc65dad4-2566-408d-bd6f-bebca9af8cb5/';

    // Get the current time for the request
    $currentTime = time();
    $amzDate = gmdate('Ymd\THis\Z', $currentTime);
    $dateStamp = gmdate('Ymd', $currentTime);

    // Prepare the canonical request
    $canonicalUri = '/applications/dc65dad4-2566-408d-bd6f-bebca9af8cb5/';
    $canonicalQueryString = '';
    $canonicalHeaders = "host:" . $host . "\n" . "x-amz-date:" . $amzDate . "\n";
    $signedHeaders = 'host;x-amz-date';
    $payloadHash = hash('sha256', '');
    $canonicalRequest = $method . "\n" . $canonicalUri . "\n" . $canonicalQueryString . "\n" . $canonicalHeaders . "\n" . $signedHeaders . "\n" . $payloadHash;

    // Prepare the string to sign
    $algorithm = 'AWS4-HMAC-SHA256';
    $credentialScope = $dateStamp . '/' . $region . '/' . $service . '/aws4_request';
    $stringToSign = $algorithm . "\n" . $amzDate . "\n" . $credentialScope . "\n" . hash('sha256', $canonicalRequest);

    // Calculate the signature
    $signingKey = getSignatureKey($credentials['SecretAccessKey'], $dateStamp, $region, $service);
    $signature = hash_hmac('sha256', $stringToSign, $signingKey);

    // Prepare the Authorization header
    $authorizationHeader = $algorithm . ' ' . 'Credential=' . $credentials['AccessKeyId'] . '/' . $credentialScope . ', ' . 'SignedHeaders=' . $signedHeaders . ', ' . 'Signature=' . $signature;

    // Make the request
    $response = $client->request($method, $endpoint, [
        'headers' => [
            'Authorization' => $authorizationHeader,
            'x-amz-date' => $amzDate,
            'x-amz-security-token' => $credentials['SessionToken']
        ]
    ]);

    echo $response->getBody();
} catch (AwsException $e) {
    echo $e->getMessage();
}

function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
    $kDate = hash_hmac('sha256', $dateStamp, 'AWS4' . $key, true);
    $kRegion = hash_hmac('sha256', $regionName, $kDate, true);
    $kService = hash_hmac('sha256', $serviceName, $kRegion, true);
    $kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
    return $kSigning;
}