<?php

/*
 * Copyright (c) 2003-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see https://ckeditor.com/legal/ckeditor-oss-license
 */

/**
 * @file
 * Implements hooks for the CKEditor 5 Premium Features module.
 */

declare(strict_types=1);

use Drupal\Core\Asset\AttachedAssetsInterface;
use Drupal\ckeditor5\Plugin\CKEditor5PluginDefinition;
use Drupal\ckeditor5_premium_features\Utility\Html;
use Drupal\Core\Render\Markup;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\ckeditor5_premium_features\Utility\LibraryDefinitionItem;
use Drupal\ckeditor5_premium_features\EditorXssFilter\CollaborationXSSFilter;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\filter\FilterFormatInterface;

/**
 * Implements hook_help().
 */
function ckeditor5_premium_features_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.ckeditor5_premium_features':
      $text = file_get_contents(__DIR__ . '/README.md');
      if (!\Drupal::moduleHandler()->moduleExists('markdown')) {
        return '<pre>' . Html::escape($text) . '</pre>';
      }
      else {
        // Use the Markdown filter to render the README.
        $filter_manager = \Drupal::service('plugin.manager.filter');
        $settings = \Drupal::configFactory()->get('markdown.settings')->getRawData();
        $config = ['settings' => $settings];
        $filter = $filter_manager->createInstance('markdown', $config);
        return $filter->process($text, 'en');
      }
      // @todo Load text from Readme.md.
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The CKEditor Premium Features, see <a href=":doc_url">online documentation for the CKEditor Premium Features</a>.', [':doc_url' => 'https://ckeditor.com/docs/trial/latest/guides/overview.html']) . '</p>';
      return $output;
  }
}

/**
 * Implements hook_library_info_build().
 */
function ckeditor5_premium_features_library_info_build(): array {
  /** @var \Drupal\ckeditor5_premium_features\Config\SettingsConfigHandlerInterface $config_handler */
  $config_handler = \Drupal::service('ckeditor5_premium_features.config_handler.settings');

  $libraries = [
    'ckeditor5-collaboration-dll',
    'cloud-services',
  ];

  if (version_compare(\Drupal::VERSION, '10.1.0', '<')) {
    $libraries[] = 'autoformat';
  }

  $definitions = [];

  foreach ($libraries as $library) {
    $definition = new LibraryDefinitionItem($library, $config_handler->getDllLocation());
    $definition->addRemoteJs($definition->id());

    $definitions[$definition->id()] = $definition->getDefinition();
  }

  return $definitions;
}

/**
 * Implements hook_editor_xss_filter_alter().
 */
function ckeditor5_premium_features_editor_xss_filter_alter(
  &$editor_xss_filter_class,
  FilterFormatInterface $format,
  ?FilterFormatInterface $original_format = NULL) {
  $editor_xss_filter_class = CollaborationXSSFilter::class;
}

/**
 * Implements hook_library_info_alter().
 */
function ckeditor5_premium_features_library_info_alter(&$libraries, $extension) {
  // @todo Change this to use `after` instead of `dependencies` after https://www.drupal.org/project/drupal/issues/1945262 is released.
  $validForm = isset($libraries['node-form']) ? 'node-form' : (isset($libraries['form-two-columns']) ? 'form-two-columns' : NULL);
  if ($extension === 'claro' && $validForm) {
    $cke5PremiumFeaturesSettings = \Drupal::configFactory()->get('ckeditor5_premium_features.settings');
    if ($cke5PremiumFeaturesSettings->get('alter_node_form_css')) {
      $libraries[$validForm]['dependencies'][] = 'ckeditor5_premium_features/claro--override--node-form';
    }
  }

  if ($extension === 'core' && isset($libraries['ckeditor5'])) {
    $libraries['ckeditor5']['dependencies'][] = 'ckeditor5_premium_features/distribution-channel';
  }

  $isCoreWithoutAutoformat = version_compare(\Drupal::VERSION, '10.1.0', '<');
  if ($isCoreWithoutAutoformat && $extension === 'ckeditor5_premium_features' && isset($libraries['collaboration-integration-base'])) {
    $key = array_search('core/ckeditor5.autoformat', $libraries["collaboration-integration-base"]["dependencies"]);
    if ($key !== FALSE) {
      unset($libraries["collaboration-integration-base"]["dependencies"][$key]);
    }
    $libraries["collaboration-integration-base"]["dependencies"][] = 'ckeditor5_premium_features/autoformat';
  }

  if ($extension === 'ckeditor5_premium_features_wproofreader') {
    $libraryDiscovery = \Drupal::service('library.discovery');
    $ckeditorLibrary = $libraryDiscovery->getLibraryByName('core', 'ckeditor5');

    if (version_compare($ckeditorLibrary['version'], '41.0.0', '<')) {
      $libraries["wproofreader"]["js"] = [
        'js/build/wproofreader_3_27.js' => [
          'minified' => TRUE,
        ],
      ];
    }
  }
}

