<?php

/**
 * @file
 * Install, update and uninstall functions for the social_group_invite module.
 */

use Drupal\Core\Config\FileStorage;
use Drupal\group\Entity\GroupType;
use Drupal\language\ConfigurableLanguageManagerInterface;

/**
 * Implements hook_install().
 *
 * @throws \Drupal\Core\Entity\EntityStorageException
 */
function social_group_invite_install() {
  // Assign permissions by default to all group types
  // that have group_invitation enabled.
  foreach (GroupType::loadMultiple() as $group_type) {
    if ($group_type->hasContentPlugin('group_invitation')) {
      social_group_invite_set_default_permissions_for_group_type($group_type);
    }
  }
}

/**
 * Set helper text of invite mail on the preview page for Groups.
 */
function social_group_invite_update_8001() {
  $config = \Drupal::configFactory()->getEditable('social_group_invite.settings');
  $config->set('invite_helper', "<p>The message above is edited by the community managers. Please contact them for questions and ideas</p>");
  $config->save();
}

/**
 * Update invite message in the message template.
 */
function social_group_invite_update_8002() {
  $config = \Drupal::configFactory()->getEditable('message.template.invited_to_join_group');

  $new_text = [
    0 => [
      'format' => 'full_html',
      'value' => '<p>You have been invited to join the group <a href="[message:gurl]">[message:gtitle]</a></p>' . "\r\n",
    ],
    1 => [
      'format' => 'full_html',
      'value' => '<p>You have been invited to join the group <a href="[message:gurl]">[message:gtitle]</a></p>' . "\r\n",
    ],
    2 => [
      'format' => 'full_html',
      'value' => '<p>Hi,</p>' . "\r\n\r\n" . '<p>I would like to invite you to my group [message:gtitle] on [site:name].</p>' . "\r\n\r\n" . '<p>Kind regards,<br />' . "\r\n" . '[message:author:display-name]</p>' . "\r\n\r\n" . '<table class="btn-wrap">' . "\r\n\t" . '<tbody>' . "\r\n\t\t" . '<tr>' . "\r\n\t\t\t" . '<td class="align-center"><a class="btn-link btn-link-bg btn-link-one" href="[message:gurl]">View group</a></td>' . "\r\n\t\t\t" . '<td class="align-center"><a class="btn-link btn-link-bg btn-link-one" href="[site:url]">About [site:name]</a></td>' . "\r\n\t\t" . '</tr>' . "\r\n\t" . '</tbody>' . "\r\n" . '</table>' . "\r\n",
    ],
  ];

  $config->set('text', $new_text);
  $config->save();
}

/**
 * Update invite message in group types.
 */
function social_group_invite_update_8005() {
  $configs = [
    'group.content_type.closed_group-group_invitation',
    'group.content_type.flexible_group-group_invitation',
    'group.content_type.open_group-group_invitation',
    'group.content_type.public_group-group_invitation',
    'group.content_type.secret_group-group_invitation',
  ];

  foreach ($configs as $config) {
    $group_config = \Drupal::configFactory()->getEditable($config);

    $invitation_body = 'Hi,<br/><br/> I would like to invite you to join my group [group:title] on [site:name].<br/><br/>Kind regards,<br/>[current-user:display-name]<br/><br/><table class="btn-wrapp">' . "\r\n\t" . '<tbody>' . "\r\n\t\t" . '<tr>' . "\r\n\t\t\t" . '<td class="align-center"><a class="btn-link btn-link-bg btn-link-one" href="[group_content:register_link]">View group</a></td>' . "\r\n\t\t\t" . '<td class="align-center"><a class="btn-link btn-link-bg btn-link-one" href="[site:url]">About [site:name]</a></td>' . "\r\n\t\t" . '</tr>' . "\r\n\t" . '</tbody>' . "\r\n" . '</table>';
    $existing_user_invitation_body = 'Hi,<br/><br/>I would like to invite you to join my group [group:title] on [site:name].<br/><br/>Kind regards,<br/>[current-user:display-name]<br/><br/><table class="btn-wrapp">' . "\r\n\t" . '<tbody>' . "\r\n\t\t" . '<tr>' . "\r\n\t\t\t" . '<td class="align-center"><a class="btn-link btn-link-bg btn-link-one" href="[group_content:my_invitations_link]">View group</a></td>' . "\r\n\t\t\t" . '<td class="align-center"><a class="btn-link btn-link-bg btn-link-one" href="[site:url]">About [site:name]</a></td>' . "\r\n\t\t" . '</tr>' . "\r\n\t" . '</tbody>' . "\r\n" . '</table>';

    $group_config->set('plugin_config.invitation_body', $invitation_body);
    $group_config->set('plugin_config.existing_user_invitation_body', $existing_user_invitation_body);
    $group_config->save();
  }
}

