<?php

/**
 * @file
 * Install and update hooks for Social Swiftmailer.
 */

/**
 * Implements hook_install().
 *
 * Perform actions related to the installation of social_swiftmail.
 */
function social_swiftmail_install() {
  $config_factory = \Drupal::configFactory();

  // Grant the default permissions for this feature.
  user_role_grant_permissions(
    'verified',
    [
      'use text format mail_html',
    ]
  );
  user_role_grant_permissions(
    'contentmanager',
    [
      'use text format mail_html',
    ]
  );
  user_role_grant_permissions(
    'sitemanager',
    [
      'use text format mail_html',
      'administer social swiftmail',
    ]
  );

  // Remove unnecessary mailer policies and set the correct theme to the default
  // policy.
  $keys = $config_factory->listAll('symfony_mailer.mailer_policy.');

  foreach ($keys as $key) {
    $config = $config_factory->getEditable($key);

    if ($key === 'symfony_mailer.mailer_policy._') {
      // Get our mailer_policy configuration.
      $configuration = $config->getOriginal('configuration');

      // Unset the old plugin and replace it with the new plugin.
      if (!empty($configuration) && isset($configuration['mailer_inline_css'])) {
        unset($configuration['mailer_inline_css']);
        $configuration['mailer_inline_css_social'] = [];
      }

      // Make sure we add our fallback text format option.
      $configuration['mail_html_text_format'] = [];
      $config->set('configuration', $configuration);
      $config->save();

      $config
        ->set('configuration.email_theme.theme', '_default')
        ->save();
    }
    else {
      $config->delete();
    }
  }
}

/**
 * Set which theme to use when sending emails.
 */
function social_swiftmail_update_8001() {
  // Alter mailsystem settings.
  $mailsystem_settings = \Drupal::configFactory()->getEditable('mailsystem.settings');
  $mailsystem_settings->set('theme', 'default')->save();
}

/**
 * Set swiftmail permissions for sitemanagers settings.
 */
function social_swiftmail_update_8002() {
  // Give SM the correct permission.
  user_role_grant_permissions('sitemanager', [
    'use text format mail_html',
    'administer social swiftmail',
  ]);
}

/**
 * Allow using the "Mail HTML" text format by the logged user.
 */
function social_swiftmail_update_8003() {
  $roles = \Drupal::entityQuery('user_role')
    ->condition('id', [
      'authenticated',
      'contentmanager',
    ], 'IN')
    ->execute();

  foreach ($roles as $role) {
    user_role_grant_permissions($role, ['use text format mail_html']);
  }
}

/**
 * Add a new module setting.
 */
function social_swiftmail_update_11001(): void {
  $settings = \Drupal::configFactory()->getEditable('social_swiftmail.settings');
  $settings->set('disabled_user_greeting_key', 'register_no_approval_required')->save();
}

/**
 * Update the disabled user greetings key to set a default.
 */
function social_swiftmail_update_11002(): 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 = [
    'register_admin_created',
    'register_pending_approval',
    'register_pending_approval_admin',
    'register_no_approval_required',
    'status_activated',
    'status_blocked',
    'cancel_confirm',
    'status_canceled',
    'password_reset',
  ];
  $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();
}

/**
 * Migrate from Swiftmailer to Symfony mailer.
 */
function social_swiftmail_update_11003(): void {
  // Uninstall the Swiftmailer.
  /** @var \Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');
  $module_installer->uninstall(['swiftmailer', 'mailsystem']);

  // Install the Symfony mailer.
  $module_installer->install(['symfony_mailer']);
  // Remove unnecessary mailer policies and set the correct theme to the default
  // policy.
  $config_factory = \Drupal::configFactory();
  $keys = $config_factory->listAll('symfony_mailer.mailer_policy.');

  foreach ($keys as $key) {
    $config = $config_factory->getEditable($key);

    if ($key === 'symfony_mailer.mailer_policy._') {
      $config
        ->set('configuration.email_theme.theme', '_default')
        ->save();
    }
    else {
      $config->delete();
    }
  }
}

/**
 * Replace the mailer_inline_css plugin for our mailer_inline_css_social plugin.
 */
function social_swiftmail_update_11004(): void {
  $config_factory = \Drupal::configFactory();
  // Get our mailer_policy configuration.
  $config_mailer = $config_factory->getEditable('symfony_mailer.mailer_policy._');
  $configuration = $config_mailer->getOriginal('configuration');

  // Unset the old plugin and replace it with the new plugin.
  if (!empty($configuration) && isset($configuration['mailer_inline_css'])) {
    unset($configuration['mailer_inline_css']);
    $configuration['mailer_inline_css_social'] = [];
  }

  // Make sure we add our fallback text format option.
  $configuration['mail_html_text_format'] = [];
  $config_mailer->set('configuration', $configuration);
  $config_mailer->save();
}
