<?php

/**
 * @file
 * Contains update functions for Page Manager.
 */

/**
 * Install the Page Manager UI for existing sites.
 */
function page_manager_update_8001() {
  \Drupal::service('module_installer')->install(['page_manager_ui']);
}

/**
 * Rename layout machine names to match layout discovery's default layouts.
 */
function page_manager_update_8002() {
  $names = \Drupal::configFactory()->listAll('page_manager.page_variant');
  foreach ($names as $name) {
    $config = \Drupal::configFactory()->getEditable($name);
    if ($config->get('variant') === 'panels_variant' && \Drupal::moduleHandler()->moduleExists('panels')) {
      \Drupal::moduleHandler()->loadInclude('panels', 'install');

      if (!function_exists('panels_convert_plugin_ids_to_layout_discovery')) {
        throw new \Exception('Panels helper function does not exist, the latest Panels 4.x-dev snapshot is required to run this update.');
      }

      $layout_id = $config->get('variant_settings.layout');
      if ($new_layout_id = panels_convert_plugin_ids_to_layout_discovery($layout_id)) {
        $config->set('variant_settings.layout', $new_layout_id);
        $config->save();
      }
    }
  }
}

/**
 * Add "redirect_location" key to all "http_status_code" page variant.
 */
function page_manager_update_8401() {
  $names = \Drupal::configFactory()->listAll('page_manager.page_variant');
  foreach ($names as $name) {
    $config = \Drupal::configFactory()->getEditable($name);
    if ($config->get('variant') === 'http_status_code') {
      $variant_settings = $config->get('variant_settings');
      if (!array_key_exists('redirect_location', $variant_settings)) {
        $config->set('variant_settings.redirect_location', '');
        $config->save();
      }
    }
  }
}