/**
 * Update group invite views().
 */
function social_group_invite_update_8006() {
  $config_path = \Drupal::service('extension.list.module')->getPath('social_group_invite') . '/config/optional';
  $source = new FileStorage($config_path);
  /** @var \Drupal\Core\Config\StorageCacheInterface $config_storage */
  $config_storage = \Drupal::service('config.storage');
  $configs = [
    'views.view.social_group_invitations',
    'views.view.social_group_user_invitations',
  ];

  // Update config.
  foreach ($configs as $config) {
    $config_storage->write($config, $source->read($config));
  }
}

/**
 * Update a text of invited_to_join_group message template.
 */
function social_group_invite_update_8007() {
  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper->executeUpdate('social_group_invite', 'social_group_invite_update_8007');

  // Output logged messages to related channel of update execution.
  return $updateHelper->logger()->output();
}

/**
 * Add a new field to the flexible group.
 */
function social_group_invite_update_11001(): void {
  // Do nothing if the Social Flexible Group module is disabled.
  if (!\Drupal::moduleHandler()->moduleExists('social_group_flexible_group')) {
    return;
  }

  $config_path = \Drupal::service('extension.list.module')->getPath('social_group_invite') . '/config/static';
  $source = new FileStorage($config_path);
  $entity_type_manager = \Drupal::entityTypeManager();

  /** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $field_storage_config_storage */
  $field_storage_config_storage = $entity_type_manager->getStorage('field_storage_config');

  // Create field storages.
  $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
  $data = $source->read('field.storage.group.field_group_invite_by_member_11001');
  if (is_array($data)) {
    $class = $field_type_manager->getPluginClass($data['type']);
    if (is_null($field_storage_config_storage->load($data['id']))) {
      $data['settings'] = $class::storageSettingsFromConfigData($data['settings']);
      $field_storage_config_storage->create($data)->save();
    }
  }

  /** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $field_config_storage */
  $field_config_storage = $entity_type_manager->getStorage('field_config');
  // Create field settings.
  $data = $source->read('field.field.group.flexible_group.field_group_invite_by_member_11001');
  if (is_array($data) && is_null($field_config_storage->load($data['id']))) {
    $field_config_storage->create($data)->save();
  }
}

/**
 * Add views bulk operations to "manage invites" page.
 */
function social_group_invite_update_11002(): string {
  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper->executeUpdate('social_group_invite', __FUNCTION__);

  // Reorder displayed fields.
  $config_factory = \Drupal::configFactory();
  $config = $config_factory->getEditable('views.view.social_group_invitations');
  $fields = $config->get('display.default.display_options.fields');
  $fields = ['social_views_bulk_operations_bulk_form_invites' => $fields['social_views_bulk_operations_bulk_form_invites']] + $fields;
  $config->set('display.default.display_options.fields', $fields);
  $config->save();

  // Output logged messages to related channel of update execution.
  return $updateHelper->logger()->output();
}

/**
 * Update exposed filter button name.
 */
function social_group_invite_update_11401(): string {
  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper->executeUpdate('social_group_invite', __FUNCTION__);

  // Output logged messages to related channel of update execution.
  return $updateHelper->logger()->output();
}

/**
 * Update email invitation messages.
 */
