<?php
namespace QuantumCache;
\defined( 'ABSPATH' ) || exit;


if ( ! function_exists( __NAMESPACE__ . '\\quantumcache_should_debug_headers' ) ) {
	/**
	 * Should we emit X-QC debug headers?
	 * - Respects QUANTUMCACHE_DEBUG_HEADERS constant if present.
	 */
	function quantumcache_should_debug_headers(): bool {
		// Constant wins if defined; no comparison needed (avoid Yoda warnings).
		if ( defined( 'QUANTUMCACHE_DEBUG_HEADERS' ) ) {
			return (bool) QUANTUMCACHE_DEBUG_HEADERS;
		}

		$val = get_option( 'quantumcache_debug_headers', '0' );

		// Normalize to a lowercase string and match against a truthy set.
		if ( is_bool( $val ) ) {
			return $val;
		}

		$val_str = is_string( $val ) ? strtolower( $val ) : (string) $val;

		// Use in_array with strict check to avoid chained comparisons (PHPCS-friendly).
		return in_array( $val_str, array( '1', 'on', 'true', 'yes' ), true );
	}
}

if ( ! function_exists( __NAMESPACE__ . '\\quantumcache_send_debug_header' ) ) {
	/**
	 * Emit a debug header only when quantumcache_should_debug_headers() is true.
	 */
	function quantumcache_send_debug_header( string $name, string $value ): void {
		if ( quantumcache_should_debug_headers() && ! headers_sent() ) {
			header( $name . ': ' . $value, false );
		}
	}
}


if ( ! function_exists( __NAMESPACE__ . '\\quantumcache_note_fragment_key' ) ) {
	function quantumcache_note_fragment_key( string $key ): void {
		static $seen = array();
		if ( ! quantumcache_should_debug_headers() ) {
			return;
		}
		$seen[ $key ]                               = true;
		$GLOBALS['quantumcache_seen_fragment_keys'] = $seen; // expose for flusher
	}
}

if ( ! function_exists( __NAMESPACE__ . '\\quantumcache_flush_fragment_headers' ) ) {
	function quantumcache_flush_fragment_headers(): void {
		if ( ! quantumcache_should_debug_headers() || headers_sent() ) {
			return;
		}
		$seen = isset( $GLOBALS['quantumcache_seen_fragment_keys'] ) && is_array( $GLOBALS['quantumcache_seen_fragment_keys'] )
			? array_keys( $GLOBALS['quantumcache_seen_fragment_keys'] )
			: array();

		$count = (string) count( $seen );

		// Emit up to 3 keys (last 16 chars) to avoid bloat.
		$max  = 3;
		$emit = array_slice( $seen, -$max );
		foreach ( $emit as $k ) {
			quantumcache_send_debug_header( 'X-QC-Fragment-Key', substr( $k, -16 ) );
		}
		if ( count( $seen ) > $max ) {
			quantumcache_send_debug_header( 'X-QC-Fragment-Keys-Trimmed', (string) ( count( $seen ) - $max ) );
		}
	}
}
