<?php
/**
 * Multisite Control Addon
 *
 * Network defaults + site override engine for selected modules.
 *
 * @package Polanger_Dashboard_Tools
 */

if ( ! defined( 'ABSPATH' ) ) {
  exit;
}

class PDT_Multisite_Control {

  /**
   * Network settings option key.
   */
  const NETWORK_OPTION = 'polanger_network_settings';

  /**
   * Site override option key.
   */
  const SITE_OVERRIDE_OPTION = 'polanger_site_override_settings';

  /**
   * Supported option map.
   *
   * @var array<string,string>
   */
  private $managed_options = array(
    'pdt_settings'                   => 'menu_manager',
    'pdt_admin_bar_settings'         => 'admin_bar',
    'pdt_general_settings'           => 'general',
    'pdt_login_page_settings'        => 'login',
    'pdt_activity_log_settings'      => 'activity_log',
    'pdt_dashboard_widgets_settings' => 'dashboard_widgets',
  );

  /**
   * Constructor.
   */
  public function __construct() {
    if ( ! is_multisite() ) {
      return;
    }

    add_filter( 'polanger_effective_settings', array( $this, 'filter_effective_settings' ), 10, 4 );
    add_action( 'pdt_admin_menu_after_dashboard_center', array( $this, 'register_site_page' ), 10, 0 );
    add_action( 'network_admin_menu', array( $this, 'register_network_page' ) );
    add_action( 'admin_post_pdt_multisite_save_site', array( $this, 'handle_site_save' ) );
    add_action( 'network_admin_edit_pdt_multisite_save_network', array( $this, 'handle_network_save' ) );
    add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
    add_action( 'network_admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
    add_action( 'admin_notices', array( $this, 'render_locked_page_notice' ) );
  }

  /**
   * Register network-level settings page.
   *
   * @return void
   */
  public function register_network_page() {
    if ( ! current_user_can( 'manage_network_options' ) ) {
      return;
    }

    add_submenu_page(
      'settings.php',
      __( 'Polanger Multisite Control', 'polanger-admin-menu-manager' ),
      __( 'Polanger Control', 'polanger-admin-menu-manager' ),
      'manage_network_options',
      'polanger-multisite-network-control',
      array( $this, 'render_network_page' )
    );
  }

  /**
   * Register site-level multisite settings page.
   *
   * @return void
   */
  public function register_site_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
      return;
    }

