<?php

/**
 * @file
 * Contains miniOrange Support class.
 */

namespace Drupal\miniorange_2fa;

use Drupal\miniorange_2fa\Helper\MoUtility;
use Drupal\miniorange_2fa\MoAuthConstants;
use Drupal\miniorange_2fa\MoAuthUtilities;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Extension\ModuleExtensionList;
/**
 * This class represents support information for
 * customer.
 */
class Miniorange2FASupport implements ContainerInjectionInterface
{
    public $email;
    public $phone;
    public $query;

    /**
     * The HTTP client.
     *
     * @var \GuzzleHttp\ClientInterface
     */
    protected $httpClient;

/**
     * The logger factory.
     *
     * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
     */
    protected $loggerFactory;

    /**
     * The module extension list service.
     *
     * @var \Drupal\Core\Extension\ModuleExtensionList
     */
    protected $moduleExtensionList;


    /**
     * Constructor.
     */
   public function __construct($email, $phone, $query, ClientInterface $http_client = NULL, LoggerChannelFactoryInterface $logger_factory = NULL, ModuleExtensionList $module_extension_list = NULL)
    {
        $this->email = $email;
        $this->phone = $phone;
        $this->query = $query;
        $this->httpClient = $http_client ?: \Drupal::httpClient();
        $this->loggerFactory = $logger_factory ?: \Drupal::service('logger.factory');
        $this->moduleExtensionList = $module_extension_list ?: \Drupal::service('extension.list.module');
    }

    public static function create(ContainerInterface $container) {
        return new static(
            '',
            '',
            '',
            $container->get('http_client'),
            $container->get('logger.factory'),
            $container->get('extension.list.module')
        );
    }

    /**
     * Send support query or license expiry notification.
     */
    public function sendSupportQuery($subject = NULL, $content = NULL) {
        if ($this->query == 'license_expiry') {
            return $this->sendLicenseExpiryNotification($subject, $content);
        }

        $this->formatQueryWithMetadata(TRUE);
        return $this->sendHttpRequest(
            MoAuthConstants::getBaseUrl() . MoAuthConstants::SUPPORT_QUERY,
            $this->buildSupportFields(),
            $this->getBasicHeaders()
        );
    }

    /**
     * Send trial request.
     */
    public function sendTrialRequest() {
        $this->formatQueryWithMetadata(FALSE);
        return $this->sendHttpRequest(
            MoAuthConstants::getBaseUrl() . MoAuthConstants::SUPPORT_QUERY,
            $this->buildSupportFields(),
            $this->getBasicHeaders()
        );
    }

    /**
     * Send license expiry notification to customer and support team.
     */
    private function sendLicenseExpiryNotification($subject, $content) {
        $config = \Drupal::config('miniorange_2fa.settings');
        $customer_key = $config->get('mo_auth_customer_id') ?? '';
        $api_key = $config->get('mo_auth_customer_api_key') ?? '';
        
        $url = MoAuthConstants::getBaseUrl() . MoAuthConstants::NOTIFY_API;
        $timestamp = MoAuthUtilities::get_timestamp();
        $headers = [
            'Content-Type' => 'application/json',
            'Customer-Key' => $customer_key,
            'Timestamp' => $timestamp,
            'Authorization' => hash('sha512', $customer_key . $timestamp . $api_key),
        ];
        
        $email_subject = $subject ?: 'License Expiry For Drupal miniOrange 2FA Module';
        $email_content = $content ?: 'Hello you license is expired.';
        
        $customer_admin_email = $config->get('mo_auth_customer_admin_email');
        $recipients = array_filter(['drupalsupport@xecurify.com', $customer_admin_email]);
        
        $success = TRUE;
        foreach ($recipients as $recipient) {
            $fields = [
                'customerKey' => $customer_key,
                'sendEmail' => TRUE,
                'email' => [
                    'customerKey' => $customer_key,
                    'fromEmail' => $this->email,
                    'fromName' => 'miniOrange',
                    'toEmail' => $recipient,
                    'toName' => $recipient,
                    'subject' => $email_subject,
                    'content' => $email_content,
                ],
            ];
            
            if (!$this->sendHttpRequest($url, $fields, $headers, "License expiry notification failed for {$recipient}")) {
                $success = FALSE;
            }
        }
        
        return $success;
    }

    /**
     * Format query with module version and metadata.
     */
    private function formatQueryWithMetadata($includeBackdoorAndCron = TRUE) {
        $version = $this->getModuleVersion() . ' | PHP ' . phpversion();
        $drupal_version = MoAuthUtilities::mo_get_drupal_core_version();
        
        $this->query = "[Drupal {$drupal_version} 2FA Module | {$version}] {$this->query}";
        
        if ($includeBackdoorAndCron) {
            $backdoor_status = \Drupal::config('miniorange_2fa.settings')->get('mo_auth_enable_backdoor') ? 'Enabled' : 'Disabled';
            $cron_status = MoAuthUtilities::getCronInformation();
            $this->query .= "<br><br>Backdoor Login: <b>{$backdoor_status}</b><br><br>Cron Status: <b>{$cron_status}</b>";
        }
    }

    /**
     * Build support query fields.
     */
    private function buildSupportFields() {
        return [
            'company' => $_SERVER['SERVER_NAME'],
            'email' => $this->email,
            'phone' => $this->phone,
            'ccEmail' => 'drupalsupport@xecurify.com',
            'query' => $this->query,
        ];
    }

    /**
     * Get basic HTTP headers for support queries.
     */
    private function getBasicHeaders() {
        return [
            'Content-Type' => 'application/json',
            'charset' => 'UTF-8',
            'Authorization' => 'Basic',
        ];
    }

    /**
     * Get module version.
     */
    private function getModuleVersion() {
        $modules_info = $this->moduleExtensionList->getExtensionInfo('miniorange_2fa');
        return $modules_info['version'];
    }

    /**
     * Send HTTP POST request with error handling.
     */
    private function sendHttpRequest($url, $fields, $headers, $error_context = NULL) {
        try {
            $this->httpClient->post($url, [
                'json' => $fields,
                'headers' => $headers,
                'verify' => FALSE,
                'allow_redirects' => TRUE,
                'timeout' => 30,
            ]);
            return TRUE;
        }
        catch (RequestException $e) {
            $error_message = $error_context ?: "HTTP Error: " . $e->getMessage();
            $this->loggerFactory->get('miniorange_2fa')->error($error_message);
            
            if ($e->hasResponse()) {
                $response_body = $e->getResponse()->getBody()->getContents();
                $this->loggerFactory->get('miniorange_2fa')->error("Response body: @body", ['@body' => $response_body]);
            }
            
            return FALSE;
        }
    }
}
