<?php

/**
 * @file
 * Contains miniOrange Customer class.
 */

namespace Drupal\oauth_server_sso;

use Drupal\oauth_server_sso\Utilities;

class MiniorangeOAuthServerCustomer {

    private $defaultCustomerId;
    private $defaultCustomerApiKey;
    public $httpClient;

    /**
     * Constructor.
    */
    public function __construct() {
        $this->defaultCustomerId = "16555";
        $this->defaultCustomerApiKey = "fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq";
        $this->httpClient = \Drupal::httpClient();
    }

    public function getHeader($addExtendedHeader = FALSE){
        $header = [
            'Content-Type'=>'application/json', 'charset'=>'UTF - 8',
            'Authorization'=> 'Basic',
        ];
        if($addExtendedHeader){
            /* Current time in milliseconds since midnight, January 1, 1970 UTC. */
            $current_time_in_millis = $this->getTimeStamp();
            /* Creating the Hash using SHA-512 algorithm */
            $string_to_hash = $this->defaultCustomerId .$current_time_in_millis . $this->defaultCustomerApiKey;
            $hashValue = hash("sha512", $string_to_hash);
            $timestamp_header = number_format($current_time_in_millis, 0, '', '' );
            $header=array_merge($header,array("Customer-Key"=>$this->defaultCustomerId,
                "Timestamp"=>$timestamp_header, "Authorization"=>$hashValue));
        }
        return $header;
    }

    public function getTimeStamp(){
        $url = MiniorangeOAuthServerConstants::BASE_URL.'/moas/rest/mobile/get-timestamp';
        $body = [];
        $currentTimeInMillis = Utilities::callAPI($url, 'POST', $body);

        if (empty($currentTimeInMillis)) {
            $currentTimeInMillis = round(microtime(true) * 1000);
            $currentTimeInMillis = number_format($currentTimeInMillis, 0, '', '');
        }
        return $currentTimeInMillis;
    }
}