    add_submenu_page(
      'polanger-dashboard',
      __( 'Multisite Control', 'polanger-admin-menu-manager' ),
      __( 'Multisite Control', 'polanger-admin-menu-manager' ),
      'manage_options',
      'polanger-multisite-control',
      array( $this, 'render_site_page' )
    );
  }

  /**
   * Enqueue shared admin styles for addon pages.
   *
   * @return void
   */
  public function enqueue_assets() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
    $locked_feature = $this->get_locked_feature_for_current_page();
    if ( ! in_array( $page, array( 'polanger-multisite-control', 'polanger-multisite-network-control' ), true ) && empty( $locked_feature ) ) {
      return;
    }

    wp_enqueue_style(
      'pdt-admin-style',
      plugin_dir_url( PDT_PLUGIN_FILE ) . 'assets/css/pdt.css',
      array(),
      PDT_VERSION
    );
    wp_enqueue_style(
      'pdt-settings-style',
      plugin_dir_url( PDT_PLUGIN_FILE ) . 'assets/css/settings-page.css',
      array(),
      PDT_VERSION
    );
    wp_enqueue_style(
      'pdt-multisite-control-style',
      plugin_dir_url( __FILE__ ) . 'css/multisite-control.css',
      array( 'pdt-admin-style', 'pdt-settings-style' ),
      PDT_VERSION
    );

    if ( ! empty( $locked_feature ) ) {
      wp_enqueue_script( 'jquery' );
      wp_add_inline_style(
        'pdt-multisite-control-style',
        '.pdt-network-locked-page form{opacity:.72}.pdt-network-locked-page input:disabled,.pdt-network-locked-page select:disabled,.pdt-network-locked-page textarea:disabled{cursor:not-allowed}'
      );
      wp_add_inline_script(
        'jquery-core',
        "document.addEventListener('DOMContentLoaded',function(){document.body.classList.add('pdt-network-locked-page');document.querySelectorAll('form').forEach(function(form){form.querySelectorAll('input,select,textarea,button').forEach(function(field){if(field.type==='hidden'){return;}field.disabled=true;});});});"
      );
    }
  }

  /**
   * Render notice when current module page is locked by network policy.
   *
   * @return void
   */
  public function render_locked_page_notice() {
    $locked_feature = $this->get_locked_feature_for_current_page();
    if ( empty( $locked_feature ) ) {
      return;
    }

    echo '<div class="notice notice-warning"><p><strong>' . esc_html__( 'Network Locked:', 'polanger-admin-menu-manager' ) . '</strong> ' . esc_html__( 'This module is controlled by network settings. Local changes are disabled for this site.', 'polanger-admin-menu-manager' ) . '</p></div>';
  }

  /**
   * Filter effective settings by merging network + site values.
   *
   * @param array  $settings    Site settings.
   * @param string $option_name Option key.
   * @param array  $defaults    Defaults.
   * @param string $context     Runtime context.
   * @return array
   */
  public function filter_effective_settings( $settings, $option_name, $defaults, $context ) {
    if ( ! isset( $this->managed_options[ $option_name ] ) ) {
      return $settings;
    }

    $network_settings = $this->get_network_settings();
    if ( empty( $network_settings['enabled'] ) ) {
      return $settings;
    }

    $feature_key = $this->managed_options[ $option_name ];
    $network_defaults = isset( $network_settings['defaults'][ $option_name ] ) && is_array( $network_settings['defaults'][ $option_name ] )
      ? $network_settings['defaults'][ $option_name ]
      : array();

    $is_locked = ! empty( $network_settings['locks'][ $feature_key ] );
    if ( $is_locked ) {
      return array_replace_recursive( $settings, $network_defaults );
    }

    $site_override = $this->is_site_override_enabled( $option_name );
    $allow_override = apply_filters( 'polanger_allow_site_override', ! empty( $network_settings['allow_site_override'] ), $feature_key, $context );

    if ( $allow_override && $site_override ) {
      return $settings;
    }

    return array_replace_recursive( $settings, $network_defaults );
  }

  /**
   * Handle network page save.
   *
   * @return void
   */
  public function handle_network_save() {
    if ( ! current_user_can( 'manage_network_options' ) ) {
      wp_die( esc_html__( 'Permission denied.', 'polanger-admin-menu-manager' ) );
    }

    check_admin_referer( 'pdt_multisite_network_settings' );

    $input = isset( $_POST['pdt_multisite_network'] ) && is_array( $_POST['pdt_multisite_network'] )
      ? wp_unslash( $_POST['pdt_multisite_network'] )
      : array();

    $settings = $this->sanitize_network_settings( $input );
    update_site_option( self::NETWORK_OPTION, $settings );
    $this->update_network_active_state( $input );

    do_action( 'polanger_network_settings_saved', $settings );

    wp_safe_redirect(
      add_query_arg(
        array(
          'page'    => 'polanger-multisite-network-control',
          'updated' => '1',
        ),
        network_admin_url( 'settings.php' )
      )
    );
    exit;
  }

  /**
   * Handle site page save.
   *
   * @return void
   */
  public function handle_site_save() {
    if ( ! current_user_can( 'manage_options' ) ) {
      wp_die( esc_html__( 'Permission denied.', 'polanger-admin-menu-manager' ) );
    }

    check_admin_referer( 'pdt_multisite_site_settings' );

    $input = isset( $_POST['pdt_multisite_site'] ) && is_array( $_POST['pdt_multisite_site'] )
      ? wp_unslash( $_POST['pdt_multisite_site'] )
      : array();

    $overrides = array();
    foreach ( $this->managed_options as $option_name => $feature_key ) {
      $overrides[ $option_name ] = ! empty( $input['override'][ $option_name ] );
    }

    update_option( self::SITE_OVERRIDE_OPTION, $overrides );
    do_action( 'polanger_settings_saved', $overrides );

    wp_safe_redirect(
      add_query_arg(
        array(
          'page'    => 'polanger-multisite-control',
          'updated' => '1',
        ),
        admin_url( 'admin.php' )
      )
    );
    exit;
  }

  /**
   * Render network page.
   *
   * @return void
   */
  public function render_network_page() {
    if ( ! current_user_can( 'manage_network_options' ) ) {
      wp_die( esc_html__( 'Permission denied.', 'polanger-admin-menu-manager' ) );
    }

    $settings = $this->get_network_settings();
    ?>
    <div id="pdt-wrap" class="pdt-ms-wrap">
      <div class="pdt-header">
        <h2 class="pdt-title"><?php esc_html_e( 'Multisite Network Control', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="pdt-subtitle"><?php esc_html_e( 'Set global defaults, lock policies, and site override behavior for all network sites.', 'polanger-admin-menu-manager' ); ?></p>
      </div>

      <?php
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended
      if ( isset( $_GET['updated'] ) && '1' === sanitize_text_field( wp_unslash( $_GET['updated'] ) ) ) :
      ?>
        <div class="pdt-notice pdt-notice-success"><span class="dashicons dashicons-yes-alt"></span><?php esc_html_e( 'Network settings saved.', 'polanger-admin-menu-manager' ); ?></div>
      <?php endif; ?>

      <form method="post" action="<?php echo esc_url( network_admin_url( 'edit.php?action=pdt_multisite_save_network' ) ); ?>" class="pdt-settings-form pdt-ms-form">
        <?php wp_nonce_field( 'pdt_multisite_network_settings' ); ?>

        <div class="pdt-settings-section">
          <h2><?php esc_html_e( 'Global Control', 'polanger-admin-menu-manager' ); ?></h2>
          <label class="pdt-toggle-switch">
            <input type="checkbox" name="pdt_multisite_network[enabled]" value="1" <?php checked( ! empty( $settings['enabled'] ) ); ?> />
            <span class="pdt-toggle-slider"></span>
            <span class="pdt-toggle-label"><?php esc_html_e( 'Enable network-wide control', 'polanger-admin-menu-manager' ); ?></span>
          </label>
          <p class="description"><?php esc_html_e( 'When enabled, network defaults are used across all sites unless a site override is allowed and enabled.', 'polanger-admin-menu-manager' ); ?></p>
          <p>
            <label>
              <input type="checkbox" name="pdt_multisite_network[network_active]" value="1" <?php checked( $this->is_network_active() ); ?> />
              <?php esc_html_e( 'Keep Multisite Control active network-wide', 'polanger-admin-menu-manager' ); ?>
            </label>
          </p>
        </div>

        <div class="pdt-settings-section">
          <h2><?php esc_html_e( 'Site Override Policy', 'polanger-admin-menu-manager' ); ?></h2>
          <label class="pdt-toggle-switch">
            <input type="checkbox" name="pdt_multisite_network[allow_site_override]" value="1" <?php checked( ! empty( $settings['allow_site_override'] ) ); ?> />
            <span class="pdt-toggle-slider"></span>
            <span class="pdt-toggle-label"><?php esc_html_e( 'Allow site-level override', 'polanger-admin-menu-manager' ); ?></span>
          </label>
          <p class="description"><?php esc_html_e( 'Sites can override unlocked modules when this option is enabled.', 'polanger-admin-menu-manager' ); ?></p>
        </div>

        <div class="pdt-settings-section">
          <h2><?php esc_html_e( 'Lock System', 'polanger-admin-menu-manager' ); ?></h2>
          <div class="pdt-checkbox-grid">
            <label><input type="checkbox" name="pdt_multisite_network[locks][menu_manager]" value="1" <?php checked( ! empty( $settings['locks']['menu_manager'] ) ); ?> /> <?php esc_html_e( 'Menu Manager (Lock)', 'polanger-admin-menu-manager' ); ?></label>
            <label><input type="checkbox" name="pdt_multisite_network[locks][admin_bar]" value="1" <?php checked( ! empty( $settings['locks']['admin_bar'] ) ); ?> /> <?php esc_html_e( 'Admin Bar (Lock)', 'polanger-admin-menu-manager' ); ?></label>
            <label><input type="checkbox" name="pdt_multisite_network[locks][general]" value="1" <?php checked( ! empty( $settings['locks']['general'] ) ); ?> /> <?php esc_html_e( 'General Settings (Lock)', 'polanger-admin-menu-manager' ); ?></label>
            <label><input type="checkbox" name="pdt_multisite_network[locks][login]" value="1" <?php checked( ! empty( $settings['locks']['login'] ) ); ?> /> <?php esc_html_e( 'Login Security (Lock)', 'polanger-admin-menu-manager' ); ?></label>
            <label><input type="checkbox" name="pdt_multisite_network[locks][activity_log]" value="1" <?php checked( ! empty( $settings['locks']['activity_log'] ) ); ?> /> <?php esc_html_e( 'Activity Log (Lock)', 'polanger-admin-menu-manager' ); ?></label>
            <label><input type="checkbox" name="pdt_multisite_network[locks][dashboard_widgets]" value="1" <?php checked( ! empty( $settings['locks']['dashboard_widgets'] ) ); ?> /> <?php esc_html_e( 'Dashboard Center (Lock)', 'polanger-admin-menu-manager' ); ?></label>
          </div>
        </div>

        <div class="pdt-settings-section">
          <h2><?php esc_html_e( 'Network Defaults', 'polanger-admin-menu-manager' ); ?></h2>
          <p class="description"><?php esc_html_e( 'These defaults are applied to all sites when network-wide control is enabled.', 'polanger-admin-menu-manager' ); ?></p>

          <div class="pdt-ms-capture-grid">
            <?php foreach ( $this->managed_options as $option_name => $feature_key ) : ?>
              <label>
                <input type="checkbox" name="pdt_multisite_network[capture_defaults][<?php echo esc_attr( $option_name ); ?>]" value="1" />
                <?php
                printf(
                  /* translators: %s: Feature label. */
                  esc_html__( 'Use this site\'s current %s settings as network defaults', 'polanger-admin-menu-manager' ),
                  esc_html( $this->get_feature_label( $feature_key ) )
                );
                ?>
              </label>
            <?php endforeach; ?>
          </div>
          <p class="description"><?php esc_html_e( 'Use these capture options when you want the full current module configuration to become the network default without duplicating every module UI here.', 'polanger-admin-menu-manager' ); ?></p>

          <h3><?php esc_html_e( 'General', 'polanger-admin-menu-manager' ); ?></h3>
          <p>
            <label>
              <?php esc_html_e( 'Log Visibility', 'polanger-admin-menu-manager' ); ?>
              <select name="pdt_multisite_network[defaults][pdt_general_settings][log_visibility]">
                <option value="all" <?php selected( $settings['defaults']['pdt_general_settings']['log_visibility'], 'all' ); ?>><?php esc_html_e( 'All allowed users', 'polanger-admin-menu-manager' ); ?></option>
                <option value="super_admin" <?php selected( $settings['defaults']['pdt_general_settings']['log_visibility'], 'super_admin' ); ?>><?php esc_html_e( 'Super Admin only', 'polanger-admin-menu-manager' ); ?></option>
              </select>
            </label>
          </p>

          <h3><?php esc_html_e( 'Login', 'polanger-admin-menu-manager' ); ?></h3>
          <p>
            <label><input type="checkbox" name="pdt_multisite_network[defaults][pdt_login_page_settings][enable_recaptcha]" value="1" <?php checked( ! empty( $settings['defaults']['pdt_login_page_settings']['enable_recaptcha'] ) ); ?> /> <?php esc_html_e( 'Enable reCAPTCHA by default', 'polanger-admin-menu-manager' ); ?></label>
          </p>
          <p>
            <label>
              <?php esc_html_e( 'reCAPTCHA version', 'polanger-admin-menu-manager' ); ?>
              <select name="pdt_multisite_network[defaults][pdt_login_page_settings][recaptcha_version]">
                <option value="v2" <?php selected( $settings['defaults']['pdt_login_page_settings']['recaptcha_version'], 'v2' ); ?>>v2</option>
                <option value="v3" <?php selected( $settings['defaults']['pdt_login_page_settings']['recaptcha_version'], 'v3' ); ?>>v3</option>
              </select>
            </label>
          </p>

          <h3><?php esc_html_e( 'Activity Log', 'polanger-admin-menu-manager' ); ?></h3>
          <p>
            <label><input type="checkbox" name="pdt_multisite_network[defaults][pdt_activity_log_settings][enabled]" value="1" <?php checked( ! empty( $settings['defaults']['pdt_activity_log_settings']['enabled'] ) ); ?> /> <?php esc_html_e( 'Enable activity logging by default', 'polanger-admin-menu-manager' ); ?></label>
          </p>
          <p>
            <label>
              <?php esc_html_e( 'Retention days', 'polanger-admin-menu-manager' ); ?>
              <select name="pdt_multisite_network[defaults][pdt_activity_log_settings][retention_days]">
                <option value="7" <?php selected( (int) $settings['defaults']['pdt_activity_log_settings']['retention_days'], 7 ); ?>>7</option>
                <option value="30" <?php selected( (int) $settings['defaults']['pdt_activity_log_settings']['retention_days'], 30 ); ?>>30</option>
                <option value="60" <?php selected( (int) $settings['defaults']['pdt_activity_log_settings']['retention_days'], 60 ); ?>>60</option>
                <option value="90" <?php selected( (int) $settings['defaults']['pdt_activity_log_settings']['retention_days'], 90 ); ?>>90</option>
              </select>
            </label>
          </p>
        </div>

        <div class="pdt-buttons">
          <p class="submit"><button type="submit" class="button button-primary"><?php esc_html_e( 'Save Network Settings', 'polanger-admin-menu-manager' ); ?></button></p>
        </div>
      </form>
    </div>
    <?php
  }

  /**
   * Render site page.
   *
   * @return void
   */
  public function render_site_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
      wp_die( esc_html__( 'Permission denied.', 'polanger-admin-menu-manager' ) );
    }

    $network_settings = $this->get_network_settings();
    $site_overrides = $this->get_site_override_settings();
    ?>
    <div id="pdt-wrap" class="pdt-ms-wrap">
      <div class="pdt-header">
        <h2 class="pdt-title"><?php esc_html_e( 'Multisite Site Control', 'polanger-admin-menu-manager' ); ?></h2>
        <p class="pdt-subtitle"><?php esc_html_e( 'Control whether this site uses network defaults or local overrides for each module.', 'polanger-admin-menu-manager' ); ?></p>
      </div>

      <?php
      // phpcs:ignore WordPress.Security.NonceVerification.Recommended
      if ( isset( $_GET['updated'] ) && '1' === sanitize_text_field( wp_unslash( $_GET['updated'] ) ) ) :
      ?>
        <div class="pdt-notice pdt-notice-success"><span class="dashicons dashicons-yes-alt"></span><?php esc_html_e( 'Site override settings saved.', 'polanger-admin-menu-manager' ); ?></div>
      <?php endif; ?>

      <?php if ( empty( $network_settings['enabled'] ) ) : ?>
        <div class="pdt-notice pdt-notice-success pdt-ms-warning"><span class="dashicons dashicons-warning"></span><?php esc_html_e( 'Network-wide control is currently disabled. Site settings run in local mode.', 'polanger-admin-menu-manager' ); ?></div>
      <?php endif; ?>

      <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="pdt-settings-form pdt-ms-form">
        <?php wp_nonce_field( 'pdt_multisite_site_settings' ); ?>
        <input type="hidden" name="action" value="pdt_multisite_save_site" />

        <div class="pdt-settings-section">
          <h2><?php esc_html_e( 'Override Controls', 'polanger-admin-menu-manager' ); ?></h2>
          <p class="description"><?php esc_html_e( 'Disable override to force this site to use network defaults for a module.', 'polanger-admin-menu-manager' ); ?></p>
          <div class="pdt-checkbox-grid">
            <?php foreach ( $this->managed_options as $option_name => $feature_key ) : ?>
              <?php
              $is_locked = ! empty( $network_settings['locks'][ $feature_key ] );
              $can_override = ! empty( $network_settings['enabled'] ) && ! $is_locked && ! empty( $network_settings['allow_site_override'] );
              ?>
              <label>
                <input
                  type="checkbox"
                  name="pdt_multisite_site[override][<?php echo esc_attr( $option_name ); ?>]"
                  value="1"
                  <?php checked( ! empty( $site_overrides[ $option_name ] ) ); ?>
                  <?php disabled( ! $can_override ); ?>
                />
                <?php echo esc_html( $this->get_feature_label( $feature_key ) ); ?>
                <?php if ( $is_locked ) : ?>
                  <span class="pdt-badge pdt-badge-new"><?php esc_html_e( 'Locked', 'polanger-admin-menu-manager' ); ?></span>
                <?php elseif ( ! empty( $site_overrides[ $option_name ] ) ) : ?>
                  <span class="pdt-badge pdt-badge-new"><?php esc_html_e( 'Override', 'polanger-admin-menu-manager' ); ?></span>
                <?php else : ?>
                  <span class="pdt-badge pdt-badge-new"><?php esc_html_e( 'Network', 'polanger-admin-menu-manager' ); ?></span>
                <?php endif; ?>
              </label>
            <?php endforeach; ?>
          </div>
        </div>

        <div class="pdt-buttons">
          <p class="submit"><button type="submit" class="button button-primary"><?php esc_html_e( 'Save Site Overrides', 'polanger-admin-menu-manager' ); ?></button></p>
        </div>
      </form>
    </div>
    <?php
  }

  /**
   * Sanitize network settings payload.
   *
   * @param array $input Raw input.
   * @return array
   */
  private function sanitize_network_settings( $input ) {
    $settings = $this->get_network_settings();

    $settings['enabled'] = ! empty( $input['enabled'] );
    $settings['allow_site_override'] = ! empty( $input['allow_site_override'] );

    foreach ( $settings['locks'] as $lock_key => $lock_value ) {
      $settings['locks'][ $lock_key ] = false;
    }

    if ( isset( $input['locks'] ) && is_array( $input['locks'] ) ) {
      $locks = $input['locks'];
      foreach ( $settings['locks'] as $lock_key => $lock_value ) {
        $settings['locks'][ $lock_key ] = ! empty( $locks[ $lock_key ] );
      }
    }

    if ( isset( $input['defaults'] ) && is_array( $input['defaults'] ) ) {
      $defaults = $input['defaults'];

      $settings['defaults']['pdt_general_settings']['log_visibility'] = isset( $defaults['pdt_general_settings']['log_visibility'] ) && in_array( $defaults['pdt_general_settings']['log_visibility'], array( 'all', 'super_admin' ), true )
        ? sanitize_text_field( $defaults['pdt_general_settings']['log_visibility'] )
        : 'all';

      $settings['defaults']['pdt_login_page_settings']['enable_recaptcha'] = ! empty( $defaults['pdt_login_page_settings']['enable_recaptcha'] );
      $settings['defaults']['pdt_login_page_settings']['recaptcha_version'] = isset( $defaults['pdt_login_page_settings']['recaptcha_version'] ) && in_array( $defaults['pdt_login_page_settings']['recaptcha_version'], array( 'v2', 'v3' ), true )
        ? sanitize_text_field( $defaults['pdt_login_page_settings']['recaptcha_version'] )
        : 'v2';

      $settings['defaults']['pdt_activity_log_settings']['enabled'] = ! empty( $defaults['pdt_activity_log_settings']['enabled'] );
      $retention_days = isset( $defaults['pdt_activity_log_settings']['retention_days'] ) ? absint( $defaults['pdt_activity_log_settings']['retention_days'] ) : 30;
      $settings['defaults']['pdt_activity_log_settings']['retention_days'] = in_array( $retention_days, array( 7, 30, 60, 90 ), true ) ? $retention_days : 30;
    }

    if ( isset( $input['capture_defaults'] ) && is_array( $input['capture_defaults'] ) ) {
      $capture_defaults = $input['capture_defaults'];
      foreach ( $this->managed_options as $option_name => $feature_key ) {
        if ( empty( $capture_defaults[ $option_name ] ) ) {
          continue;
        }

        $current_settings = get_option( $option_name, array() );
        $settings['defaults'][ $option_name ] = is_array( $current_settings ) ? $current_settings : array();
      }
    }

    return $settings;
  }

  /**
   * Get network settings with defaults.
   *
   * @return array
   */
  private function get_network_settings() {
    $settings = get_site_option( self::NETWORK_OPTION, array() );
    return array_replace_recursive( $this->get_network_settings_defaults(), is_array( $settings ) ? $settings : array() );
  }

  /**
   * Get default shape for network settings.
   *
   * @return array
   */
  private function get_network_settings_defaults() {
    return array(
      'enabled'             => false,
      'allow_site_override' => true,
      'locks'               => array(
        'menu_manager'      => false,
        'admin_bar'         => false,
        'general'           => false,
        'login'             => false,
        'activity_log'      => false,
        'dashboard_widgets' => false,
      ),
      'defaults'            => array(
        'pdt_settings'                  => array(),
        'pdt_admin_bar_settings'        => array(),
        'pdt_general_settings'      => array(
          'log_visibility' => 'all',
        ),
        'pdt_login_page_settings'   => array(
          'enable_recaptcha' => false,
          'recaptcha_version' => 'v2',
        ),
        'pdt_activity_log_settings' => array(
          'enabled'        => false,
          'retention_days' => 30,
        ),
        'pdt_dashboard_widgets_settings' => array(),
      ),
    );
  }

  /**
   * Get site override settings.
   *
   * @return array
   */
  private function get_site_override_settings() {
    $overrides = get_option( self::SITE_OVERRIDE_OPTION, array() );
    $defaults = array();
    foreach ( array_keys( $this->managed_options ) as $option_name ) {
      $defaults[ $option_name ] = false;
    }

    if ( ! is_array( $overrides ) ) {
      return $defaults;
    }

    foreach ( $defaults as $option_name => $value ) {
      $defaults[ $option_name ] = ! empty( $overrides[ $option_name ] );
    }

    return $defaults;
  }

  /**
   * Check site override flag for an option.
   *
   * @param string $option_name Option key.
   * @return bool
   */
  private function is_site_override_enabled( $option_name ) {
    $overrides = $this->get_site_override_settings();
    return ! empty( $overrides[ $option_name ] );
  }

  /**
   * Check whether addon is marked active network-wide.
   *
   * @return bool
   */
  private function is_network_active() {
    $network_active_addons = get_site_option( 'pdt_network_active_addons', array() );
    if ( ! is_array( $network_active_addons ) ) {
      return false;
    }

    return in_array( 'multisite-control', array_map( 'sanitize_key', $network_active_addons ), true );
  }

  /**
   * Update network-wide active addon state for this addon.
   *
   * @param array $input Sanitized-ish network form input.
   * @return void
   */
  private function update_network_active_state( $input ) {
    $network_active_addons = get_site_option( 'pdt_network_active_addons', array() );
    $network_active_addons = is_array( $network_active_addons ) ? array_map( 'sanitize_key', $network_active_addons ) : array();

    if ( ! empty( $input['network_active'] ) ) {
      $network_active_addons[] = 'multisite-control';
    } else {
      $network_active_addons = array_values( array_diff( $network_active_addons, array( 'multisite-control' ) ) );
    }

    update_site_option( 'pdt_network_active_addons', array_values( array_unique( $network_active_addons ) ) );
  }

  /**
   * Get locked feature key for the current admin page.
   *
   * @return string
   */
  private function get_locked_feature_for_current_page() {
    if ( is_network_admin() ) {
      return '';
    }

    $network_settings = $this->get_network_settings();
    if ( empty( $network_settings['enabled'] ) ) {
      return '';
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $tab = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '';

    $page_feature_map = array(
      'polanger-dashboard'          => 'menu_manager',
      'polanger-admin-bar'          => 'admin_bar',
      'polanger-login-page'         => 'login',
      'polanger-activity-log'       => 'activity_log',
      'polanger-dashboard-widgets'  => 'dashboard_widgets',
    );

    $feature = isset( $page_feature_map[ $page ] ) ? $page_feature_map[ $page ] : '';
    if ( 'polanger-settings' === $page ) {
      if ( 'activity-log' === $tab ) {
        $feature = 'activity_log';
      } elseif ( 'security' === $tab ) {
        $feature = 'login';
      } else {
        $feature = 'general';
      }
    }

    if ( empty( $feature ) || empty( $network_settings['locks'][ $feature ] ) ) {
      return '';
    }

    return $feature;
  }

  /**
   * Human label for feature key.
   *
   * @param string $feature_key Feature key.
   * @return string
   */
  private function get_feature_label( $feature_key ) {
    $labels = array(
      'menu_manager'      => __( 'Menu Manager', 'polanger-admin-menu-manager' ),
      'admin_bar'         => __( 'Admin Bar', 'polanger-admin-menu-manager' ),
      'general'           => __( 'General Settings', 'polanger-admin-menu-manager' ),
      'login'             => __( 'Login Security', 'polanger-admin-menu-manager' ),
      'activity_log'      => __( 'Activity Log', 'polanger-admin-menu-manager' ),
      'dashboard_widgets' => __( 'Dashboard Center', 'polanger-admin-menu-manager' ),
    );

    return isset( $labels[ $feature_key ] ) ? $labels[ $feature_key ] : $feature_key;
  }
}
