<?php

/**
 * @file
 * The social profile fields install file.
 */

use Drupal\Core\Config\FileStorage;
use Drupal\search_api\Entity\Index;
use Drupal\user\Entity\User;
use Symfony\Component\Yaml\Yaml;

/**
 * Implements hook_install().
 */
function social_profile_fields_install() {
  // Set some default permissions.
  // Clear the entity field manager cached field definitions as the address
  // field overrides settings need to be applied.
  _social_profile_fields_set_permissions();
  _social_profile_fields_update_search_index();
  _social_profile_fields_update_search_index('social_all');
  _social_profile_fields_nationalities();
}

/**
 * Disable and enable the search index, so the nickname field is added.
 */
function social_profile_fields_update_8001() {
  _social_profile_fields_update_search_index();
}

/**
 * Disable and enable the main search index, so the nickname field is added.
 */
function social_profile_fields_update_8002() {
  _social_profile_fields_update_search_index('social_all');
}

/**
 * Function to set permissions.
 */
function _social_profile_fields_set_permissions() {
  user_role_grant_permissions('sitemanager', ['social profile fields change used profile fields']);
}

/**
 * Disable and enable the search index, so the nickname field is added.
 *
 * @param string $index_id
 *   The search index ID.
 */
function _social_profile_fields_update_search_index($index_id = 'social_users') {
  /** @var \Drupal\search_api\IndexInterface $index */
  $index = Index::load($index_id);

  $logger = \Drupal::logger('social_profile_fields');
  $logger->info('Loaded search index');

  // If currently enabled we will first disabled and enable the index.
  if ($index !== NULL && $index->status()) {
    $logger->info('Search index exists');

    // Elevate permissions so we can index *all* the items.
    $accountSwitcher = \Drupal::service('account_switcher');
    $account = User::load(1);
    $accountSwitcher->switchTo($account);

    // Disable and enable the index so the tagging field is properly added.
    $index->disable()->save();
    $logger->info('Search index disabled');
    $index->enable()->save();
    $logger->info('Search index enabled');

    // Restore user account.
    $accountSwitcher->switchBack();
  }
}

/**
 * Add a field for nationality.
 */
function social_profile_fields_update_8003() {
  $entity_type_ids = [
    'taxonomy.vocabulary.' => 'taxonomy_vocabulary',
    'field.storage.profile.field_profile_' => 'field_storage_config',
    'field.field.profile.profile.field_profile_' => 'field_config',
  ];

  $path = \Drupal::service('extension.list.module')->getPath('social_profile_fields') . '/config/static/';

  foreach ($entity_type_ids as $prefix => $entity_type_id) {
    $config_file = $path . $prefix . 'nationality_8003.yml';
    $settings = Yaml::parseFile($config_file);

    /** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $storage */
    $storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);

    $storage->createFromStorageRecord($settings)->save();
  }

  _social_profile_fields_nationalities();
}

/**
 * Create taxonomy terms for nationalities in the "Nationality" vocabulary.
 */
function _social_profile_fields_nationalities() {
  $path = \Drupal::service('extension.list.module')->getPath('social_profile_fields') . '/content/';
  $data = Yaml::parseFile($path . 'nationalities.yml');

  $storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');

  foreach ($data['nationalities'] as $nationality) {
    /** @var \Drupal\taxonomy\TermInterface $term */
    $term = $storage->create(['vid' => 'nationality']);

    $term->setName($nationality)->save();
  }
}

/**
 * Make "Nationality" vocabulary translatable.
 */
function social_profile_fields_update_11201(): void {
  if (!\Drupal::moduleHandler()->moduleExists('social_content_translation')) {
    return;
  }

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

  $config_storage->write('language.content_settings.taxonomy_term.nationality', (array) $source->read('language.content_settings.taxonomy_term.nationality_11201'));
}

/**
 * Add new permissions for taxonomies.
 */
function social_profile_fields_update_121001(): void {
  // Nothing to do if the module is not installed.
  if (!\Drupal::moduleHandler()->moduleExists("taxonomy_access_fix")) {
    return;
  }

  // Permission to grant.
  $taxonomy_permissions = [
    'view terms in nationality',
    'view term names in nationality',
    'select terms in nationality',
  ];

  // Authenticated roles.
  $authenticated_roles = [
    'sitemanager',
    'verified',
    'contentmanager',
  ];

  // Load the permission.
  $entity_type_manager = \Drupal::entityTypeManager();
  foreach ($authenticated_roles as $role) {
    /** @var \Drupal\user\RoleInterface $role */
    $role = $entity_type_manager->getStorage('user_role')->load($role);

    // If the role does not have the permission, grant permission.
    foreach ($taxonomy_permissions as $taxonomy_permission) {
      if (!$role->hasPermission($taxonomy_permission)) {
        $role->grantPermission($taxonomy_permission);
        $role->save();
      }
    }
  }

  // For anonymous role, we need to check the if Registration Fields is enabled.
  if (!\Drupal::moduleHandler()->moduleExists("social_registration_fields")) {
    return;
  }

  // Load anonymous role.
  /** @var \Drupal\user\RoleInterface $role */
  $role = $entity_type_manager->getStorage('user_role')->load('anonymous');

  // If the role does not have the permission, grant permission.
  foreach ($taxonomy_permissions as $taxonomy_permission) {
    if (!$role->hasPermission($taxonomy_permission)) {
      $role->grantPermission($taxonomy_permission);
      $role->save();
    }
  }
}
