<?php

namespace Drupal\user_provisioning;

use Drupal\Core\Config\ImmutableConfig;
use GuzzleHttp\Exception\RequestException;

/**
 *
 */
class moUserProvisioningCustomer {
  public $email;
  public $phone;
  public $password;
  public $otp_token;
  private $default_customer_Id;
  private $default_customer_api_key;
  private ImmutableConfig $config;

  /**
   *
   */
  public function __construct($email, $phone = NULL, $password = NULL, $otp_token = NULL) {
    $this->email = $email;
    $this->phone = $phone;
    $this->password = $password;
    $this->otp_token = $otp_token;
    $this->default_customer_Id = "16555";
    $this->default_customer_api_key = "fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq";
    $this->config = \Drupal::config('user_provisioning.settings');
  }

  /**
   * @return bool
   */
  public function isCurlInstalled() {
    return in_array('curl', get_loaded_extensions());
  }

  /**
   * @param $add_extended_header
   * @return false[]|string[]
   */
  public function getHeader($add_extended_header = FALSE) {

    $header = [
      'Content-Type' => 'application/json',
      'charset' => 'UTF - 8',
      'Authorization' => 'Basic',
    ];

    if ($add_extended_header) {
      /* Current time in milliseconds since midnight, January 1, 1970 UTC. */
      $current_time_in_millis = moUserProvisioningSupport::getTimestamp();

      /* Creating the Hash using SHA-512 algorithm */
      $string_to_hash = $this->default_customer_Id . $current_time_in_millis . $this->default_customer_api_key;
      $hashValue = hash("sha512", $string_to_hash);
      $timestamp_header = number_format($current_time_in_millis, 0, '', '');
      $header = array_merge($header, ["Customer-Key" => $this->default_customer_Id, "Timestamp" => $timestamp_header, "Authorization" => $hashValue]);
    }
    return $header;
  }

  /**
   * @param $url
   * @param $fields
   * @param bool $add_extended_header
   * @return false|string|void
   */
  public function callService($url, $fields, $add_extended_header = FALSE) {
    if (!$this->isCurlInstalled()) {
      return json_encode([
        "statusCode" => 'ERROR',
        "statusMessage" => 'cURL is not enabled on your site. Please enable the cURL module.',
      ]);
    }
    $fieldString = is_string($fields) ? $fields : json_encode($fields);

    $header = $this->getHeader($add_extended_header);

    try {
      $response = \Drupal::httpClient()
        ->post($url, [
          'body' => $fieldString,
          'allow_redirects' => TRUE,
          'http_errors' => FALSE,
          'decode_content' => TRUE,
          'verify' => FALSE,
          'headers' => $header,
        ]);
      return $response->getBody()->getContents();
    }
    catch (RequestException $exception) {
      $error = [
        '%apiName' => explode("moas", $url)[1],
        '%error' => $exception->getResponse()->getBody()->getContents(),
      ];
      \Drupal::logger('user_provisioning')->notice('Error at %apiName of  %error', $error);
    }
  }
}
