<?php
/**
 * HappyFenceNG Total Enterprise Security Plugin
 * HAPPYWPRESS is a RazorVue Trademark.
 *
 * @package     HappyFenceNG
 * @developer   Simonluca Scillitani
 * @copyright   2025 RazorVue di Scillitani Simonluca
 * @link        https://razorvue.it
 * @author      RazorVue di Scillitani Simonluca
 * @brand       HappyWPress
 * @uri         https://happywpress.com
 * @set all
 */

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

/**PHPCS -> code compliance: we put useful comments where needed.. */
class HappyFenceNGVRBUN extends HappyFenceNGAVRoute {

	/**PHPCS -> code compliance: we put useful comments where needed.. */
	public function doRoute() {
		try {

			$first_page_id = 0;
			$pages         = get_pages();
			if ( ! empty( $pages ) ) {
					$first_page_id = (int) $pages[0]->ID;
			}

			if ( HappyFenceNGPROC::equals( HappyFenceNGWhoAmI::get_instance()->TRAP404->trap_404_template_page_id, 0 ) ) {
				HappyFenceNGWhoAmI::get_instance()->TRAP404->trap_404_template_page_id = $first_page_id;
			}

			$nonce_save_settings = wp_create_nonce( 'happyfenceng_BUN_save_settings' );
			$burn                = HappyFenceNGFailFast::setup();
			$params              = array(
				'texts'  => array(
					'title'                              => esc_html__( 'Advanced Security Features', 'happyfenceng-total-enterprise-security' ),
					'sub_title_filesystem_sec'           => esc_html__( 'Advanced Filesystem Protection', 'happyfenceng-total-enterprise-security' ),
					'sub_title_api_rest'                 => esc_html__( 'REST API: Block Specific Endpoints', 'happyfenceng-total-enterprise-security' ),

					'autoremove_dangerous_files_title'   => esc_html__( 'Auto-remove dangerous files', 'happyfenceng-total-enterprise-security' ),
					'autoremove_dangerous_files_description' => esc_html__( 'Automatically delete the files above if found (use with caution)', 'happyfenceng-total-enterprise-security' ),
					'autoremove_dangerous_files_tooltip' => esc_html__( 'Automatically deletes potentially dangerous files (such as install.php, readme.html, or backup archives) if detected during scans. Use with caution as this action is irreversible.', 'happyfenceng-total-enterprise-security' ),

					'select_endpoints_to_block_title'    => esc_html__( 'Select endpoints to block', 'happyfenceng-total-enterprise-security' ),
					'select_endpoints_to_block_description' => esc_html__( 'REST API Endpoint Blocking', 'happyfenceng-total-enterprise-security' ),
					'select_endpoints_to_block_tooltip'  => esc_html__( 'Allows selective blocking of specific REST API endpoints to limit external access to sensitive or unused routes. Useful for reducing attack surface and hardening your WordPress installation.', 'happyfenceng-total-enterprise-security' ),

					'sub_title_user_enum'                => esc_html__( 'User Enumeration Hardening', 'happyfenceng-total-enterprise-security' ),
					'block_user_enum_title'              => esc_html__( 'Block user enumeration via login attempts', 'happyfenceng-total-enterprise-security' ),
					'block_user_enum_description'        => esc_html__( 'Enable uniform login error and delay to prevent username probing.', 'happyfenceng-total-enterprise-security' ),
					'block_user_enum_tooltip'            => esc_html__( 'Prevents username enumeration by returning identical error messages and adding a delay to all failed logins. This mitigates time-based attacks that rely on measuring response differences to guess valid usernames.', 'happyfenceng-total-enterprise-security' ),

					'sub_title_404'                      => esc_html__( '404 Trap (Anti-Scanner Cloaking)', 'happyfenceng-total-enterprise-security' ),
					'enable_404_trap_title'              => esc_html__( 'Enable 404 Trap', 'happyfenceng-total-enterprise-security' ),
					'enable_404_trap_description'        => esc_html__( 'Activate anti-scanner 404 cloaking', 'happyfenceng-total-enterprise-security' ),
					'enable_404_trap_tooltip'            => esc_html__( 'Activates a stealth 404 trap that returns fake but consistent pages instead of standard 404 errors. This confuses automated scanners by masking which URLs actually exist, using uniform-size responses or predefined templates to neutralize length-based brute-force attacks and directory enumeration.', 'happyfenceng-total-enterprise-security' ),

					'mode_404_trap_title'                => esc_html__( 'Trap Mode', 'happyfenceng-total-enterprise-security' ),
					'mode_404_trap_description'          => esc_html__( 'Choose trap mode', 'happyfenceng-total-enterprise-security' ),
					'mode_404_trap_tooltip'              => esc_html__( 'Choose the 404 Trap response mode: Stealth returns a minimal fake page with random content; Shield Black adds a random delay before responding, simulating server lag; Template uses a real WordPress page with invisible content embedded. All modes prevent scanners from reliably detecting missing pages.', 'happyfenceng-total-enterprise-security' ),

					'max_words_title'                    => esc_html__( 'Max Words / Characters', 'happyfenceng-total-enterprise-security' ),
					'max_words_description'              => esc_html__( 'Set the max number', 'happyfenceng-total-enterprise-security' ),
					'max_words_tooltip'                  => esc_html__( 'Sets the maximum number of words or characters used to generate fake pages for the 404 Trap, controlling the size of the uniform response to confuse scanners.', 'happyfenceng-total-enterprise-security' ),
					'template_page_title'                => esc_html__( 'Template Page', 'happyfenceng-total-enterprise-security' ),
					'template_page_description'          => esc_html__( '(for Template mode)', 'happyfenceng-total-enterprise-security' ),
					'template_page_tooltip'              => esc_html__( 'Selects the WordPress page used as the base template for fake 404 responses in Template mode. The page content will be served with hidden payloads to confuse scanners.', 'happyfenceng-total-enterprise-security' ),
					'feature_requires'                   => esc_html__( 'THIS FEATURE REQUIRES ENTERPRISE', 'happyfenceng-total-enterprise-security' ),
					'save_settings'                      => esc_html__( 'Save Settings', 'happyfenceng-total-enterprise-security' ),
					'settings_saved'                     => esc_html__( 'Settings Saved', 'happyfenceng-total-enterprise-security' ),
					'error_saving_settings'              => esc_html__( 'Error saving settings', 'happyfenceng-total-enterprise-security' ),
				),
				'links'  => array(
					'happyfenceng_logo_url' => esc_url( HAPPYFENCENG_PLUGIN_URL . 'assets/images/happyfenceng-small.png' ),

				),
				'values' => array(
					'auto_remove_dangerous_files' => HappyFenceNGCleaner::checkMe( HappyFenceNGWhoAmI::get_instance()->FILESYSTEM->auto_remove_dangerous_files, HappyFenceNGPlaceholder::BOOL_PROP_DEFAULT ),
					'enable_rest_blocking'        => HappyFenceNGCleaner::checkMe( HappyFenceNGWhoAmI::get_instance()->REST->enable_rest_blocking, HappyFenceNGPlaceholder::BOOL_PROP_DEFAULT ),
					'all_rest_endpoints'          => self::get_all_rest_endpoints(),
					'blocked_endpoints'           => HappyFenceNGCleaner::checkMe( HappyFenceNGWhoAmI::get_instance()->REST->blocked_endpoints, HappyFenceNGPlaceholder::EMPTY_ARRAY ),
					'block_user_enum'             => HappyFenceNGCleaner::checkMe( HappyFenceNGWhoAmI::get_instance()->LOGINENUM->block_user_enum, HappyFenceNGPlaceholder::BOOL_PROP_DEFAULT ),
					'enable_404_trap'             => HappyFenceNGCleaner::checkMe( HappyFenceNGWhoAmI::get_instance()->TRAP404->enable_404_trap, HappyFenceNGPlaceholder::BOOL_PROP_DEFAULT ),
					'trap_404_mode'               => HappyFenceNGCleaner::checkMe( HappyFenceNGWhoAmI::get_instance()->TRAP404->trap_404_mode, 'stealth' ),
					'trap_404_MAX_WORDS'          => HappyFenceNGCleaner::checkMe( HappyFenceNGWhoAmI::get_instance()->TRAP404->trap_404_MAX_WORDS, 100 ),
					'trap_404_template_page'      => HappyFenceNGCleaner::checkMe( HappyFenceNGWhoAmI::get_instance()->TRAP404->trap_404_template_page_id, $first_page_id ),
					'pages'                       => get_pages(),
					'checkbox_on'                 => HappyFenceNGPlaceholder::CHECKBOX_ON,
					'checkbox_off'                => HappyFenceNGPlaceholder::CHECKBOX_OFF,
					'burnNonce'                   => $burn,
					'nonce'                       => $nonce_save_settings,
					'feature_enabled'             => ( function_exists( 'htes_fs' ) && HappyFenceNGTR::is_in( static::class, array( HappyFenceNGTR::BUNKER ) ) ),

				),
			);

			ob_start();
			HappyFenceNGVControl::renderView( $params, 'bun' );
			// phpcs:ignore WordPress.Security.EscapeOutput
			echo ob_get_clean();

		} catch ( Throwable $e ) {
			HappyFenceNGLOGCORE::logcore(
				'HappyFenceNGVRBUN - cannot render UI ' . $e->getMessage(),
				HappyFenceNGSyslogFacility::UI,
				HappyFenceNGSyslogSeverity::ERROR
			);
			ob_end_clean();
			HappyFenceNGCleaner::cleaner_oops();
		}
	}

	/**PHPCS -> code compliance: we put useful comments where needed.. */
	public static function get_all_rest_endpoints() {
			$all = rest_get_server()->get_routes() ?? array();
			ksort( $all );
			$flat_endpoints = array();

		foreach ( $all as $path => $endpoint_arr ) {
			foreach ( $endpoint_arr as $endpoint ) {
						$flat_endpoints[] = $path;
			}
		}

		// Filtra i duplicati usando array_unique.
		$unique_endpoints = array_unique( $flat_endpoints );

		return $unique_endpoints;
	}
}
