<?php
/**
 * WooCommerce Cleanup module.
 *
 * @package Kramar
 * @since   1.0.0
 */

declare( strict_types=1 );

namespace Kramar\Modules\Performance;

// Prevent direct access.
defined( 'ABSPATH' ) || exit;

/**
 * WooCommerce Cleanup module.
 *
 * @since 1.0.0
 */
final class WC_Cleanup extends \Kramar\Module {

	/**
	 * {@inheritDoc}
	 */
	public function get_slug(): string {
		return 'wc-cleanup';
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_category(): string {
		return 'performance';
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_name(): string {
		return __( 'WooCommerce Cleanup', 'kramar' );
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_description(): string {
		return __( 'Strip WooCommerce admin bloat, promotional features, dashboard widgets, and background tasks. All settings are safe for production use.', 'kramar' );
	}

	/**
	 * {@inheritDoc}
	 */
	public function get_default_settings(): array {
		return [
			'enabled'                   => false,
			// Admin bloat (all default ON — safe, no side effects).
			'strip_admin_features'      => true,
			'disable_marketplace'       => true,
			'disable_setup_wizard'      => true,
			'disable_payment_offers'    => true,
			'disable_marketing_menu'    => true,
			'disable_dashboard_widgets' => true,
			'disable_admin_bar_bloat'   => true,
			'disable_usage_tracking'    => true,
			'disable_remote_logging'    => true,
			'disable_maxmind'           => true,
			// Frontend performance (default OFF — theme-dependent).
			'disable_wc_widgets'        => false,
			'disable_photoswipe'        => false,
			'disable_flexslider'        => false,
			'disable_zoom'              => false,
			'disable_geolocation'       => false,
			// API (default OFF — dangerous).
			'disable_rest_api'          => false,
		];
	}

	/**
	 * {@inheritDoc}
	 */
	public function sanitize_settings( array $input ): array {
		return [
			'enabled'                   => ! empty( $input['enabled'] ),
			'strip_admin_features'      => ! empty( $input['strip_admin_features'] ),
			'disable_marketplace'       => ! empty( $input['disable_marketplace'] ),
			'disable_setup_wizard'      => ! empty( $input['disable_setup_wizard'] ),
			'disable_payment_offers'    => ! empty( $input['disable_payment_offers'] ),
			'disable_marketing_menu'    => ! empty( $input['disable_marketing_menu'] ),
			'disable_dashboard_widgets' => ! empty( $input['disable_dashboard_widgets'] ),
			'disable_admin_bar_bloat'   => ! empty( $input['disable_admin_bar_bloat'] ),
			'disable_usage_tracking'    => ! empty( $input['disable_usage_tracking'] ),
			'disable_remote_logging'    => ! empty( $input['disable_remote_logging'] ),
			'disable_maxmind'           => ! empty( $input['disable_maxmind'] ),
			'disable_wc_widgets'        => ! empty( $input['disable_wc_widgets'] ),
			'disable_photoswipe'        => ! empty( $input['disable_photoswipe'] ),
			'disable_flexslider'        => ! empty( $input['disable_flexslider'] ),
			'disable_zoom'              => ! empty( $input['disable_zoom'] ),
			'disable_geolocation'       => ! empty( $input['disable_geolocation'] ),
			'disable_rest_api'          => ! empty( $input['disable_rest_api'] ),
		];
	}

	/**
	 * {@inheritDoc}
	 */
	protected function run(): void {
		$this->run_admin_cleanup();
		$this->run_frontend_cleanup();
		$this->run_api_cleanup();
	}

	/**
	 * Register admin-side cleanup hooks.
	 *
	 * @since 1.0.0
	 */
	private function run_admin_cleanup(): void {
		if ( ! is_admin() ) {
			return;
		}

		if ( $this->get_setting( 'strip_admin_features' ) ) {
			// Emptying woocommerce_admin_features removes EVERY WC Admin feature,
			// not just the promotional ones — including "analytics", which left
			// WooCommerce → Analytics dead with a hard "Sorry, you are not
			// allowed to access this page" for a setting documented as safe and
			// shipped on by default. Strip the marketing/onboarding surfaces and
			// keep the features a shop actually runs on.
			add_filter(
				'woocommerce_admin_features',
				static function ( $features ) {
					$remove = [
						'onboarding',
						'onboarding-tasks',
						'marketing',
						'remote-inbox-notifications',
						'remote-free-extensions',
						'wc-pay-welcome-page',
						'payment-gateway-suggestions',
						'product-recommendations',
						'shipping-label-banner',
						'shipping-smart-defaults',
						'subscriptions',
						'store-alerts',
						'mobile-app-banner',
					];

					/**
					 * WC Admin features Kramar removes as "admin bloat".
					 *
					 * @since 1.0.2
					 *
					 * @param string[] $remove Feature slugs to strip.
					 */
					$remove = (array) apply_filters( 'kramar_stripped_admin_features', $remove );

					return array_values( array_diff( (array) $features, $remove ) );
				},
				999
			);
		}

		if ( $this->get_setting( 'disable_marketplace' ) ) {
			add_filter( 'woocommerce_allow_marketplace_suggestions', '__return_false' );
			add_filter( 'option_woocommerce_show_marketplace_suggestions', fn() => 'no' );
			add_filter( 'woocommerce_show_addons_page', '__return_false' );
		}

		if ( $this->get_setting( 'disable_setup_wizard' ) ) {
			add_filter( 'option_woocommerce_task_list_hidden', fn() => 'yes' );
			add_filter( 'option_woocommerce_task_list_complete', fn() => 'yes' );
			add_filter( 'option_woocommerce_extended_task_list_hidden', fn() => 'yes' );
		}

		if ( $this->get_setting( 'disable_payment_offers' ) ) {
			add_filter( 'woocommerce_admin_payment_gateway_suggestion_specs', '__return_empty_array' );
		}

		if ( $this->get_setting( 'disable_marketing_menu' ) ) {
			add_filter( 'woocommerce_marketing_menu_items', '__return_empty_array' );
			add_action( 'admin_menu', [ $this, 'remove_marketing_menu' ], 99 );
		}

		if ( $this->get_setting( 'disable_dashboard_widgets' ) ) {
			add_action( 'wp_dashboard_setup', [ $this, 'remove_dashboard_widgets' ], 99 );
		}

		if ( $this->get_setting( 'disable_admin_bar_bloat' ) ) {
			add_filter( 'woocommerce_show_admin_bar_visit_store', '__return_false' );
		}

		if ( $this->get_setting( 'disable_usage_tracking' ) ) {
			add_filter( 'option_woocommerce_allow_tracking', fn() => 'no' );
		}

		if ( $this->get_setting( 'disable_remote_logging' ) ) {
			add_filter( 'woocommerce_register_log_handlers', [ $this, 'remove_remote_log_handler' ] );
		}

		if ( $this->get_setting( 'disable_maxmind' ) ) {
			add_filter( 'woocommerce_maxmind_geolocation_update_database_periodically', '__return_false' );
		}
	}

	/**
	 * Register frontend cleanup hooks.
	 *
	 * @since 1.0.0
	 */
	private function run_frontend_cleanup(): void {
		if ( is_admin() ) {
			return;
		}

		if ( $this->get_setting( 'disable_wc_widgets' ) ) {
			add_action( 'widgets_init', [ $this, 'unregister_widgets' ], 11 );
		}

		add_action( 'wp_enqueue_scripts', [ $this, 'dequeue_frontend_assets' ], 99 );
	}

	/**
	 * Register REST API cleanup hooks.
	 *
	 * @since 1.0.0
	 */
	private function run_api_cleanup(): void {
		if ( $this->get_setting( 'disable_rest_api' ) ) {
			add_filter( 'woocommerce_rest_api_get_rest_namespaces', '__return_empty_array' );
		}
	}

	/**
	 * Remove the WooCommerce marketing menu item.
	 *
	 * @since 1.0.0
	 */
	public function remove_marketing_menu(): void {
		remove_submenu_page( 'woocommerce-marketing', 'woocommerce-marketing' );
	}

	/**
	 * Remove WooCommerce dashboard widgets.
	 *
	 * @since 1.0.0
	 */
	public function remove_dashboard_widgets(): void {
		remove_meta_box( 'woocommerce_dashboard_status', 'dashboard', 'normal' );
		remove_meta_box( 'woocommerce_dashboard_recent_reviews', 'dashboard', 'normal' );
		remove_meta_box( 'wc_admin_dashboard_setup', 'dashboard', 'normal' );
	}

	/**
	 * Remove the WooCommerce remote logger from the log handlers list.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $handlers Log handlers value from filter.
	 * @return mixed Original value if not an array, or filtered array.
	 */
	public function remove_remote_log_handler( mixed $handlers ): mixed {
		if ( ! is_array( $handlers ) ) {
			return $handlers;
		}

		return array_filter(
			$handlers,
			function ( $handler ): bool {
				if ( is_object( $handler ) ) {
					return ! str_contains( get_class( $handler ), 'RemoteLogger' );
				}
				if ( is_array( $handler ) ) {
					$class = is_object( $handler[0] ?? null ) ? get_class( $handler[0] ) : ( $handler[0] ?? '' );
					return ! str_contains( (string) $class, 'RemoteLogger' );
				}
				return ! str_contains( (string) $handler, 'RemoteLogger' );
			}
		);
	}

	/**
	 * Unregister WooCommerce legacy widgets.
	 *
	 * @since 1.0.0
	 */
	public function unregister_widgets(): void {
		$widgets = [
			'WC_Widget_Cart',
			'WC_Widget_Layered_Nav',
			'WC_Widget_Layered_Nav_Filters',
			'WC_Widget_Price_Filter',
			'WC_Widget_Product_Categories',
			'WC_Widget_Product_Search',
			'WC_Widget_Product_Tag_Cloud',
			'WC_Widget_Products',
			'WC_Widget_Recently_Viewed',
			'WC_Widget_Top_Rated_Products',
			'WC_Widget_Recent_Reviews',
			'WC_Widget_Rating_Filter',
		];

		foreach ( $widgets as $widget ) {
			unregister_widget( $widget );
		}
	}

	/**
	 * Dequeue frontend assets based on settings.
	 *
	 * @since 1.0.0
	 */
	public function dequeue_frontend_assets(): void {
		if ( $this->get_setting( 'disable_photoswipe' ) ) {
			// Both the current handles and the legacy aliases. WooCommerce prints
			// the scripts as wc-photoswipe / wc-photoswipe-ui-default and keeps the
			// bare names only as back-compat aliases, so dequeuing those alone was a
			// no-op: the stylesheets went (their handles really are bare) and the
			// JS stayed, leaving an unstyled lightbox rather than no lightbox. The
			// flexslider and zoom toggles beside this one already list both.
			wp_dequeue_script( 'wc-photoswipe' );
			wp_dequeue_script( 'wc-photoswipe-ui-default' );
			wp_dequeue_script( 'photoswipe' );
			wp_dequeue_script( 'photoswipe-ui-default' );
			wp_dequeue_style( 'wc-photoswipe' );
			wp_dequeue_style( 'wc-photoswipe-default-skin' );
			wp_dequeue_style( 'photoswipe' );
			wp_dequeue_style( 'photoswipe-default-skin' );
		}

		if ( $this->get_setting( 'disable_flexslider' ) ) {
			wp_dequeue_script( 'flexslider' );
			wp_dequeue_script( 'wc-flexslider' );
		}

		if ( $this->get_setting( 'disable_zoom' ) ) {
			wp_dequeue_script( 'zoom' );
			wp_dequeue_script( 'wc-zoom' );
		}

		if ( $this->get_setting( 'disable_geolocation' ) ) {
			wp_dequeue_script( 'wc-geolocation' );
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public function render_extra_settings( string $option_name ): void {
		$settings = [
			'strip_admin_features'      => $this->get_setting( 'strip_admin_features' ),
			'disable_marketplace'       => $this->get_setting( 'disable_marketplace' ),
			'disable_setup_wizard'      => $this->get_setting( 'disable_setup_wizard' ),
			'disable_payment_offers'    => $this->get_setting( 'disable_payment_offers' ),
			'disable_marketing_menu'    => $this->get_setting( 'disable_marketing_menu' ),
			'disable_dashboard_widgets' => $this->get_setting( 'disable_dashboard_widgets' ),
			'disable_admin_bar_bloat'   => $this->get_setting( 'disable_admin_bar_bloat' ),
			'disable_usage_tracking'    => $this->get_setting( 'disable_usage_tracking' ),
			'disable_remote_logging'    => $this->get_setting( 'disable_remote_logging' ),
			'disable_maxmind'           => $this->get_setting( 'disable_maxmind' ),
			'disable_wc_widgets'        => $this->get_setting( 'disable_wc_widgets' ),
			'disable_photoswipe'        => $this->get_setting( 'disable_photoswipe' ),
			'disable_flexslider'        => $this->get_setting( 'disable_flexslider' ),
			'disable_zoom'              => $this->get_setting( 'disable_zoom' ),
			'disable_geolocation'       => $this->get_setting( 'disable_geolocation' ),
			'disable_rest_api'          => $this->get_setting( 'disable_rest_api' ),
		];
		$slug     = $this->get_slug();
		$cat      = $this->get_category();
		?>
		<div class="kramar-module__extra">
			<div class="kramar-settings-stack">

				<p><strong><?php esc_html_e( 'Admin Cleanup', 'kramar' ); ?></strong></p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][strip_admin_features]"
							value="1"
							<?php checked( $settings['strip_admin_features'] ); ?>
						/>
						<?php esc_html_e( 'Strip all WC Admin features', 'kramar' ); ?>
					</label>
					<span class="description"><?php esc_html_e( 'Applies the woocommerce_admin_features filter to disable ~20 features at once.', 'kramar' ); ?></span>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_marketplace]"
							value="1"
							<?php checked( $settings['disable_marketplace'] ); ?>
						/>
						<?php esc_html_e( 'Disable marketplace suggestions', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_setup_wizard]"
							value="1"
							<?php checked( $settings['disable_setup_wizard'] ); ?>
						/>
						<?php esc_html_e( 'Disable setup wizard &amp; task list', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_payment_offers]"
							value="1"
							<?php checked( $settings['disable_payment_offers'] ); ?>
						/>
						<?php esc_html_e( 'Disable payment gateway suggestions', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_marketing_menu]"
							value="1"
							<?php checked( $settings['disable_marketing_menu'] ); ?>
						/>
						<?php esc_html_e( 'Disable Marketing menu', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_dashboard_widgets]"
							value="1"
							<?php checked( $settings['disable_dashboard_widgets'] ); ?>
						/>
						<?php esc_html_e( 'Disable WooCommerce dashboard widgets', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_admin_bar_bloat]"
							value="1"
							<?php checked( $settings['disable_admin_bar_bloat'] ); ?>
						/>
						<?php esc_html_e( 'Hide "Visit Store" from admin bar', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_usage_tracking]"
							value="1"
							<?php checked( $settings['disable_usage_tracking'] ); ?>
						/>
						<?php esc_html_e( 'Disable usage tracking', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_remote_logging]"
							value="1"
							<?php checked( $settings['disable_remote_logging'] ); ?>
						/>
						<?php esc_html_e( 'Disable remote error logging', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_maxmind]"
							value="1"
							<?php checked( $settings['disable_maxmind'] ); ?>
						/>
						<?php esc_html_e( 'Disable MaxMind geolocation database updates', 'kramar' ); ?>
					</label>
				</p>

				<p><strong><?php esc_html_e( 'Frontend Performance', 'kramar' ); ?></strong></p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_wc_widgets]"
							value="1"
							<?php checked( $settings['disable_wc_widgets'] ); ?>
						/>
						<?php esc_html_e( 'Unregister WooCommerce legacy widgets', 'kramar' ); ?>
					</label>
					<span class="description"><?php esc_html_e( 'Only disable if your theme does not use the WooCommerce widget sidebar.', 'kramar' ); ?></span>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_photoswipe]"
							value="1"
							<?php checked( $settings['disable_photoswipe'] ); ?>
						/>
						<?php esc_html_e( 'Dequeue PhotoSwipe (product lightbox)', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_flexslider]"
							value="1"
							<?php checked( $settings['disable_flexslider'] ); ?>
						/>
						<?php esc_html_e( 'Dequeue FlexSlider (product gallery)', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_zoom]"
							value="1"
							<?php checked( $settings['disable_zoom'] ); ?>
						/>
						<?php esc_html_e( 'Dequeue Zoom (product image zoom)', 'kramar' ); ?>
					</label>
				</p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_geolocation]"
							value="1"
							<?php checked( $settings['disable_geolocation'] ); ?>
						/>
						<?php esc_html_e( 'Dequeue geolocation script', 'kramar' ); ?>
					</label>
				</p>

				<p><strong><?php esc_html_e( 'Order Storage', 'kramar' ); ?></strong></p>

				<?php
				$hpos_enabled = class_exists( \Automattic\WooCommerce\Utilities\OrderUtil::class )
					&& \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled();
				$features_url = admin_url( 'admin.php?page=wc-settings&tab=advanced&section=features' );
				?>
				<p>
					<?php if ( $hpos_enabled ) : ?>
						<span style="color:#00a32a;">&#10003;</span>
						<strong><?php esc_html_e( 'HPOS active', 'kramar' ); ?></strong>
						— <?php esc_html_e( 'Orders use high-performance custom tables. This is the fastest storage mode.', 'kramar' ); ?>
					<?php else : ?>
						<span style="color:#dba617;">&#9888;</span>
						<strong><?php esc_html_e( 'HPOS not active', 'kramar' ); ?></strong>
						— <?php
						printf(
							/* translators: %s: link to WooCommerce features settings */
							esc_html__( 'Orders still use the slower post meta table. Enable HPOS in %s for better performance.', 'kramar' ),
							'<a href="' . esc_url( $features_url ) . '">' . esc_html__( 'WooCommerce → Settings → Advanced → Features', 'kramar' ) . '</a>'
						);
						?>
					<?php endif; ?>
				</p>

				<p><strong><?php esc_html_e( 'Advanced', 'kramar' ); ?></strong></p>

				<p>
					<label>
						<input
							type="checkbox"
							name="<?php echo esc_attr( $option_name ); ?>[<?php echo esc_attr( $cat ); ?>][<?php echo esc_attr( $slug ); ?>][disable_rest_api]"
							value="1"
							<?php checked( $settings['disable_rest_api'] ); ?>
						/>
						<?php esc_html_e( 'Disable WooCommerce REST API namespaces', 'kramar' ); ?>
					</label>
					<span class="description" style="color:#d63638;"><strong><?php esc_html_e( 'Warning: Breaks headless stores and Block-based checkout on some configurations.', 'kramar' ); ?></strong></span>
				</p>

			</div>
		</div>
		<?php
	}

	/**
	 * Read a boolean setting for this module.
	 *
	 * @since 1.0.0
	 *
	 * @param string $key Setting key.
	 * @return bool Setting value.
	 */
	private function get_setting( string $key ): bool {
		return (bool) $this->plugin->get_setting( $this->get_category(), $this->get_slug(), $key );
	}
}
