<?php

namespace DisableRSSFeeds;

use WP_PowerSuite\Core\AbstractModule;

class Module extends AbstractModule {

	private const MODULE_ID = 'disable-rss-feeds';
	private const MODULE_VERSION = '1.1.2';

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Disable RSS Feeds', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Turn off public RSS feeds when you do not want posts syndicated or automatically mirrored elsewhere.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return 'frontend';
	}

	protected function registerHooks(): void {
		if ( $this->shouldShortCircuit() ) {
			return;
		}

		remove_action( 'wp_head', 'feed_links', 2 );
		remove_action( 'wp_head', 'feed_links_extra', 3 );
		/*
		 * Block before template-loader calls do_feed() so every feed type is covered, including
		 * custom do_feed_{$feed} handlers plugins register (core only maps rdf/rss/rss2/atom).
		 */
		add_action( 'template_redirect', [ $this, 'blockFeedRequest' ], 0 );
	}

	/**
	 * No HTML head or feeds on REST/AJAX; ModuleManager may still load this module in those contexts.
	 */
	private function shouldShortCircuit(): bool {
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return true;
		}
		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			return true;
		}
		return false;
	}

	public function blockFeedRequest(): void {
		if ( ! is_feed() ) {
			return;
		}

		status_header( 403 );
		nocache_headers();
		wp_die(
			__( 'RSS feeds are disabled.', 'wp-powersuite' ),
			__( 'Forbidden', 'wp-powersuite' ),
			[ 'response' => 403 ]
		);
	}
}
