<?php

namespace Drupal\user_provisioning;

use Drupal\user_provisioning\Helpers\moUserProvisioningLogger;
use GuzzleHttp\Exception\RequestException;

/**
 *
 */
class moUserProvisioningCustomer {
  public string $email;
  public ?string $phone;
  public ?string $password;
  public ?string $otp_token;
  private string $default_customer_Id;
  private string $default_customer_api_key;
  private moUserProvisioningLogger $mo_logger;

  /**
   *
   */
  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->mo_logger = new moUserProvisioningLogger();
  }

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

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

    $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]);
    }
    $this->mo_logger->addLog('Returning final header: ' . print_r($header, TRUE), __LINE__, __FUNCTION__, __FILE__);
    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()) {
        $this->mo_logger->addLog('cURL is not installed. Returning error response.', __LINE__, __FUNCTION__, __FILE__);
      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,
        ]);
        $response_body = $response->getBody()->getContents();
        $this->mo_logger->addLog('Response body: ' . $response_body, __LINE__, __FUNCTION__, __FILE__);
      return $response_body;
    }
    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);
    }
  }
}
