<?php

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

/**
 * Implements hook_install().
 */
function password_policy_install() {
  // Set user password reset timestamp to now.
  $timestamp = gmdate(DATETIME_DATETIME_STORAGE_FORMAT, REQUEST_TIME);
  /** @var \Drupal\user\UserInterface[] $users */
  $users = \Drupal::entityTypeManager()->getStorage('user')->loadMultiple();
  // @todo Get rid of updating all users.
  foreach ($users as $user) {
    $user
      ->set('field_last_password_reset', $timestamp)
      ->set('field_password_expiration', '0')
      ->save();
  }

  // Rebuild user entity form display for new fields.
  $storage = \Drupal::entityTypeManager()->getStorage('entity_form_display');
  /** @var $user_form_display \Drupal\Core\Entity\Display\EntityFormDisplayInterface */
  $user_form_display = $storage->load('user.user.default');
  if (!$user_form_display) {
    $user_form_display = $storage->create([
      'targetEntityType' => 'user',
      'bundle' => 'user',
      'mode' => 'default',
      'status' => TRUE,
    ]);
  }
  $user_form_display
    ->setComponent('field_last_password_reset', [
      'type' => 'datetime_default',
      // Display before contact standard profile field.
      'weight' => 4,
      'settings' => [],
    ])
    ->setComponent('field_password_expiration', [
      'type' => 'boolean_checkbox',
      'weight' => 3,
      'settings' => ['display_label' => TRUE],
    ])
    ->save();
}
