<?php

namespace Drupal\azure_ad;

use Drupal;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\user_provisioning\moUserProvisioningConstants;
use Drupal\user_provisioning\moUserProvisioningSupport;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;

class MoAzureUtilities
{

    private Client $http_client;
    private ImmutableConfig $config;
    private LoggerInterface $logger;

    public function __construct()
    {
        $this->config = \Drupal::config('azure_ad.settings');
        $this->http_client = \Drupal::httpClient();
        $this->logger = Drupal::logger('azure_ad');
    }

    public static function drupalIsCli()
    {
        $server = \Drupal::request()->server;
        $server_software = $server->get('SERVER_SOFTWARE');
        $server_argc = $server->get('argc');

        if(!isset($server_software) && (php_sapi_name() == 'cli' || (is_numeric($server_argc) && $server_argc > 0)))
            return TRUE;
        else
            return FALSE;
    }

    /**
     * @throws Exception
     */
    public function skipFeedback($modules_version, $url){

        $email = \Drupal::config('system.site')->get('mail');

        [$customerKey] = $this->CustomerApiKey();
        $fromEmail 			= 'no-reply@xecurify.com';
        $subject            = 'Regarding Drupal ' . \DRUPAL::VERSION . ' Azure AD Sync Module - '.$modules_version.' Feedback';

        $content =
            '<div>Hello there,
            <br><br>Thank you for showing interest in the miniOrange Azure AD Sync module.
            <br><br>It seems like you were looking for Sync solution between your Drupal site and Azure AD. I hope that you found our module useful and easy to configure.
            <br><br>Can you please let me know whether you are able to successfully configure our module with Azure AD? In case you are facing any issues in our module or if you have any questions or concerns, please feel free to reach out to <a href="mailto:'.moUserProvisioningConstants::SUPPORT_EMAIL.'" target="_blank">'. moUserProvisioningConstants::SUPPORT_EMAIL .'</a>. We will be happy to assist you. If you want we can also set up an online meeting sometime convenient for you for the same.
            <br><br>In case having an online meeting is not convenient for you, we can communicate through email as well. Also, can you please provide us with some more information on your use case so that we can provide you with a solution that will satisfy all of your use case requirements?
            <br><br><b>If you want, we can also provide you with the 7 days free full-featured trial.</b>
            <br><br>Waiting for your reply.
            <br><br>Thanks and Regards,
            <br>miniOrange Drupal team';

        $fields = array(
            'customerKey'	=> $customerKey,
            'sendEmail' 	=> true,
            'email' 		=> array(
                'customerKey'   => $customerKey,
                'fromEmail'     => $fromEmail,
                'fromName' 		=> 'miniOrange',
                'toEmail' 		=> $email,
                'toName' 		=> $email,
                'subject' 		=> $subject,
                'content' 		=> $content
            ),
        );

        $this->AzureHttpCall($fields, $url);
    }

    public function CustomerApiKey(){
        $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);

        return [$customerKey, $currentTimeInMillis, $hashValue];
    }

    public function AzureHttpCall($fields, $url){
        [$customerKey, $currentTimeInMillis, $hashValue] = $this->CustomerApiKey();
        $field_string = json_encode($fields);
        $header = [
            'Content-Type' => 'application/json',
            'Customer-Key' => $customerKey,
            'Timestamp' => $currentTimeInMillis,
            'Authorization' => $hashValue
        ];

        $options = [
            'body' => $field_string,
            'allow_redirects' => TRUE,
            'http_errors' => FALSE,
            'decode_content' => TRUE,
            'verify' => FALSE,
            'headers' => $header
        ];

        try {
            $this->http_client->request('POST', $url, $options)->getBody()->getContents();
        } catch (GuzzleException $e) {
            $this->logger->error($e->getMessage());
            throw new Exception($e->getMessage(), $e->getCode(), $e);
        }
    }

    public function getModuleVersion(){
        $modules_info = \Drupal::service('extension.list.module')->getExtensionInfo('azure_ad');
        $module_version = $modules_info['version'];
        return $module_version;
    }

}
