<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class UPSD_Plugin {

	private static $instance = null;
	private $option_key      = 'upsd_settings';

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	public static function activate() {
		$current = get_option( 'upsd_settings', array() );
		update_option( 'upsd_settings', wp_parse_args( is_array( $current ) ? $current : array(), self::get_defaults() ) );
	}

	private static function get_defaults() {
		return array(
			'disable_emojis'          => 0,
			'disable_embeds'          => 0,
			'remove_dashicons_guests' => 0,
			'disable_xmlrpc'          => 0,
			'limit_revisions'         => 0,
			'revisions_to_keep'       => 5,
			'heartbeat_mode'          => 'default',
		);
	}

	private function __construct() {
		add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );

		add_action( 'admin_post_upsd_apply_recommended', array( $this, 'handle_apply_recommended' ) );
		add_action( 'admin_post_upsd_cleanup_revisions', array( $this, 'cleanup_revisions' ) );
		add_action( 'admin_post_upsd_cleanup_spam', array( $this, 'cleanup_spam' ) );
		add_action( 'admin_post_upsd_cleanup_transients', array( $this, 'cleanup_transients' ) );

		add_action( 'init', array( $this, 'apply_settings' ), 1 );

		add_filter( 'xmlrpc_enabled', array( $this, 'filter_xmlrpc' ) );
		add_filter( 'wp_revisions_to_keep', array( $this, 'filter_revisions' ), 10, 2 );
		add_filter( 'heartbeat_settings', array( $this, 'filter_heartbeat_settings' ) );
	}

	private function get_settings() {
		$saved = get_option( $this->option_key, array() );

		return wp_parse_args( is_array( $saved ) ? $saved : array(), self::get_defaults() );
	}

	private function require_manage_options() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to do that.', 'dirtytackle-performance-cleanup' ) );
		}
	}

	private function redirect_with_notice( $notice_key ) {
		wp_safe_redirect(
			add_query_arg(
				array(
					'page'        => 'dirtytackle-performance-cleanup',
					'upsd_notice' => rawurlencode( $notice_key ),
				),
				admin_url( 'options-general.php' )
			)
		);
		exit;
	}

	private function clear_status_cache() {
		delete_transient( 'upsd_status_counts' );
	}

	public function add_settings_page() {
		add_options_page(
			__( 'DirtyTackle Performance Cleanup', 'dirtytackle-performance-cleanup' ),
			__( 'DirtyTackle Performance Cleanup', 'dirtytackle-performance-cleanup' ),
			'manage_options',
			'dirtytackle-performance-cleanup',
			array( $this, 'render_settings_page' )
		);
	}

	public function register_settings() {
		register_setting(
			'upsd_settings_group',
			$this->option_key,
			array( $this, 'sanitize_settings' )
		);
	}

	public function enqueue_admin_assets( $hook ) {
		if ( 'settings_page_dirtytackle-performance-cleanup' !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'upsd-admin',
			UPSD_PLUGIN_URL . 'assets/admin.css',
			array(),
			UPSD_VERSION
		);

		wp_enqueue_script(
			'upsd-admin',
			UPSD_PLUGIN_URL . 'assets/admin.js',
			array(),
			UPSD_VERSION,
			true
		);

		wp_localize_script(
			'upsd-admin',
			'upsdAdmin',
			array(
				'confirmCleanup' => __( 'Are you sure? This cleanup action cannot be undone.', 'dirtytackle-performance-cleanup' ),
			)
		);
	}

	public function handle_apply_recommended() {
		$this->require_manage_options();
		check_admin_referer( 'upsd_apply_recommended' );

		$settings                           = self::get_defaults();
		$settings['disable_emojis']         = 1;
		$settings['disable_embeds']         = 1;
		$settings['remove_dashicons_guests'] = 1;
		$settings['disable_xmlrpc']         = 1;
		$settings['limit_revisions']        = 1;
		$settings['revisions_to_keep']      = 5;
		$settings['heartbeat_mode']         = 'limit';

		update_option( $this->option_key, $settings );
		$this->clear_status_cache();

		$this->redirect_with_notice( 'recommended' );
	}

	public function cleanup_revisions() {
		$this->require_manage_options();
		check_admin_referer( 'upsd_cleanup_revisions' );

		$deleted = $this->delete_revisions_batch( 100 );
		$this->clear_status_cache();

		if ( false === $deleted ) {
			$this->redirect_with_notice( 'revisions_error' );
		}

		$this->redirect_with_notice( 'revisions_' . absint( $deleted ) );
	}

	public function cleanup_spam() {
		$this->require_manage_options();
		check_admin_referer( 'upsd_cleanup_spam' );

		$deleted = $this->delete_spam_comments_batch( 100 );
		$this->clear_status_cache();

		if ( false === $deleted ) {
			$this->redirect_with_notice( 'spam_error' );
		}

		$this->redirect_with_notice( 'spam_' . absint( $deleted ) );
	}

	public function cleanup_transients() {
		$this->require_manage_options();
		check_admin_referer( 'upsd_cleanup_transients' );

		$deleted = $this->delete_transients_batch( 400 );
		$this->clear_status_cache();

		if ( false === $deleted ) {
			$this->redirect_with_notice( 'transients_error' );
		}

		$this->redirect_with_notice( 'transients_' . absint( $deleted ) );
	}

	private function delete_revisions_batch( $limit ) {
		$revision_ids = get_posts(
			array(
				'post_type'              => 'revision',
				'post_status'            => 'inherit',
				'fields'                 => 'ids',
				'posts_per_page'         => absint( $limit ),
				'orderby'                => 'ID',
				'order'                  => 'ASC',
				'no_found_rows'          => true,
				'suppress_filters'       => true,
				'update_post_meta_cache' => false,
				'update_post_term_cache' => false,
			)
		);

		if ( ! is_array( $revision_ids ) ) {
			return false;
		}

		$deleted = 0;

		foreach ( $revision_ids as $revision_id ) {
			if ( wp_delete_post_revision( $revision_id ) ) {
				++$deleted;
			}
		}

		return $deleted;
	}

	private function delete_spam_comments_batch( $limit ) {
		$comment_ids = get_comments(
			array(
				'status'  => 'spam',
				'fields'  => 'ids',
				'number'  => absint( $limit ),
				'orderby' => 'comment_ID',
				'order'   => 'ASC',
			)
		);

		if ( ! is_array( $comment_ids ) ) {
			return false;
		}

		$deleted = 0;

		foreach ( $comment_ids as $comment_id ) {
			if ( wp_delete_comment( $comment_id, true ) ) {
				++$deleted;
			}
		}

		return $deleted;
	}

	private function delete_transients_batch( $limit ) {
		global $wpdb;

		$option_names = $wpdb->get_col( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			$wpdb->prepare(
				"SELECT option_name
				FROM {$wpdb->options}
				WHERE option_name LIKE %s
					OR option_name LIKE %s
					OR option_name LIKE %s
					OR option_name LIKE %s
				ORDER BY option_name ASC
				LIMIT %d",
				'_transient_%',
				'_transient_timeout_%',
				'_site_transient_%',
				'_site_transient_timeout_%',
				absint( $limit )
			)
		);

		if ( null === $option_names ) {
			return false;
		}

		$transient_keys = array();
		$site_keys      = array();

		foreach ( $option_names as $option_name ) {
			if ( 0 === strpos( $option_name, '_site_transient_timeout_' ) ) {
				$site_keys[] = substr( $option_name, 24 );
			} elseif ( 0 === strpos( $option_name, '_site_transient_' ) ) {
				$site_keys[] = substr( $option_name, 16 );
			} elseif ( 0 === strpos( $option_name, '_transient_timeout_' ) ) {
				$transient_keys[] = substr( $option_name, 19 );
			} elseif ( 0 === strpos( $option_name, '_transient_' ) ) {
				$transient_keys[] = substr( $option_name, 11 );
			}
		}

		$transient_keys = array_filter( array_unique( $transient_keys ) );
		$site_keys      = array_filter( array_unique( $site_keys ) );
		$deleted        = 0;

		foreach ( $transient_keys as $transient_key ) {
			if ( delete_transient( $transient_key ) ) {
				++$deleted;
			}
		}

		foreach ( $site_keys as $site_key ) {
			if ( delete_site_transient( $site_key ) ) {
				++$deleted;
			}
		}

		return $deleted;
	}

	public function sanitize_settings( $input ) {
		$sanitized = self::get_defaults();

		$sanitized['disable_emojis']          = empty( $input['disable_emojis'] ) ? 0 : 1;
		$sanitized['disable_embeds']          = empty( $input['disable_embeds'] ) ? 0 : 1;
		$sanitized['remove_dashicons_guests'] = empty( $input['remove_dashicons_guests'] ) ? 0 : 1;
		$sanitized['disable_xmlrpc']          = empty( $input['disable_xmlrpc'] ) ? 0 : 1;
		$sanitized['limit_revisions']         = empty( $input['limit_revisions'] ) ? 0 : 1;
		$sanitized['revisions_to_keep']       = max( 1, absint( isset( $input['revisions_to_keep'] ) ? $input['revisions_to_keep'] : 5 ) );

		$allowed_heartbeat              = array( 'default', 'limit', 'disable_frontend' );
		$heartbeat                      = isset( $input['heartbeat_mode'] ) ? sanitize_text_field( $input['heartbeat_mode'] ) : 'default';
		$sanitized['heartbeat_mode']    = in_array( $heartbeat, $allowed_heartbeat, true ) ? $heartbeat : 'default';

		add_settings_error(
			'upsd_messages',
			'upsd_settings_saved',
			__( 'Settings saved.', 'dirtytackle-performance-cleanup' ),
			'updated'
		);

		return $sanitized;
	}

	public function apply_settings() {
		$settings = $this->get_settings();

		if ( ! empty( $settings['remove_dashicons_guests'] ) && ! is_admin() && ! is_user_logged_in() ) {
			add_action( 'wp_enqueue_scripts', array( $this, 'maybe_remove_dashicons' ), 100 );
		}

		if ( ! empty( $settings['disable_emojis'] ) ) {
			$this->disable_emojis();
		}

		if ( ! empty( $settings['disable_embeds'] ) ) {
			$this->disable_embeds();
		}

		if ( ! is_admin() && 'disable_frontend' === $settings['heartbeat_mode'] ) {
			add_action( 'wp_enqueue_scripts', array( $this, 'disable_frontend_heartbeat' ), 100 );
		}
	}

	public function maybe_remove_dashicons() {
		wp_dequeue_style( 'dashicons' );
		wp_deregister_style( 'dashicons' );
	}

	public function disable_frontend_heartbeat() {
		wp_dequeue_script( 'heartbeat' );
		wp_deregister_script( 'heartbeat' );
	}

	private function disable_emojis() {
		remove_action( 'admin_print_styles', 'print_emoji_styles' );
		remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
		remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
		remove_action( 'wp_print_styles', 'print_emoji_styles' );
		remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
		remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
		remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
		add_filter( 'emoji_svg_url', '__return_false' );
		add_filter( 'tiny_mce_plugins', array( $this, 'filter_tinymce_plugins' ) );
	}

	public function filter_tinymce_plugins( $plugins ) {
		if ( ! is_array( $plugins ) ) {
			return array();
		}

		return array_diff( $plugins, array( 'wpemoji' ) );
	}

	private function disable_embeds() {
		remove_action( 'rest_api_init', 'wp_oembed_register_route' );
		remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
		remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
		remove_action( 'wp_head', 'wp_oembed_add_host_js' );
		remove_filter( 'pre_oembed_result', 'wp_filter_pre_oembed_result', 10 );
		add_filter( 'embed_oembed_discover', '__return_false' );
		add_action( 'wp_enqueue_scripts', array( $this, 'dequeue_embed_script' ), 100 );
	}

	public function dequeue_embed_script() {
		wp_dequeue_script( 'wp-embed' );
		wp_deregister_script( 'wp-embed' );
	}

	public function filter_xmlrpc( $enabled ) {
		$settings = $this->get_settings();

		return ! empty( $settings['disable_xmlrpc'] ) ? false : $enabled;
	}

	public function filter_revisions( $num, $post ) {
		$settings = $this->get_settings();

		if ( empty( $settings['limit_revisions'] ) ) {
			return $num;
		}

		return max( 1, absint( $settings['revisions_to_keep'] ) );
	}

	public function filter_heartbeat_settings( $settings ) {
		$plugin_settings = $this->get_settings();

		if ( 'limit' === $plugin_settings['heartbeat_mode'] ) {
			$settings['interval'] = 60;
		}

		return $settings;
	}

	private function get_status_counts() {
		$cached = get_transient( 'upsd_status_counts' );

		if ( is_array( $cached ) ) {
			return $cached;
		}

		global $wpdb;

		$counts = array(
			'revisions'  => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'revision'" ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			'spam'       => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_approved = 'spam'" ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
			'transients' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name LIKE '_transient_%' OR option_name LIKE '_site_transient_%'" ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
		);

		set_transient( 'upsd_status_counts', $counts, 5 * MINUTE_IN_SECONDS );

		return $counts;
	}

	private function render_status_box( $label, $value ) {
		?>
		<div class="upsd-stat">
			<span><?php echo esc_html( $label ); ?></span>
			<strong><?php echo esc_html( number_format_i18n( $value ) ); ?></strong>
		</div>
		<?php
	}

	private function render_notice() {
		$notice = '';

		if ( isset( $_GET['upsd_notice'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$allowed_notices = array(
				'recommended',
				'revisions_error',
				'spam_error',
				'transients_error',
			);

			$notice = sanitize_text_field( wp_unslash( $_GET['upsd_notice'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

			if (
				! in_array( $notice, $allowed_notices, true ) &&
				0 !== strpos( $notice, 'revisions_' ) &&
				0 !== strpos( $notice, 'spam_' ) &&
				0 !== strpos( $notice, 'transients_' )
			) {
				$notice = '';
			}
		}

		if ( '' !== $notice ) {
			$message = '';
			$type    = 'success';

			if ( 'recommended' === $notice ) {
				$message = __( 'Recommended settings applied.', 'dirtytackle-performance-cleanup' );
			} elseif ( 'revisions_error' === $notice ) {
				$message = __( 'Revision cleanup could not be completed.', 'dirtytackle-performance-cleanup' );
				$type    = 'error';
			} elseif ( 'spam_error' === $notice ) {
				$message = __( 'Spam comment cleanup could not be completed.', 'dirtytackle-performance-cleanup' );
				$type    = 'error';
			} elseif ( 'transients_error' === $notice ) {
				$message = __( 'Transient cleanup could not be completed.', 'dirtytackle-performance-cleanup' );
				$type    = 'error';
			} elseif ( 0 === strpos( $notice, 'revisions_' ) ) {
				$count = absint( substr( $notice, 10 ) );

				if ( $count > 0 ) {
						$message = sprintf(
						/* translators: %s: number of revisions removed in this batch. */
						__( '%s revisions removed in this batch.', 'dirtytackle-performance-cleanup' ),
						number_format_i18n( $count )
					);
				} else {
					$message = __( 'No revisions found to remove.', 'dirtytackle-performance-cleanup' );
				}
			} elseif ( 0 === strpos( $notice, 'spam_' ) ) {
				$count = absint( substr( $notice, 5 ) );

				if ( $count > 0 ) {
						$message = sprintf(
						/* translators: %s: number of spam comments removed in this batch. */
						__( '%s spam comments removed in this batch.', 'dirtytackle-performance-cleanup' ),
						number_format_i18n( $count )
					);
				} else {
					$message = __( 'No spam comments found to remove.', 'dirtytackle-performance-cleanup' );
				}
			} elseif ( 0 === strpos( $notice, 'transients_' ) ) {
				$count = absint( substr( $notice, 11 ) );

				if ( $count > 0 ) {
						$message = sprintf(
						/* translators: %s: number of transients cleared in this batch. */
						__( '%s transients cleared in this batch.', 'dirtytackle-performance-cleanup' ),
						number_format_i18n( $count )
					);
				} else {
					$message = __( 'No transients found to clear.', 'dirtytackle-performance-cleanup' );
				}
			}

			if ( $message ) {
				echo '<div class="notice notice-' . esc_attr( $type ) . ' is-dismissible"><p>' . esc_html( $message ) . '</p></div>';
			}
		}

		settings_errors( 'upsd_messages' );
	}

	private function render_checkbox_card( $settings, $key, $title, $description, $result ) {
		$enabled = ! empty( $settings[ $key ] );
		?>
		<div class="upsd-card">
			<span class="upsd-badge"><?php esc_html_e( 'Safe', 'dirtytackle-performance-cleanup' ); ?></span>
			<h2><?php echo esc_html( $title ); ?></h2>
			<p><?php echo esc_html( $description ); ?></p>
			<p class="upsd-result"><strong><?php esc_html_e( 'Expected result:', 'dirtytackle-performance-cleanup' ); ?></strong> <?php echo esc_html( $result ); ?></p>
			<label class="upsd-toggle">
				<input type="checkbox" name="<?php echo esc_attr( $this->option_key ); ?>[<?php echo esc_attr( $key ); ?>]" value="1" <?php checked( $enabled ); ?> />
				<span><?php esc_html_e( 'Enable this setting', 'dirtytackle-performance-cleanup' ); ?></span>
			</label>
		</div>
		<?php
	}

	private function render_heartbeat_card( $settings ) {
		$current = isset( $settings['heartbeat_mode'] ) ? $settings['heartbeat_mode'] : 'default';
		$name    = esc_attr( $this->option_key ) . '[heartbeat_mode]';
		?>
		<div class="upsd-card">
			<span class="upsd-badge"><?php esc_html_e( 'Safe', 'dirtytackle-performance-cleanup' ); ?></span>
			<h2><?php esc_html_e( 'Reduce background admin activity', 'dirtytackle-performance-cleanup' ); ?></h2>
			<p><?php esc_html_e( 'Heartbeat is a built in WordPress system that sends background requests. Reducing it can help on slower hosting.', 'dirtytackle-performance-cleanup' ); ?></p>
			<p class="upsd-result"><strong><?php esc_html_e( 'Expected result:', 'dirtytackle-performance-cleanup' ); ?></strong> <?php esc_html_e( 'Lower server load from repeated background requests.', 'dirtytackle-performance-cleanup' ); ?></p>
			<p class="upsd-note"><strong><?php esc_html_e( 'Good to know:', 'dirtytackle-performance-cleanup' ); ?></strong> <?php esc_html_e( 'If you edit posts with multiple users, leave this on reduced mode rather than fully disabling it.', 'dirtytackle-performance-cleanup' ); ?></p>

			<label class="upsd-radio">
				<input type="radio" name="<?php echo esc_attr( $name ); ?>" value="default" <?php checked( 'default', $current ); ?> />
				<span><?php esc_html_e( 'Leave it alone', 'dirtytackle-performance-cleanup' ); ?></span>
			</label>

			<label class="upsd-radio">
				<input type="radio" name="<?php echo esc_attr( $name ); ?>" value="limit" <?php checked( 'limit', $current ); ?> />
				<span><?php esc_html_e( 'Reduce activity frequency', 'dirtytackle-performance-cleanup' ); ?></span>
			</label>

			<label class="upsd-radio">
				<input type="radio" name="<?php echo esc_attr( $name ); ?>" value="disable_frontend" <?php checked( 'disable_frontend', $current ); ?> />
				<span><?php esc_html_e( 'Turn it off on the front end only', 'dirtytackle-performance-cleanup' ); ?></span>
			</label>
		</div>
		<?php
	}

	private function render_revisions_card( $settings ) {
		$enabled = ! empty( $settings['limit_revisions'] );
		$count   = isset( $settings['revisions_to_keep'] ) ? absint( $settings['revisions_to_keep'] ) : 5;
		?>
		<div class="upsd-card">
			<span class="upsd-badge"><?php esc_html_e( 'Safe', 'dirtytackle-performance-cleanup' ); ?></span>
			<h2><?php esc_html_e( 'Limit saved post revisions', 'dirtytackle-performance-cleanup' ); ?></h2>
			<p><?php esc_html_e( 'WordPress stores revision history as you edit posts and pages. Limiting it helps reduce database buildup over time.', 'dirtytackle-performance-cleanup' ); ?></p>
			<p class="upsd-result"><strong><?php esc_html_e( 'Expected result:', 'dirtytackle-performance-cleanup' ); ?></strong> <?php esc_html_e( 'Less database bloat on sites with lots of edits.', 'dirtytackle-performance-cleanup' ); ?></p>

			<label class="upsd-toggle">
				<input type="checkbox" name="<?php echo esc_attr( $this->option_key ); ?>[limit_revisions]" value="1" <?php checked( $enabled ); ?> />
				<span><?php esc_html_e( 'Enable revision limit', 'dirtytackle-performance-cleanup' ); ?></span>
			</label>

			<div class="upsd-inline-field">
				<label for="upsd-revisions-to-keep"><?php esc_html_e( 'Revisions to keep', 'dirtytackle-performance-cleanup' ); ?></label>
				<input id="upsd-revisions-to-keep" type="number" min="1" step="1" name="<?php echo esc_attr( $this->option_key ); ?>[revisions_to_keep]" value="<?php echo esc_attr( $count ); ?>" />
			</div>
		</div>
		<?php
	}

	private function render_cleanup_card( $action, $nonce, $title, $description, $button_text ) {
		?>
		<div class="upsd-card upsd-cleanup-card">
			<span class="upsd-badge upsd-badge-warn"><?php esc_html_e( 'Cleanup', 'dirtytackle-performance-cleanup' ); ?></span>
			<h2><?php echo esc_html( $title ); ?></h2>
			<p><?php echo esc_html( $description ); ?></p>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
				<input type="hidden" name="action" value="<?php echo esc_attr( $action ); ?>" />
				<?php wp_nonce_field( $nonce ); ?>
				<button type="submit" class="button button-secondary upsd-confirm-action"><?php echo esc_html( $button_text ); ?></button>
			</form>
		</div>
		<?php
	}

	public function render_settings_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$settings = $this->get_settings();
		$counts   = $this->get_status_counts();
		?>
		<div class="wrap upsd-wrap">
			<?php $this->render_notice(); ?>

			<div class="upsd-hero">
				<div class="upsd-hero-brand">
					<img
						src="<?php echo esc_url( UPSD_PLUGIN_URL . 'assets/icon.png' ); ?>"
						alt="<?php esc_attr_e( 'DirtyTackle Performance Cleanup icon', 'dirtytackle-performance-cleanup' ); ?>"
						class="upsd-logo"
					/>

					<div class="upsd-hero-copy">
						<h1><?php esc_html_e( 'DirtyTackle Performance Cleanup', 'dirtytackle-performance-cleanup' ); ?></h1>
						<p><?php esc_html_e( 'Safe speed improvements for WordPress without the risky settings that often break layouts.', 'dirtytackle-performance-cleanup' ); ?></p>
						<p class="upsd-hero-subtext"><?php esc_html_e( 'These settings remove unnecessary WordPress code, reduce background activity, and clean old database clutter without touching your theme files.', 'dirtytackle-performance-cleanup' ); ?></p>
						<p class="upsd-hero-subtext"><?php esc_html_e( 'Ideal for brochure sites, blogs, affiliate sites, and small business WordPress installs.', 'dirtytackle-performance-cleanup' ); ?></p>
					</div>
				</div>

				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="upsd-recommended-form">
					<input type="hidden" name="action" value="upsd_apply_recommended" />
					<?php wp_nonce_field( 'upsd_apply_recommended' ); ?>
					<button type="submit" class="button button-primary button-hero"><?php esc_html_e( 'Apply Recommended Settings', 'dirtytackle-performance-cleanup' ); ?></button>
				</form>
			</div>

			<div class="upsd-section-head">
				<h2><?php esc_html_e( 'System status', 'dirtytackle-performance-cleanup' ); ?></h2>
				<p><?php esc_html_e( 'A quick view of the areas this plugin can help tidy up.', 'dirtytackle-performance-cleanup' ); ?></p>
			</div>

			<div class="upsd-stats">
				<?php
				$this->render_status_box( __( 'Saved revisions', 'dirtytackle-performance-cleanup' ), $counts['revisions'] );
				$this->render_status_box( __( 'Spam comments', 'dirtytackle-performance-cleanup' ), $counts['spam'] );
				$this->render_status_box( __( 'Stored transient rows', 'dirtytackle-performance-cleanup' ), $counts['transients'] );
				?>
			</div>

			<form method="post" action="options.php">
				<?php settings_fields( 'upsd_settings_group' ); ?>

				<div class="upsd-section-head">
					<h2><?php esc_html_e( 'Safe speed wins', 'dirtytackle-performance-cleanup' ); ?></h2>
					<p><?php esc_html_e( 'These are the low risk settings that can help trim unnecessary WordPress code.', 'dirtytackle-performance-cleanup' ); ?></p>
				</div>

				<div class="upsd-grid">
					<?php
					$this->render_checkbox_card(
						$settings,
						'disable_emojis',
						__( 'Stop WordPress loading emoji code', 'dirtytackle-performance-cleanup' ),
						__( 'Removes extra emoji scripts and styles that many sites do not need.', 'dirtytackle-performance-cleanup' ),
						__( 'Slightly lighter page load with fewer unnecessary assets.', 'dirtytackle-performance-cleanup' )
					);

					$this->render_checkbox_card(
						$settings,
						'disable_embeds',
						__( 'Turn off WordPress embed code', 'dirtytackle-performance-cleanup' ),
						__( 'Useful if you do not use WordPress post embeds on your site.', 'dirtytackle-performance-cleanup' ),
						__( 'Less front end code loaded on each page.', 'dirtytackle-performance-cleanup' )
					);

					$this->render_checkbox_card(
						$settings,
						'remove_dashicons_guests',
						__( 'Remove Dashicons for visitors', 'dirtytackle-performance-cleanup' ),
						__( 'Stops WordPress loading the Dashicons icon font for logged out users.', 'dirtytackle-performance-cleanup' ),
						__( 'One less stylesheet for visitors who do not need admin icons.', 'dirtytackle-performance-cleanup' )
					);

					$this->render_checkbox_card(
						$settings,
						'disable_xmlrpc',
						__( 'Disable older remote publishing access', 'dirtytackle-performance-cleanup' ),
						__( 'Turns off authenticated XML-RPC features used by older remote publishing tools that most sites do not need.', 'dirtytackle-performance-cleanup' ),
						__( 'Reduced attack surface and one less background feature to worry about.', 'dirtytackle-performance-cleanup' )
					);
					?>
				</div>

				<div class="upsd-section-head">
					<h2><?php esc_html_e( 'Reduce background load', 'dirtytackle-performance-cleanup' ); ?></h2>
					<p><?php esc_html_e( 'These settings help cut down on behind the scenes activity that can build up over time.', 'dirtytackle-performance-cleanup' ); ?></p>
				</div>

				<div class="upsd-grid">
					<?php
					$this->render_heartbeat_card( $settings );
					$this->render_revisions_card( $settings );
					?>
				</div>

				<div class="upsd-footer-actions">
					<?php submit_button( __( 'Save settings', 'dirtytackle-performance-cleanup' ), 'primary', 'submit', false ); ?>
				</div>
			</form>

			<div class="upsd-section-head">
				<h2><?php esc_html_e( 'Cleanup tools', 'dirtytackle-performance-cleanup' ); ?></h2>
				<p><?php esc_html_e( 'Use these when you want to remove old clutter from the database. These actions cannot be undone.', 'dirtytackle-performance-cleanup' ); ?></p>
				<p class="upsd-cleanup-subtext"><?php esc_html_e( 'These tools are best used after backups, migrations, plugin removals, or large content editing sessions.', 'dirtytackle-performance-cleanup' ); ?></p>
			</div>

			<div class="upsd-grid">
				<?php
				$this->render_cleanup_card(
					'upsd_cleanup_revisions',
					'upsd_cleanup_revisions',
					__( 'Clear revisions', 'dirtytackle-performance-cleanup' ),
					__( 'Deletes up to 100 saved revision posts per run using the WordPress revision APIs.', 'dirtytackle-performance-cleanup' ),
					__( 'Clear revisions', 'dirtytackle-performance-cleanup' )
				);

				$this->render_cleanup_card(
					'upsd_cleanup_spam',
					'upsd_cleanup_spam',
					__( 'Clear spam comments', 'dirtytackle-performance-cleanup' ),
					__( 'Deletes up to 100 comments marked as spam per run using the WordPress comment APIs.', 'dirtytackle-performance-cleanup' ),
					__( 'Clear spam comments', 'dirtytackle-performance-cleanup' )
				);

				$this->render_cleanup_card(
					'upsd_cleanup_transients',
					'upsd_cleanup_transients',
					__( 'Clear transients', 'dirtytackle-performance-cleanup' ),
					__( 'Clears a batch of stored transients per run using the WordPress transient APIs.', 'dirtytackle-performance-cleanup' ),
					__( 'Clear transients', 'dirtytackle-performance-cleanup' )
				);
				?>
			</div>
		</div>
		<?php
	}
}
