<?php

/**
 * @file
 * Main module file.
 */

use Drupal\Core\Link;
use Drupal\support_dar\LicenseManager;

/**
 * Implements hook_cron().
 */
function support_dar_cron() {
  /** @var \Drupal\support_dar\LicenseManager $license_manager */
  $license_manager = \Drupal::service('support_dar.license_manager');
  $license_manager->checkLicense();
}

/**
 * Implements hook_requirements_alter().
 */
function support_dar_requirements_alter(array &$requirements) {
  /** @var \Drupal\support_dar\LicenseManager $license_manager */
  $license_manager = \Drupal::service('support_dar.license_manager');
  $status = $license_manager->getStatus();
  /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
  $date_formatter = \Drupal::service('date.formatter');
  $expiration_date = $license_manager->getExpirationDate();
  $support_mail = 'support@dar.ru';
  switch ($status) {
    case LicenseManager::IS_NOT_ACTIVE:
      $severity = REQUIREMENT_ERROR;
      $description = t('License not activated, contact us @support_mail', ['@support_mail' => $support_mail]);
      break;

    case LicenseManager::IS_ACTIVE:
      // Everything is good, do nothing.
      $description = t('Your license is active until @date', ['@date' => $date_formatter->format($expiration_date, 'html_date')]);
      $severity = REQUIREMENT_OK;
      break;

    case LicenseManager::IS_SOON_EXPIRED:
      $description = t('Your license is about to expire @data, please contact us to renew it @support_mail', [
        '@date' => $date_formatter->format($expiration_date, 'html_date'),
        '@support_mail' => $support_mail,
      ]);
      $severity = REQUIREMENT_WARNING;
      break;

    case LicenseManager::IS_NOT_CONFIGURED:
      $description = t('The license cannot be verified, the settings are not filled in. You can configure it @here',
        [
          '@here' => Link::createFromRoute(t('here'), 'support_dar.settings')
            ->toString(),
        ],
      );
      $severity = REQUIREMENT_WARNING;
      break;
  }
  $requirements['support_dar'] = [
    'title' => t('Support DAR'),
    'description' => $description,
    'severity' => $severity,
  ];
}
