<?php

namespace Drupal\keycloak_user_provisioning;

use Drupal\Core\Config\ImmutableConfig;
use Drupal\user_provisioning\moUserProvisioningConstants;
use Drupal\user_provisioning\moUserProvisioningCustomer;
use Drupal\user_provisioning\moUserProvisioningSupport;
use Drupal\user_provisioning\moUserProvisioningUtilities;

/**
 * Helper class for sending support query to drupalsupport@xecurify.com.
 */
class MoKeycloakSupport {
  /**
   * Config property.
   *
   * @var ImmutableConfig
   */
  private ImmutableConfig $config;

  /**
   * Email of user.
   *
   * @var string
   */
  private string $email;

  /**
   * Query of user.
   *
   * @var string
   */
  private string $query;

  /**
   * Query description.
   *
   * @var string
   */
  private string $queryDescription;

  /**
   * Query type.
   *
   * @var string
   */
  private string $queryType;

  /**
   * Request stack service.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  private mixed $requestStack;

  public function __construct($email, $query, $queryDescription, $queryType) {
    $this->email = $email;
    $this->query = $query;
    $this->queryDescription = $queryDescription;
    $this->queryType = $queryType;
    $this->config = \Drupal::config('user_provisioning.settings');
    $this->requestStack = \Drupal::service('request_stack');
  }

  /**
   * Send support query.
   */
  public function sendSupportQuery(): bool {
    $base_url = $this->requestStack->getCurrentRequest()->getSchemeAndHttpHost();
    $modules_info = \Drupal::service('extension.list.module')->getExtensionInfo('keycloak_user_provisioning');

    $modules_version = $modules_info['version'];
    $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 = moUserProvisioningSupport::getTimestamp();
    $stringToHash = $customerKey . $currentTimeInMillis . $apikey;
    $hashValue = hash("sha512", $stringToHash);

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

    if ($this->queryType == 'Trial 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 . ' Keycloak User Provisioning Module | ' . $modules_version;
      $this->queryDescription = ($this->queryType == 'Contact Support' ? 'Query - ' : $request_for . ' requested for - ') . $this->queryDescription;
      $query = $this->queryType == 'Contact Support' ? '<strong>Support needed for:</strong> ' : 'Query: ';
      $content = '<div >Hello, <br><br>Company :<a href="' . $base_url . '" target="_blank" >' . $base_url . '</a><br><br>' . $query . $this->query . '<br><br>Email:<a href="mailto:' . $this->email . '" target="_blank">' . $this->email . '</a><br><br>Query:[DRUPAL ' . moUserProvisioningUtilities::mo_get_drupal_core_version() . ' Keycloak User Provisioning Free | PHP ' . phpversion() . ' | ' . $modules_version . ' ] ' . $this->queryDescription . '</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,
        ],
      ];
    }
    else {
      $url = moUserProvisioningConstants::MO_NOTIFY_SEND;

      $subject = 'Query request for Drupal-' . \DRUPAL::VERSION . ' Keycloak User Sync (Free) | ' . $modules_version;

      $query1 = 'Phone Number:';
      $content = '<div >Hello, <br><br>Company :<a href="' . $base_url . '" target="_blank" >' . $base_url . '</a><br><br>' . $query1 . $this->query . '<br><br>Email:<a href="mailto:' . $this->email . '" target="_blank">' . $this->email . '</a><br><br>Query:[DRUPAL ' . moUserProvisioningUtilities::mo_get_drupal_core_version() . ' Keycloak User Provisioning Free | PHP ' . phpversion() . ' | ' . $modules_version . ' ] ' . $this->queryDescription . '</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,
        ],
      ];
    }

    $field_string = json_encode($fields);
    $mo_user_provisioning_customer = new moUserProvisioningCustomer($this->email, NULL, NULL, NULL);
    $response = $mo_user_provisioning_customer->callService($url, $field_string, $header);

    if ($response != 'Query submitted.' && json_decode($response, TRUE) == NULL) {
      $error = [
        '%method' => 'sendSupportQuery',
        '%file' => 'MoKeycloakSupport.php',
        '%error' => $response,
      ];
      \Drupal::logger('keycloak_user_provisioning')->notice('Error at %method of %file: %error', $error);
      return FALSE;
    }
    elseif (json_decode($response, TRUE) !== NULL) {
      if (json_decode($response, TRUE)['status'] != 'SUCCESS') {
        $error = [
          '%method' => 'sendSupportQuery',
          '%file' => 'MoKeycloakSupport.php',
          '%error' => $response,
        ];
        \Drupal::logger('keycloak_user_provisioning')->notice('Error at %method of %file: %error', $error);
        return FALSE;
      }
    }
    return TRUE;
  }

}
