<?php

namespace Drupal\user_provisioning;

use Drupal\Core\Config\ImmutableConfig;
use Drupal\user_provisioning\Helpers\moUserProvisioningLogger;

/**
 * Handles user provisioning support and trial requests.
 */
class moUserProvisioningSupport {

  /**
   * User provisioning module configuration.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  private ImmutableConfig $config;
  /**
   * Requesting user email address.
   *
   * @var string|null
   */
  public ?string $email;
  /**
   * Requesting user phone number.
   *
   * @var string|null
   */
  public ?string $phone;
  /**
   * Support query text.
   *
   * @var string
   */
  public string $query;
  /**
   * Type of support query.
   *
   * @var string
   */
  public string $queryType;
  /**
   * Trial method selected by the user.
   *
   * @var string
   */
  public string $trialMethod;
  /**
   * Provisioning module display name.
   *
   * @var string
   */
  public string $moduleName;
  /**
   * Provisioning module version.
   *
   * @var string|null
   */
  public ?string $moduleVersion;
  /**
   * Logger service for support request traces.
   *
   * @var \Drupal\user_provisioning\Helpers\moUserProvisioningLogger
   */
  private moUserProvisioningLogger $moLogger;
  /**
   * Selected provider name.
   *
   * @var mixed|string
   */
  private mixed $provider;

  /**
   * Constructs a support request helper.
   *
   * @param string $email
   *   The requestor email address.
   * @param string $phone
   *   The requestor phone number.
   * @param string $query
   *   The support query text.
   * @param string $query_type
   *   The support query type.
   * @param string $trial_method
   *   The selected trial method.
   * @param mixed|string $provider
   *   The selected identity provider.
   * @param string $module_name
   *   The module display name.
   * @param string|null $module_version
   *   The module version.
   */
  public function __construct($email, $phone, $query, $query_type, $trial_method = '', $provider = '', $module_name = 'User Provisioning', $module_version = NULL) {
    $this->email = $email;
    $this->phone = $phone;
    $this->query = $query;
    $this->queryType = $query_type;
    $this->trialMethod = $trial_method;
    $this->moduleName = $module_name;
    $this->moduleVersion = $module_version;
    $this->config = \Drupal::config('user_provisioning.settings');
    $this->provider = $provider;
    $this->moLogger = new moUserProvisioningLogger();
  }

