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

use QuantumCache\Admin\AdminPage;
use QuantumCache\Cache\QueryCache;
use QuantumCache\Cache\FragmentCache;
use QuantumCache\Cache\AutoFragments;

require_once __DIR__ . '/Support/Helpers.php';

final class Plugin {

	public static function init(): void {
		// Register everything early on 'init' so WP APIs are available.
		add_action(
			'init',
			static function () {
				QueryCache::register();
				AutoFragments::register();
				AdminPage::register();

								// Bridge admin options to runtime filters.
				add_filter(
					'quantumcache_query_ttl',
					function ( $ttl, $q ) {
						$opt = (int) get_option( 'quantumcache_query_ttl', 0 );
						return $opt > 0 ? $opt : $ttl;
					},
					10,
					2
				);
				add_filter(
					'quantumcache_query_stale_ttl',
					function ( $ttl, $q ) {
						$opt = (int) get_option( 'quantumcache_query_stale_ttl', 0 );
						if ( $opt >= 0 ) {
													return ( $opt ? $opt : $ttl );
						}
												return $ttl;
					},
					10,
					2
				);
				add_filter(
					'quantumcache_min_archive_ids',
					function ( $min, $q ) {
						$opt = (int) get_option( 'quantumcache_min_archive_ids', 12 );
						return $opt >= 0 ? $opt : $min;
					},
					10,
					2
				);
				add_filter(
					'quantumcache_fragment_ttl',
					function ( $ttl, $name, $ctx ) {
						$opt = (int) get_option( 'quantumcache_fragment_ttl', 0 );
						return $opt > 0 ? $opt : $ttl;
					},
					10,
					3
				);
				add_filter(
					'quantumcache_fragment_stale_ttl',
					function ( $ttl, $name, $ctx ) {
						$opt = (int) get_option( 'quantumcache_fragment_stale_ttl', -1 );
						if ( $opt >= 0 ) {
													return ( $opt ? $opt : $ttl );
						}
												return $ttl;
					},
					10,
					3
				);
								// ---- Policy gates ----
				add_filter(
					'quantumcache_is_cacheable_request',
					static function ( bool $ok ): bool {
						if ( is_admin() ) {
							return false;
						}

												$req_method = isset( $_SERVER['REQUEST_METHOD'] )
						? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) )
						: 'GET';

						if ( ! in_array( $req_method, array( 'GET', 'HEAD' ), true ) ) {
								return false;
						}

						// If logged in but logged-in cache is not allowed → non-cacheable.
						if ( function_exists( 'is_user_logged_in' ) && is_user_logged_in() ) {
							if ( ! \quantumcache_allow_logged_in_cache() ) {
								return false;
							}
						}

						return $ok;
					},
					10,
					1
				);

				add_filter( 'quantumcache_should_bypass_cache', static fn( bool $b )=>$b, 10, 1 );
				add_filter( 'quantumcache_can_store_response', static fn( bool $b )=>$b, 10, 1 );
				add_filter( 'quantumcache_should_store_response', static fn( bool $b )=>$b, 10, 1 );
				add_filter( 'quantumcache_ttl_for_request', static fn( int $ttl, array $ctx )=>( $ttl > 0 ? $ttl : 120 ), 10, 2 );

				// ---- Key variance / CDN vary ----
				add_filter( 'quantumcache_query_key_context', static fn( array $ctx, \WP_Query $q )=>$ctx, 10, 2 );
				add_filter( 'quantumcache_variant_cookies', static fn( array $cookies )=>$cookies, 10, 1 );

				// ---- Tag surfaces ----
				add_filter( 'quantumcache_store_additional_tags', static fn( array $tags, array $ctx )=>$tags, 10, 2 );
				add_filter(
					'quantumcache_current_request_tags',
					function ( $tags ) {
						return (array) $tags;
					},
					10,
					1
				);
			},
			0
		);

		// Template helper for fragments (namespaced).
		if ( ! function_exists( 'QuantumCache\\quantumcache_fragment' ) ) {
			function quantumcache_fragment( string $name, array $ctx, callable $producer, array $opts = array() ): string {
				return FragmentCache::render( $name, $ctx, $producer, $opts );
			}
		}
	}
}

add_action( 'send_headers', '\\QuantumCache\\quantumcache_flush_fragment_headers', 98 );

// Headers/debug info (safe to leave here; activation hook moves to main file).
add_action(
	'send_headers',
	static function () {
		global $wpdb;

		// Only emit when the admin toggle is ON.
		if ( \QuantumCache\quantumcache_should_debug_headers() && ! headers_sent() ) {
			\QuantumCache\quantumcache_send_debug_header( 'X-QC-DB-Queries', (string) (int) $wpdb->num_queries );

			// timer_stop( $display = 0, $precision = 3 ) returns seconds as float string when $display=0.
			$ms = number_format_i18n( (float) timer_stop( 0, 3 ) * 1000, 3 );
			\QuantumCache\quantumcache_send_debug_header( 'X-QC-DB-Time', $ms . 'ms' );

			\QuantumCache\quantumcache_send_debug_header(
				'X-QC-Store-Actual',
				\QuantumCache\Support\StoreFactory::storeName()
			);
		}
	},
	99
);