/**
 * Implements hook_module_implements_alter().
 */
function ckeditor5_premium_features_module_implements_alter(&$implementations, $hook) {
  if (in_array($hook, ['library_info_alter', 'ckeditor5_plugin_info_alter', 'form_alter'])) {
    // Make sure this module's implementations are executed in the end.
    if (isset($implementations["ckeditor5_premium_features"])) {
      unset($implementations["ckeditor5_premium_features"]);
      $implementations["ckeditor5_premium_features"] = FALSE;
    }
  }
}

/**
 * Implements hook_js_settings_alter().
 */
function ckeditor5_premium_features_js_settings_alter(array &$settings, AttachedAssetsInterface $assets) {
  $moduleHandler = \Drupal::service('module_handler');
  $settings["ckeditor5Premium"]["isMediaInstalled"] = $moduleHandler->moduleExists('media');
}

/**
 * Implements hook_filter_format_disable().
 */
function ckeditor5_premium_features_filter_format_disable(FilterFormatInterface $format) {
  // Revoke all collaboration permissions after text format is disabled.
  /** @var \Drupal\ckeditor5_premium_features\Utility\PermissionHelper $permissionHelper */
  $permissionHelper = \Drupal::service('ckeditor5_premium_features.permission_helper');
  $permissionHelper->revokeCollaborationPermissions([$format]);
}

/**
 * Implements hook_theme().
 */
function ckeditor5_premium_features_theme($existing, $type, $theme, $path): array {
  return [
    'ckeditor5_textarea' => [
      'render element' => 'element',
      'template' => 'ckeditor5-textarea'
    ],
  ];
}

/**
 * Implements hook_preprocess_HOOK().
 */
function ckeditor5_premium_features_preprocess_ckeditor5_textarea(&$variables): void {
  template_preprocess_textarea($variables);
  $element = $variables['element'];
  $variables['sidebar'] = !empty($element['#sidebar']) ? $element['#sidebar'] : NULL;
  $variables['document_outline'] = !empty($element['#document_outline']) ? $element['#document_outline'] : NULL;
}

function ckeditor5_premium_features_check_htmldiff_installed(): bool {
  return ckeditor5_premium_features_check_dependency_class('Caxy\HtmlDiff\HtmlDiff');
}

function ckeditor5_premium_features_check_jwt_installed(): bool {
  return ckeditor5_premium_features_check_dependency_class('Firebase\JWT\JWT');
}

function ckeditor5_premium_features_check_dependency_class(string $class): bool {
  if (class_exists($class, FALSE)) {
    return TRUE;
  }

  try {
    $exist = @class_exists($class, TRUE);
    return $exist;
  } catch (\Exception $e) {
    return FALSE;
  }
}

