<?php

namespace Waypoint\Agent\Setup;

use Waypoint\Agent\Base\Thing;

class Disable_Comments extends Thing {

	public function attach_hooks(): void {
		add_filter( 'comments_open', '__return_false', 20, 2 );
		add_filter( 'pings_open', '__return_false', 20, 2 );
		add_filter( 'comments_array', '__return_empty_array', 10, 2 );
		add_filter( 'pre_option_default_comment_status', '__return_zero' );
		add_filter( 'pre_option_default_ping_status', '__return_zero' );

		add_action( 'init', [ $this, 'remove_post_type_support' ], 100 );
		add_action( 'rest_api_init', [ $this, 'disable_rest_endpoint' ], 99 );
		add_action( 'admin_menu', [ $this, 'remove_admin_menu' ] );
		add_action( 'admin_bar_menu', [ $this, 'remove_admin_bar_node' ], 999 );
		add_action( 'wp_dashboard_setup', [ $this, 'remove_dashboard_widget' ] );
	}

	public function remove_post_type_support(): void {
		foreach ( get_post_types() as $post_type ) {
			remove_post_type_support( $post_type, 'comments' );
			remove_post_type_support( $post_type, 'trackbacks' );
		}
	}

	public function disable_rest_endpoint(): void {
		add_filter( 'rest_endpoints', [ $this, 'remove_comment_endpoints' ] );
	}

	public function remove_comment_endpoints( array $endpoints ): array {
		unset( $endpoints['/wp/v2/comments'] );
		unset( $endpoints['/wp/v2/comments/(?P<id>[\d]+)'] );
		return $endpoints;
	}

	public function remove_admin_menu(): void {
		remove_menu_page( 'edit-comments.php' );
	}

	public function remove_admin_bar_node( \WP_Admin_Bar $wp_admin_bar ): void {
		$wp_admin_bar->remove_node( 'comments' );
	}

	public function remove_dashboard_widget(): void {
		remove_meta_box( 'dashboard_recent_comments', 'dashboard', 'normal' );
	}
}
