<?php

/**
 * @file
 * Post update functions for LocalGov Elections.
 */

use Drupal\Core\Config\FileStorage;

/**
 * Install new election areas admin view.
 */
function localgov_elections_post_update_install_areas_admin_view(): void {
  $config_name = 'views.view.localgov_election_areas_admin';

  // Check if view already exists.
  $config = \Drupal::configFactory()->getEditable($config_name);
  if (!$config->isNew()) {
    \Drupal::logger('localgov_elections')->notice(
      'View @name already exists, skipping installation.',
      ['@name' => $config_name]
    );
    return;
  }

  // Load the configuration from the install directory.
  $module_path = \Drupal::service('extension.list.module')
    ->getPath('localgov_elections');
  $config_path = $module_path . '/config/install';
  $source = new FileStorage($config_path);

  $data = $source->read($config_name);
  if (!$data) {
    \Drupal::logger('localgov_elections')->error(
      'Config @name not found in module install directory.',
      ['@name' => $config_name]
    );
    return;
  }

  // Install the view configuration.
  $config->setData($data)->save(TRUE);

  \Drupal::logger('localgov_elections')->notice(
    'Installed election areas admin view.'
  );
}
