<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

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

/**
 * Class LiteSpeedCache
 */
class LiteSpeedCache extends AbstractPlugin {
	public function init(): void {
		add_filter( 'fibofilters/admin_script/config/use_initial_nonce', [ $this, 'use_initial_nonce_if_esi_is_active' ] );
		add_action( 'litespeed_control_finalize', [ $this, 'prevent_caching_indexer_rest_api' ] );

		add_action( 'litespeed_control_finalize', [ $this, 'set_control' ] );
	}

	/**
	 * Compatibility with the ESI mechanism from the LiteSpeed Cache plug-in
	 *
	 * Active "ESI" option in the "LiteSpeed Cache" plugin causes the nonce when saving the settings of our plugin
	 * to be different from "wpApiSettings.nonce". This causes a 403 error when trying to save the settings with
	 * the message "rest_cookie_invalid_nonce".
	 *
	 * When the "ESI" mechanism is active, our plugin sets the nonce to "wpApiSettings.nonce" again
	 * before saving the settings via the REST API.
	 */
	public function use_initial_nonce_if_esi_is_active(): bool {
		// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		return (bool) apply_filters( 'litespeed_esi_status', false );
	}

	public function prevent_caching_indexer_rest_api() {
		$uri = esc_url( $_SERVER['REQUEST_URI'] );

		if ( strpos( $uri, 'wp-json/fibofilters/v1/index' ) !== false ) {
			// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
			do_action( 'litespeed_control_set_nocache', 'fibofilters indexer rest api' );
		}
	}

	/**
	 * Disables caching for the FiboFilters REST API
	 */
	public function set_control() {
		// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		if ( ! apply_filters( 'litespeed_control_cacheable', false ) ) {
			return;
		}

		$uri     = esc_url( $_SERVER['REQUEST_URI'] );
		$uri_len = strlen( $uri );
		if ( $uri_len < 5 ) {
			return;
		}

		if ( strpos( $uri, 'wp-json/fibofilters/v1' ) !== false ) {
			// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
			do_action( 'litespeed_control_set_nocache', 'fibofilters rest api' );
		}
	}
}
