<?php


namespace Drupal\miniorange_saml\Api;
use Drupal\miniorange_saml\Utilities;
use Drupal\miniorange_saml\MiniorangeSamlConstant;

class MoAuthApi{

    private $apiKey;
    private $customerId;

    public function  __construct($customerId = MiniorangeSamlConstant::DEFAULT_CUSTOMER_ID, $apiKey = MiniorangeSamlConstant::DEFAULT_API_KEY ){

        $this->customerId = $customerId;
        $this->apiKey = $apiKey;
    }

    /**
     * This function is used to get the timestamp value
     */
    public function getTimeStamp() {
        $url = MiniorangeSamlConstant::SERVER_TIME_API;
        $fields = array();
        $currentTimeInMillis = $this->makeCurlCall($url,$fields);
        if (empty($currentTimeInMillis)) {
            $currentTimeInMillis = round(microtime(true) * 1000);
            $currentTimeInMillis = number_format($currentTimeInMillis, 0, '', '');
        }
        return $currentTimeInMillis;
    }

    function makeCurlCall( $url, $fields, $http_header_array =array( 'Content-Type: application/json', 'charset: UTF - 8', 'Authorization: Basic' ) ) {

        if ( gettype( $fields ) !== 'string' ) {
            $fields = json_encode( $fields );
        }

        $response = $this->postHttpCall($url, $fields,$http_header_array);

        return $response;

    }

    function getHttpHeaderArray() {

        /* Current time in milliseconds since midnight, January 1, 1970 UTC. */
        $currentTimeInMillis = $this->getTimeStamp();

        /* Creating the Hash using SHA-512 algorithm */
        $stringToHash = $this->customerId . $currentTimeInMillis . $this->apiKey;
        $hashValue = hash( "sha512", $stringToHash );

        $headers = array(
            "Content-Type: application/json",
            "Customer-Key: ".$this->customerId,
            "Timestamp: ".$currentTimeInMillis,
            "Authorization: ".$hashValue
        );

        return $headers;
    }

    public function postHttpCall($url, $fields, $http_header_array) {
        $headers = ['Content-Type' => 'application/json',];
        foreach ($http_header_array as $header) {
            $headers[] = $header;
        }
        try {
            $response = \Drupal::httpClient()->post($url, [
                'body' => $fields,
                'headers' => $headers,
                'allow_redirects' => true,
                'http_errors' => false,
                'decode_content' => true,
                'verify' => false,
            ]);
            return $response->getBody()->getContents();
        }
        catch (\Exception $exception) {
          \Drupal::messenger()->addError('Something went wrong. Please see recent logs for more details.');
            \Drupal::logger('miniorange_saml')->debug($exception->getMessage());
        }

    }
}
