<?php
/**
 * BaseCloud Boost — Security Headers
 *
 * Adds HTTP security headers to all non-admin front-end responses.
 * These headers harden the site against common web attacks and improve
 * Google security audits / Lighthouse "Best Practices" scores.
 *
 * Headers added (each individually toggleable in settings):
 *
 *  X-Content-Type-Options: nosniff
 *    — Prevents MIME-type sniffing attacks.
 *
 *  X-Frame-Options: SAMEORIGIN
 *    — Prevents clickjacking by blocking cross-origin iframes.
 *
 *  Referrer-Policy: strict-origin-when-cross-origin
 *    — Limits referrer information sent to third-party sites.
 *
 *  Permissions-Policy: interest-cohort=()
 *    — Opts out of FLoC / Topics API (privacy).
 *
 *  X-XSS-Protection: 1; mode=block
 *    — Legacy XSS protection for older IE/Edge.
 *
 *  Strict-Transport-Security (HSTS): max-age=31536000; includeSubDomains
 *    — Enforces HTTPS for 1 year (only sent over HTTPS connections).
 *
 * @package BaseCloud\Boost\Core
 */

declare( strict_types=1 );

namespace BaseCloud\Boost\Core;

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

/**
 * Sends HTTP security response headers.
 */
class Security_Headers {

	/**
	 * Boot security headers module.
	 *
	 * @return void
	 */
	public function boot(): void {
		if ( ! BCBOOST_get_option( 'security_headers', false ) ) {
			return;
		}

		add_action( 'send_headers', [ $this, 'send' ] );
	}

	/**
	 * Emit all configured security headers.
	 *
	 * @return void
	 */
	public function send(): void {
		// Never add these headers in the admin area.
		if ( is_admin() ) {
			return;
		}

		header( 'X-Content-Type-Options: nosniff' );
		header( 'X-Frame-Options: SAMEORIGIN' );
		header( 'Referrer-Policy: strict-origin-when-cross-origin' );
		header( 'Permissions-Policy: interest-cohort=(), geolocation=(), microphone=(), camera=()' );
		header( 'X-XSS-Protection: 1; mode=block' );

		// HSTS — only over HTTPS.
		if ( is_ssl() || ( ! empty( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) ) {
			$hsts_max_age = (int) BCBOOST_get_option( 'hsts_max_age', 31536000 );
			if ( $hsts_max_age > 0 ) {
				$hsts = 'max-age=' . $hsts_max_age . '; includeSubDomains';
				if ( BCBOOST_get_option( 'hsts_preload', false ) ) {
					$hsts .= '; preload';
				}
				header( 'Strict-Transport-Security: ' . $hsts );
			}
		}
	}

	/**
	 * Return equivalent .htaccess rules for Apache servers.
	 *
	 * @return string
	 */
	public static function get_htaccess_rules(): string {
		return '
# ── BaseCloud Boost: Security Headers ────────────────────────────────
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    Header always set Permissions-Policy "interest-cohort=(), geolocation=(), microphone=(), camera=()"
    Header always set X-XSS-Protection "1; mode=block"
</IfModule>
';
	}
}
