<?php
/**
 * Defensive HTTP headers for the admin pages and plugin REST endpoints.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k\Security;

defined( 'ABSPATH' ) || exit;

final class Headers {

	public static function register(): void {
		add_action( 'send_headers', array( __CLASS__, 'maybe_add_headers' ) );
		add_filter( 'rest_post_dispatch', array( __CLASS__, 'add_rest_headers' ), 10, 3 );
	}

	public static function maybe_add_headers(): void {
		if ( ! is_admin() ) {
			return;
		}
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || strpos( (string) $screen->id, 'suitemkt3k' ) === false ) {
			return;
		}
		header( 'X-Content-Type-Options: nosniff' );
		header( 'Referrer-Policy: strict-origin-when-cross-origin' );
		header( 'X-Frame-Options: SAMEORIGIN' );
	}

	/**
	 * @param \WP_HTTP_Response $response
	 * @param \WP_REST_Server   $server
	 * @param \WP_REST_Request  $request
	 * @return \WP_HTTP_Response
	 */
	public static function add_rest_headers( $response, $server, $request ) {
		$route = (string) $request->get_route();
		if ( strpos( $route, '/suitemkt3k/' ) !== false ) {
			$response->header( 'X-Content-Type-Options', 'nosniff' );
			$response->header( 'Referrer-Policy', 'no-referrer' );
		}
		return $response;
	}
}