  /**
   * This function is written for sending the Support query.
   *
   * @return bool
   *   TRUE when the support request succeeds; otherwise FALSE.
   */
  public function sendSupportQuery(): bool {
    $modules_info = \Drupal::service('extension.list.module')->getExtensionInfo('user_provisioning');
    $modules_version = $this->moduleVersion == NULL ? $modules_info['version'] : $this->moduleVersion;
    $host = \Drupal::request()->getHost();

    if ($this->queryType == 'Trial Request' || $this->queryType == 'Call Request' || $this->queryType == 'Contact Support') {

      $url = moUserProvisioningConstants::MO_NOTIFY_SEND;

      $request_for = $this->queryType == 'Trial Request' ? 'Trial' : 'Support';

      $subject = $request_for . ' request for Drupal-' . \DRUPAL::VERSION . ' ' . $this->moduleName . ' Module | ' . $modules_version;
      $this->query = $request_for . ' requested for - ' . $this->query;

      $customerKey = $this->config->get('mo_user_provisioning_customer_id');
      $apikey = $this->config->get('mo_user_provisioning_customer_api_key');

      if ($customerKey == '') {
        $customerKey = "16555";
        $apikey = "fFd2XcvTGDemZvbw1bcUesNJWEqKbbUq";
      }

      $currentTimeInMillis = self::getTimestamp();
      $stringToHash = $customerKey . $currentTimeInMillis . $apikey;
      $hashValue = hash("sha512", $stringToHash);

      if ($this->queryType == 'Contact Support') {
        $content = '<div >Hello, <br><br>Company :<a href="' . $host . '" target="_blank" >' . $host . '</a><br><br><strong>Support needed for: </strong>' . $this->phone . '<br><br>Email:<a href="mailto:' . $this->email . '" target="_blank">' . $this->email . '</a><br><br>Query:[DRUPAL ' . moUserProvisioningUtilities::moGetDrupalCoreVersion() . ' | ' . $this->moduleName . ' Free | ' . $modules_version . ' | PHP ' . phpversion() . ' ] ' . $this->query . '</div>';
      }
      elseif ($this->queryType == 'Trial Request') {
        $content = '<div >Hello, <br><br>Company :<a href="' . $host . '" target="_blank" >' . $host . '</a><br><br>Trial Needed for: ' . $this->trialMethod . '<br><br>Provider Name: ' . $this->provider . '<br><br>Email: <a href="mailto:' . $this->email . '" target="_blank">' . $this->email . '</a><br><br>Query:[DRUPAL ' . moUserProvisioningUtilities::moGetDrupalCoreVersion() . ' | ' . $this->moduleName . ' Free | PHP ' . phpversion() . ' | ' . $modules_version . ' ] ' . $this->query . '</div>';
      }
      else {
        $content = '<div >Hello, <br><br>Company :<a href="' . $host . '" target="_blank" >' . $host . '</a><br><br>Phone Number: ' . $this->phone . '<br><br>Email:<a href="mailto:' . $this->email . '" target="_blank">' . $this->email . '</a><br><br>Query:[DRUPAL ' . moUserProvisioningUtilities::moGetDrupalCoreVersion() . ' | ' . $this->moduleName . ' Free | PHP ' . phpversion() . ' | ' . $modules_version . ' ] ' . $this->query . '</div>';
      }

      $fields = [
        'customerKey' => $customerKey,
        'sendEmail' => TRUE,
        'email' => [
          'customerKey' => $customerKey,
          'fromEmail' => $this->email,
          'fromName' => 'miniOrange',
          'toEmail' => moUserProvisioningConstants::SUPPORT_EMAIL,
          'toName' => moUserProvisioningConstants::SUPPORT_EMAIL,
          'subject' => $subject,
          'content' => $content,
        ],
      ];

      $header = [
        'Content-Type' => 'application/json',
        'Customer-Key' => $customerKey,
        'Timestamp' => $currentTimeInMillis,
        'Authorization' => $hashValue,
      ];

    }
    else {

      $this->query = '[Drupal ' . \DRUPAL::VERSION . $this->moduleName . ' Module | PHP ' . phpversion() . ' | ' . $modules_version . '] ' . $this->query;
      $fields = [
        'company' => $host,
        'email' => $this->email,
        'phone' => $this->phone,
        'ccEmail' => moUserProvisioningConstants::SUPPORT_EMAIL,
        'query' => $this->query,
      ];

      $url = moUserProvisioningConstants::CONTACT_US;

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

    $field_string = json_encode($fields);
    $mo_user_provisioning_customer = new moUserProvisioningCustomer('', NULL, NULL, NULL);
    $response = $mo_user_provisioning_customer->callService($url, $field_string, $header);
    $this->moLogger->addLog('Sending support query. URL: ' . $url, __LINE__, __FUNCTION__, __FILE__);
    $this->moLogger->addFormattedLog($fields, __LINE__, __FUNCTION__, __FILE__, 'Support query fields:');

    return $response;
  }

  /**
   * This function is written to get the timestamp.
   *
   * @return string
   *   The service timestamp in milliseconds.
   */
  public static function getTimestamp(): string {
    $url = moUserProvisioningConstants::GET_TIMESTAMP;
    $mo_user_provisioning_customer = new moUserProvisioningCustomer('', NULL, NULL, NULL);
    $content = $mo_user_provisioning_customer->callService($url, [], []);

    if (empty($content)) {
      $currentTimeInMillis = round(microtime(TRUE) * 1000);
      $currentTimeInMillis = number_format($currentTimeInMillis, 0, '', '');
    }
    return empty($content) ? $currentTimeInMillis : $content;
  }

}