function social_group_invite_update_11501(): void {
  $config_factory = \Drupal::configFactory();

  $group_config = \Drupal::config('social_group.settings');
  $invite_settings = $group_config->get('group_invite');

  $configurations = [
    'group.content_type.closed_group-group_invitation',
    'group.content_type.flexible_group-group_invitation',
    'group.content_type.open_group-group_invitation',
    'group.content_type.public_group-group_invitation',
    'group.content_type.secret_group-group_invitation',
  ];

  foreach ($configurations as $name) {
    $configuration = $config_factory->getEditable($name);

    if ($configuration->isNew()) {
      // Configuration doesn't exist.
      continue;
    }

    // Set email subject text.
    if (empty($configuration->get('plugin_config.invitation_subject')) && !empty($invite_settings['invite_subject'])) {
      $configuration->set('plugin_config.invitation_subject', $invite_settings['invite_subject']);
      $configuration->save();
    }
    // Set email body text.
    if (empty($configuration->get('plugin_config.invitation_body')) && !empty($invite_settings['invite_message'])) {
      $configuration->set('plugin_config.invitation_body', $invite_settings['invite_message']);
      $configuration->save();
    }
  }
}

/**
 * Add the invite emails to the disabled user greetings key.
 */
function social_group_invite_update_11502(): void {
  $settings = \Drupal::configFactory()->getEditable('social_swiftmail.settings');
  $disabled_greeting_keys = $settings->get("disabled_user_greeting_keys");
  $disabled_greeting_keys = array_filter(explode("\r\n", $disabled_greeting_keys));

  $new_disable_greeting_keys = [
    'invite',
  ];
  $new_disable_greeting_keys = array_diff($new_disable_greeting_keys, $disabled_greeting_keys);
  foreach ($new_disable_greeting_keys as $new_key) {
    $disabled_greeting_keys[] = $new_key;
  }

  $settings->set('disabled_user_greeting_keys', implode("\r\n", $disabled_greeting_keys))->save();
}

/**
 * Update email invitation messages with new token for the symfony mailer.
 *
 * After introducing the symfony mailer the steps in building an email changed
 * giving us issues with replacing the current-user in the invitation batch,
 * resulting in anonymous. We replace this with the user token where we set
 * the correct data in the symfony email builder for group invitations.
 */
function social_group_invite_update_11503(): void {
  $config_factory = \Drupal::configFactory();

  // Update default invite configuration.
  $configuration = $config_factory->getEditable('social_group.settings');
  if (!empty($configuration->get('group_invite.invite_subject'))) {
    $subject = str_replace('[current-user:display-name]', '[user:display-name]', $configuration->get('group_invite.invite_subject'));
    $configuration->set('group_invite.invite_subject', $subject);
    $configuration->save();
  }
  if (!empty($configuration->get('group_invite.invite_message'))) {
    $body = str_replace('[current-user:display-name]', '[user:display-name]', $configuration->get('group_invite.invite_message'));
    $configuration->set('group_invite.invite_message', $body);
    $configuration->save();
  }

  // Update the group content specific invite configuration.
  $configurations = [
    'group.content_type.closed_group-group_invitation',
    'group.content_type.flexible_group-group_invitation',
    'group.content_type.open_group-group_invitation',
    'group.content_type.public_group-group_invitation',
    'group.content_type.secret_group-group_invitation',
  ];

  foreach ($configurations as $name) {
    $configuration = $config_factory->getEditable($name);

    if ($configuration->isNew()) {
      // Skip if the configuration doesn't exist.
      continue;
    }

    // Set email subject text.
    if (!empty($configuration->get('plugin_config.invitation_subject'))) {
      $subject = str_replace('[current-user:display-name]', '[user:display-name]', $configuration->get('plugin_config.invitation_subject'));
      $configuration->set('plugin_config.invitation_subject', $subject);
      $configuration->save();
    }
    // Set email body text.
    if (!empty($configuration->get('plugin_config.invitation_body'))) {
      $body = str_replace('[current-user:display-name]', '[user:display-name]', $configuration->get('plugin_config.invitation_body'));
      $configuration->set('plugin_config.invitation_body', $body);
      $configuration->save();
    }
  }
}

/**
 * Update views bulk operations actions to make them translatable.
 */
function social_group_invite_update_12001(): string {
  /** @var \Drupal\update_helper\Updater $updateHelper */
  $updateHelper = \Drupal::service('update_helper.updater');

  // Execute configuration update definitions with logging of success.
  $updateHelper->executeUpdate('social_group_invite', __FUNCTION__);

  // Output logged messages to related channel of update execution.
  return $updateHelper->logger()->output();
}

/**
 * Update email invitation messages with new token for the symfony mailer.
 */
