<?php

namespace Drupal\miniorange_2fa\EventSubscriber;

use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\miniorange_2fa\Services\LicenseManager;
use Drupal\miniorange_2fa\Services\LicenseExpiryScheduler;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * License Subscriber for handling license expiry checks.
 */
class LicenseSubscriber implements EventSubscriberInterface {

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

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The license manager service.
   *
   * @var \Drupal\miniorange_2fa\Services\LicenseManager
   */
  protected $licenseManager;

  /**
   * The license expiry scheduler service.
   *
   * @var \Drupal\miniorange_2fa\Services\LicenseExpiryScheduler
   */
  protected $licenseExpiryScheduler;

  /**
   * Constructor.
   */
  public function __construct(
    LoggerChannelFactoryInterface $logger_factory,
    ConfigFactoryInterface $config_factory,
    LicenseManager $license_manager,
    LicenseExpiryScheduler $license_expiry_scheduler
  ) {
    $this->loggerFactory = $logger_factory;
    $this->configFactory = $config_factory;
    $this->licenseManager = $license_manager;
    $this->licenseExpiryScheduler = $license_expiry_scheduler;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      KernelEvents::TERMINATE => ['onTerminate', 10],
    ];
  }

  /**
   * Handle kernel terminate event.
   *
   * @param \Symfony\Component\HttpKernel\Event\TerminateEvent $event
   *   The terminate event.
   */
  public function onTerminate(TerminateEvent $event) {
    if (!$event->isMainRequest()) {
      return;
    }

    if (!$this->isModuleConfigured()) {
      return;
    }

    try {
      if ($this->licenseManager->shouldFetchLicense()) {
        $this->processLicenseFetch();
      }
    }
    catch (\Exception $e) {
      $this->loggerFactory->get('miniorange_2fa')->error('Error in license subscriber: @message', [
        '@message' => $e->getMessage()
      ]);
    }
  }

  /**
   * Check if the module is properly configured.
   *
   * @return bool
   *   TRUE if module is configured.
   */
  protected function isModuleConfigured(): bool {
    $config = $this->configFactory->get('miniorange_2fa.settings');
    $customer_id = $config->get('mo_auth_customer_id');
    $api_key = $config->get('mo_auth_customer_api_key');
    $status = $config->get('mo_auth_status');
    
    return !empty($customer_id) && !empty($api_key) && $status === 'PLUGIN_CONFIGURATION';
  }

  /**
   * Process license fetch from API.
   */
  protected function processLicenseFetch(): void {
    $this->loggerFactory->get('miniorange_2fa')->info('Fetching license information (24-hour interval reached).');
    
    $license_response = $this->licenseManager->fetchLicense();
    
    if ($license_response) {
      $this->loggerFactory->get('miniorange_2fa')->info('License information fetched successfully.');
      
      $this->checkLicenseStatusAndNotify();
    }
    else {
      $this->loggerFactory->get('miniorange_2fa')->warning('Failed to fetch license information.');
    }
  }



  /**
   * Check license status and send notifications if needed.
   */
  protected function checkLicenseStatusAndNotify(): void {
    $remaining_days = $this->licenseManager->getRemainingDays();
    if ($remaining_days == 0) {
      $this->loggerFactory->get('miniorange_2fa')->warning('License has expired.');
    }
    elseif ($remaining_days <= 30) {
      $this->loggerFactory->get('miniorange_2fa')->info('License expires in @days days.', [
        '@days' => $remaining_days
      ]);
    }
    
    $this->licenseExpiryScheduler->processExpiryNotifications($remaining_days);
  }

} 