<?php

namespace Drupal\user_provisioning\Api;

use Drupal\Core\Http\ClientFactory;
use Drupal\user_provisioning\moUserProvisioningConstants;

class MoAuthApi {
    private $apiKey;
    private $customerId;
    private $httpClient;

    public function __construct($customerId = moUserProvisioningConstants::DEFAULT_CUSTOMER_ID, $apiKey = moUserProvisioningConstants::DEFAULT_API_KEY) {
        $this->customerId = $customerId;
        $this->apiKey = $apiKey;
        $this->httpClient = \Drupal::httpClient();
    }

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

    public function makeHttpClientCall($url, $fields, $http_header_array = ['Content-Type' => 'application/json', 'charset' => 'UTF-8', 'Authorization' => 'Basic']) {
        $response = $this->httpClient->post($url, [
            'headers' => $http_header_array,
            'body' => json_encode($fields),
            'verify' => FALSE,
        ]);
        return $response->getBody()->getContents();
    }
}