function ckeditor5_premium_features_display_missing_dependency_warning(TranslatableMarkup $message): void {
  $learn = t("To learn how to fix this, go to the <a href=\"@url\" target=\"_blank\">CKEditor 5 Premium Features configuration guide</a>", [
    '@url' => 'https://www.drupal.org/docs/extending-drupal/contributed-modules/contributed-module-documentation/ckeditor-5-premium-features/configuration-guide#s-optional-composer-dependencies'
  ]);
  \Drupal::messenger()->addWarning(Markup::create($message . ' ' . $learn));
}

function ckeditor5_premium_features_display_dependency_general_info_message(): void {
  $message = t('A few CKEditor 5 Premium Features modules require additional Composer packages to work properly. To learn more, go to the <a href="@url" target="_blank">CKEditor 5 Premium Features configuration guide</a>', [
    '@url' => 'https://www.drupal.org/docs/extending-drupal/contributed-modules/contributed-module-documentation/ckeditor-5-premium-features/configuration-guide#s-optional-composer-dependencies'
  ]);
  \Drupal::messenger()->addMessage(Markup::create($message));
}

/**
 * Implements hook_form_filter_format_edit_form_alter().
 */
function ckeditor5_premium_features_form_filter_format_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id): void {
  // Get the filter format entity from the form state.
  $filter_format = $form_state->getFormObject()->getEntity();

  // Check if CKEditor 5 is the selected editor.
  $editor = \Drupal::entityTypeManager()->getStorage('editor')->load($filter_format->id());
  if (!$editor || $editor->getEditor() !== 'ckeditor5') {
    return;
  }

  // Get the ComposerDependencyChecker service.
  $dependency_checker = \Drupal::service('ckeditor5_premium_features.composer_dependency_checker');

  // Get the module handler service to check if modules are enabled.
  $module_handler = \Drupal::moduleHandler();

  // Check for required dependencies based on enabled modules.
  $missing_dependencies = [];

  // Check for Real-time collaboration and document converters.
  if ($module_handler->moduleExists('ckeditor5_premium_features_export_word') ||
      $module_handler->moduleExists('ckeditor5_premium_features_export_pdf') ||
      $module_handler->moduleExists('ckeditor5_premium_features_import_word') ||
      $module_handler->moduleExists('ckeditor5_premium_features_realtime_collaboration')) {
    if (!$dependency_checker->isLibraryInstalled('firebase/php-jwt')) {
      $missing_dependencies[] = 'firebase/php-jwt';
    }
  }

  // Check for asynchronous collaboration and notifications.
  if ($module_handler->moduleExists('ckeditor5_premium_features_collaboration') ||
      $module_handler->moduleExists('ckeditor5_premium_features_notifications')) {
    if (!$dependency_checker->isLibraryInstalled('caxy/php-htmldiff')) {
      $missing_dependencies[] = 'caxy/php-htmldiff';
    }
  }

  // Check for OpenAI and AzureAI providers for the AI Assistant.
  if ($module_handler->moduleExists('ckeditor5_premium_features_ai_assistant')) {
    if (!$dependency_checker->isLibraryInstalled('openai-php/client')) {
      $missing_dependencies[] = 'openai-php/client';
    }

    if (!$dependency_checker->isLibraryInstalled('aws/aws-sdk-php')) {
      $missing_dependencies[] = 'aws/aws-sdk-php';
    }
  }

  // Display warnings for missing dependencies.
  if (!empty($missing_dependencies)) {

    $form['editor']['dependencies'] = [
      '#type' => 'container',
      '#weight' => -9,
      '#states' => [
        'visible' => [
          ':input[name="editor[editor]"]' => ['value' => 'ckeditor5'],
        ],
      ],
      'msg' => [
        '#markup' => '<div class="messages messages--warning">' .
          t('A few CKEditor 5 Premium Features require additional Composer packages to work properly. For more information, see the <a href="@url" target="_blank">CKEditor 5 Premium Features configuration guide</a>.', [
            '@url' => 'https://www.drupal.org/docs/extending-drupal/contributed-modules/contributed-module-documentation/ckeditor-5-premium-features/configuration-guide#s-optional-composer-dependencies',
          ]) .
          '</div>',
      ],
    ];

  }
}
