<?php

namespace EasyCriticalCSS;

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

/**
 * This file is for compatibility purposes and will not use the easy_cc prefix in defines.
 * phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
 */

class Compatibility_Cloudflare extends Compatibility {
	public static $cf_setup = null;

	public static function init() {
		self::add_conditional_action( [ __CLASS__, 'get_cloudflare_setup' ], 'wp_headers', [ __CLASS__, 'update_header_cache' ] );
	}

	public static function get_cloudflare_setup() {
		if ( null !== self::$cf_setup ) {
			return self::$cf_setup;
		}

		$cloudflare_email   = Settings::get_global_cloudflare_email();
		$cloudflare_api_key = Settings::get_global_cloudflare_api_key();
		$cloudflare_zone_id = Settings::get_global_cloudflare_zone_id();
		if ( empty( $cloudflare_email ) || empty( $cloudflare_api_key ) || empty( $cloudflare_zone_id ) ) {
			return false;
		}

		self::$cf_setup = [
			'email'   => $cloudflare_email,
			'api_key' => $cloudflare_api_key,
			'zone_id' => $cloudflare_zone_id,
		];

		return self::$cf_setup;
	}

	public static function update_header_cache( $headers ) {
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- No need for nonce verification as we are using this for read-only purposes.
		if ( isset( $_GET['critical-css'] ) && preg_match( '/^skip\d{14}$/', sanitize_text_field( wp_unslash( $_GET['critical-css'] ) ) ) ) {
			$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
			$headers['Pragma']        = 'no-cache';
			$headers['Expires']       = 'Thu, 01 Jan 1970 00:00:00 GMT';
		}

		return $headers;
	}

	public static function clear_cloudflare_cache( $url = null ) {
		$cloudflare = self::get_cloudflare_setup();
		if ( ! $cloudflare ) {
			return;
		}

		$body = $url ? [ 'files' => [ esc_url_raw( $url ) ] ] : [ 'purge_everything' => true ];

		$response = wp_safe_remote_post(
			'https://api.cloudflare.com/client/v4/zones/' . $cloudflare['zone_id'] . '/purge_cache',
			[
				'headers' => [
					'X-Auth-Email' => $cloudflare['email'],
					'X-Auth-Key'   => $cloudflare['api_key'],
					'Content-Type' => 'application/json',
				],
				'body'    => wp_json_encode( $body ),
				'timeout' => 10,
			]
		);

		if ( is_wp_error( $response ) ) {
			Debug::ecc_log(
				[
					'step'  => 'clear_cloudflare_cache',
					'error' => $response->get_error_message(),
				]
			);
		} else {
			$code          = wp_remote_retrieve_response_code( $response );
			$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
			if ( 200 !== $code || empty( $response_body['success'] ) ) {
				Debug::ecc_log(
					[
						'step'  => 'clear_cloudflare_cache',
						'error' => $response_body,
					]
				);
			}
		}
	}
}
