<?php

/**
 * LiteSpeed Cache
 *
 * https://wordpress.org/plugins/litespeed-cache/
 */
if ( ! class_exists( 'BWFAN_Compatibility_With_LightSpeed' ) ) {
	class BWFAN_Compatibility_With_LightSpeed {

		public function __construct() {
			$admin_page = filter_input( INPUT_GET, 'page' );
			if ( ! empty( $admin_page ) && 'litespeed-cache' === $admin_page ) {
				return;
			}

			/** Exclude FKA endpoints from cache */
			add_filter( 'option_litespeed.conf.cache-exc', array( $this, 'cache_exc' ), PHP_INT_MAX );
			add_filter( 'default_option_litespeed.conf.cache-exc', array( $this, 'cache_exc' ), PHP_INT_MAX );

			/** Exclude admin role from cache */
			add_filter( 'option_litespeed.conf.cache-exc_roles', array( $this, 'cache_exc_roles' ), PHP_INT_MAX );
			add_filter( 'default_option_litespeed.conf.cache-exc_roles', array( $this, 'cache_exc_roles' ), PHP_INT_MAX );

			/** Exclude query strings from cache */
			add_filter( 'option_litespeed.conf.cache-exc_qs', array( $this, 'cache_exc_qs' ), PHP_INT_MAX );
			add_filter( 'default_option_litespeed.conf.cache-exc_qs', array( $this, 'cache_exc_qs' ), PHP_INT_MAX );
		}

		/**
		 * Exclude FKA endpoints from cache
		 *
		 * @param $value
		 *
		 * @return false|string
		 */
		public function cache_exc( $value ) {
			$value = BWFAN_Common::make_array( $value );

			$value[] = "^/wp-json/" . BWFAN_API_NAMESPACE . "/";
			$value[] = "^/wp-json/woofunnels/";
			$value[] = "^/wp-json/funnelkit-automations/";

			$value = BWFAN_Common::unique( $value );

			return wp_json_encode( $value );
		}

		/**
		 * Exclude admin role from cache
		 *
		 * @param $value
		 *
		 * @return false|string
		 */
		public function cache_exc_roles( $value ) {
			$value = BWFAN_Common::make_array( $value );

			$value[] = "administrator";

			$value = BWFAN_Common::unique( $value );

			return wp_json_encode( $value );
		}

		/**
		 * Exclude query strings from cache
		 *
		 * @param $value
		 *
		 * @return false|string
		 */
		public function cache_exc_qs( $value ) {
			$value = BWFAN_Common::make_array( $value );

			$value[] = "bwfan-track-id";
			$value[] = "bwfan-track-action";
			$value[] = "bwfan-link-trigger";

			$value = BWFAN_Common::unique( $value );

			return wp_json_encode( $value );
		}
	}

	if ( defined( 'LSCWP_V' ) ) {
		new BWFAN_Compatibility_With_LightSpeed();
	}
}
