<?php
/**
 * Main bootstrap class for Maintenance Center.
 *
 * @package Polanger_Maintenance_Center
 */

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

require_once POLANGER_MAINTENANCE_CENTER_DIR . 'includes/class-polanger-maintenance-settings.php';
require_once POLANGER_MAINTENANCE_CENTER_DIR . 'includes/class-polanger-maintenance-runtime.php';

class Polanger_Maintenance_Center {

  /**
   * Singleton instance.
   *
   * @var Polanger_Maintenance_Center|null
   */
  private static $instance = null;

  /**
   * Get singleton.
   *
   * @return Polanger_Maintenance_Center
   */
  public static function instance() {
    if ( null === self::$instance ) {
      self::$instance = new self();
    }

    return self::$instance;
  }

  /**
   * Activation callback.
   *
   * @return void
   */
  public static function activate() {
    Polanger_Maintenance_Settings::activate();
  }

  /**
   * Boot plugin services.
   *
   * @return void
   */
  public function boot() {
    add_filter( 'pdt_register_addons', array( $this, 'register_addon_card' ) );

    add_action(
      'polanger_init',
      static function( $loader ) {
        if ( ! is_object( $loader ) || ! method_exists( $loader, 'register_module' ) ) {
          return;
        }

        $loader->register_module(
          array(
            'name'        => 'Polanger Maintenance Center',
            'slug'        => 'maintenance-center',
            'version'     => POLANGER_MAINTENANCE_CENTER_VERSION,
            'requires'    => '1.5.3',
            'description' => 'A focused maintenance workflow with simple scheduling, bypass control, branded pages, and deployment locks.',
            'page_slug'   => 'polanger-settings&tab=maintenance',
            'is_core'     => false,
          )
        );
      }
    );

    if ( ! $this->is_polanger_core_available() ) {
      return;
    }

    Polanger_Maintenance_Settings::instance()->register_hooks();
    Polanger_Maintenance_Runtime::instance()->register_hooks();
  }

  /**
   * Register addon card on the Polanger Addons screen.
   *
   * @param array $addons Existing addon registry.
   * @return array
   */
  public function register_addon_card( $addons ) {
    if ( ! is_array( $addons ) ) {
      $addons = array();
    }

    if ( ! isset( $addons['maintenance-center'] ) ) {
      $addons['maintenance-center'] = array(
        'title'       => __( 'Maintenance Center', 'polanger-admin-menu-manager' ),
        'description' => __( 'Manage maintenance windows, bypass access, branded holding pages, and deployment-focused frontend locks from one workflow.', 'polanger-admin-menu-manager' ),
        'status'      => 'active',
        'slug'        => 'polanger-settings&tab=maintenance',
        'is_core'     => false,
      );
    }

    return $addons;
  }

  /**
   * Whether Polanger core helpers are available.
   *
   * @return bool
   */
  private function is_polanger_core_available() {
    return function_exists( 'pdt_get_user_access_level' ) && function_exists( 'pdt_is_addon_active' );
  }

  /**
   * Legacy compatibility bridge for old standalone deactivation flows.
   *
   * @return void
   */
  public function maybe_handle_suite_deactivation() {
    if ( ! is_admin() || ( ! current_user_can( 'activate_plugins' ) && ! current_user_can( 'manage_network_plugins' ) ) ) {
      return;
    }

    if ( empty( $_POST['pdt_addons_toggle_submit'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
      return;
    }

    if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'pdt_toggle_addon' ) ) {
      return;
    }

    $addon_slug = isset( $_POST['addon_slug'] ) ? sanitize_key( wp_unslash( $_POST['addon_slug'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
    $action     = isset( $_POST['toggle_action'] ) ? sanitize_key( wp_unslash( $_POST['toggle_action'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing

    if ( POLANGER_MAINTENANCE_CENTER_ADDON_SLUG !== $addon_slug || 'deactivate' !== $action ) {
      return;
    }

    if ( ! function_exists( 'deactivate_plugins' ) ) {
      require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $is_network_active = function_exists( 'is_plugin_active_for_network' ) && is_plugin_active_for_network( plugin_basename( POLANGER_MAINTENANCE_CENTER_FILE ) );

    if ( $is_network_active && ! current_user_can( 'manage_network_plugins' ) ) {
      return;
    }

    polanger_maintenance_center_sync_suite_addon_state( false );
    deactivate_plugins( plugin_basename( POLANGER_MAINTENANCE_CENTER_FILE ), true, $is_network_active );

    wp_safe_redirect(
      add_query_arg(
        array(
          'page'   => 'polanger-addons',
          'status' => 'addon-deactivated',
          'addon'  => POLANGER_MAINTENANCE_CENTER_ADDON_SLUG,
        ),
        admin_url( 'admin.php' )
      )
    );
    exit;
  }
}