function social_group_invite_update_13001(): void {
  $config_factory = \Drupal::configFactory();

  // Groups to look for translation.
  $groups = [
    'secret_group',
    'closed_group',
    'flexible_group',
    'open_group',
    'public_group',
  ];

  foreach ($groups as $group) {
    $config_name = sprintf('group.content_type.%s-group_invitation', $group);
    $configuration = $config_factory->getEditable($config_name);

    // When the plugin is empty, go to the next.
    $plugin_config_data = $configuration->getOriginal('plugin_config');
    if (empty($plugin_config_data)) {
      continue;
    }

    // Change tokens.
    if (!empty($plugin_config_data['existing_user_invitation_subject'])) {
      $plugin_config_data['existing_user_invitation_subject'] = str_replace('[current-user:display-name]', '[user:display-name]', $plugin_config_data['existing_user_invitation_subject']);
    }
    if (!empty($plugin_config_data['existing_user_invitation_body'])) {
      $plugin_config_data['existing_user_invitation_body'] = str_replace('[current-user:display-name]', '[user:display-name]', $plugin_config_data['existing_user_invitation_body']);
    }
    $configuration->set('plugin_config', $plugin_config_data);
    $configuration->save();

    // When the Social Language is disabled, go to the next.
    if (!\Drupal::service('module_handler')->moduleExists('social_language')) {
      continue;
    }

    // Change token from email template from languages.
    $language_manager = \Drupal::languageManager();
    foreach ($language_manager->getLanguages() as $language) {
      if (!$language_manager instanceof ConfigurableLanguageManagerInterface) {
        continue;
      }
      $config_translation = $language_manager->getLanguageConfigOverride($language->getId(), $config_name);

      // When the current language don't have translation, go to the next.
      $plugin_config_data = $config_translation->get('plugin_config');
      if (empty($plugin_config_data)) {
        continue;
      }

      // Change tokens.
      if (!empty($plugin_config_data['existing_user_invitation_subject'])) {
        $plugin_config_data['existing_user_invitation_subject'] = str_replace('[current-user:display-name]', '[user:display-name]', $plugin_config_data['existing_user_invitation_subject']);
      }
      if (!empty($plugin_config_data['existing_user_invitation_body'])) {
        $plugin_config_data['existing_user_invitation_body'] = str_replace('[current-user:display-name]', '[user:display-name]', $plugin_config_data['existing_user_invitation_body']);
      }
      $config_translation->set('plugin_config', $plugin_config_data);
      $config_translation->save();
    }
  }
}

/**
 * Update user group invitations view configuration.
 */
function social_group_invite_update_13002() {
  $config_factory = \Drupal::configFactory();
  $config = $config_factory->getEditable('views.view.social_group_user_invitations');

  // Let's check if this configuration object does exist in storage before
  // updating it.
  if (!$config->isNew()) {
    $config->set('display.default.display_options.filters.uid_current', [
      'admin_label' => '',
      'entity_type' => 'user',
      'expose' => [
        'description' => '',
        'identifier' => '',
        'label' => '',
        'multiple' => FALSE,
        'operator' => '',
        'operator_id' => '',
        'operator_limit_selection' => FALSE,
        'operator_list' => [],
        'remember' => FALSE,
        'remember_roles' => [
          'authenticated' => 'authenticated',
        ],
        'required' => FALSE,
        'use_operator' => FALSE,
      ],
      'exposed' => FALSE,
      'field' => 'uid_current',
      'group' => 1,
      'group_info' => [
        'default_group' => 'All',
        'default_group_multiple' => [],
        'description' => '',
        'group_items' => [],
        'identifier' => '',
        'label' => '',
        'multiple' => FALSE,
        'optional' => TRUE,
        'remember' => FALSE,
        'widget' => 'select',
      ],
      'group_type' => 'group',
      'id' => 'uid_current',
      'is_grouped' => FALSE,
      'operator' => '=',
      'plugin_id' => 'user_current',
      'relationship' => 'gc__user',
      'table' => 'users',
      'value' => '1',
    ]);

    $config->set('display.default.display_options.access.options.role', [
      'administrator' => 'administrator',
      'verified' => 'verified',
    ]);

    $config->save();
  }
}
