<?php

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

/**
 * Implements hook_install().
 */
function social_gdpr_install() {
  // Grant the default permissions for this feature.
  user_role_grant_permissions(
    'sitemanager',
    [
      'administer data policy settings',
      'administer data policy entities',
      'edit data policy',
      'view all data policy revisions',
      'access data policy revisions',
      'revert all data policy revisions',
      'overview user consents',
      'edit inform and consent setting',
      'overview inform and consent settings',
      'administer inform and consent settings',
      'change inform and consent setting status',
    ]
  );

  \Drupal::configFactory()->getEditable('data_policy.data_policy')
    ->set('enforce_consent', TRUE)
    ->save();
}

/**
 * Update data policy permissions with new administer entities permission.
 */
function social_gdpr_update_8901() {
  user_role_grant_permissions('sitemanager', ['administer data policy entities']);
}

/**
 * Add permissions for SM to add translations for Data Policy.
 */
function social_gdpr_update_8902() {
  user_role_grant_permissions('sitemanager', ['translate data_policy']);
}

/**
 * Search for invalid permission(s) and remove them from existing roles.
 *
 * Permissions to check:
 * - "translate data_policy".
 */
function social_gdpr_update_111101(): void {
  $entity_type_manager = \Drupal::entityTypeManager();
  $all_permissions = array_keys(\Drupal::service('user.permissions')->getPermissions());
  /** @var \Drupal\user\RoleInterface[] $roles */
  $roles = $entity_type_manager->getStorage('user_role')->loadMultiple();

  $permissions_to_check = [
    'translate data_policy',
  ];

  // If permission is not valid (is not on the list of all permissions),
  // we need to revoke it from all existing roles.
  foreach ($permissions_to_check as $permission_to_check) {
    if (!in_array($permission_to_check, $all_permissions)) {
      foreach ($roles as $role) {
        if ($role->hasPermission($permission_to_check)) {
          $role->revokePermission($permission_to_check);
          $role->save();
        }
      }
    }
  }
}
