<?php

namespace EasyCriticalCSS;

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

class Critical_CSS_Server {
	public static function init() {
		add_filter( 'redirect_canonical', [ __CLASS__, 'prevent_trailing_slash_redirect' ], 10, 2 );

		add_action( 'init', [ __CLASS__, 'register_css_endpoints' ] );
		add_action( 'template_redirect', [ __CLASS__, 'serve_css_file' ] );
	}

	public static function prevent_trailing_slash_redirect( $redirect_url, $requested_url ) {
		// Stop WP early so the CSS is output as the file.
		if ( preg_match( '/easy-(critical|remaining|secondary|manual)-css\/[a-f0-9]+-\d+\.css$/', $requested_url ) ) {
			return false;
		}

		return $redirect_url;
	}

	public static function register_css_endpoints() {
		add_rewrite_rule( '^easy-critical-css/([a-f0-9]+)-(\d+)\.css$', 'index.php?easy_critical_css_id=$matches[1]&timestamp=$matches[2]', 'top' );
		add_rewrite_tag( '%easy_critical_css_id%', '([a-f0-9]+)' );

		add_rewrite_rule( '^easy-remaining-css/([a-f0-9]+)-(\d+)\.css$', 'index.php?easy_remaining_css_id=$matches[1]&timestamp=$matches[2]', 'top' );
		add_rewrite_tag( '%easy_remaining_css_id%', '([a-f0-9]+)' );

		add_rewrite_rule( '^easy-secondary-css/([a-f0-9]+)-(\d+)\.css$', 'index.php?easy_secondary_css_id=$matches[1]&timestamp=$matches[2]', 'top' );
		add_rewrite_tag( '%easy_secondary_css_id%', '([a-f0-9]+)' );

		add_rewrite_tag( '%timestamp%', '(\d+)' );
	}

	public static function serve_css_file() {
		$critical  = get_query_var( 'easy_critical_css_id' );
		$remaining = get_query_var( 'easy_remaining_css_id' );
		$secondary = get_query_var( 'easy_secondary_css_id' );
		$manual    = get_query_var( 'easy_manual_css_id' );

		switch ( true ) {
			case $critical:
				$css_output = Critical_CSS::get_critical_css( $critical );
				break;
			case $remaining:
				$css_output = Critical_CSS::get_remaining_css( $remaining );
				break;
			case $secondary:
				$css_output = Critical_CSS::get_secondary_css( $secondary );
				break;
			case $manual:
				$css_output = Settings::get_individual_manual_secondary_css( $manual );
				break;
			default:
				return;
		}

		header( 'Content-Type: text/css' );
		// We escape through a custom CSS escaping function instead of a standard WP escaping function because '>' is needed for CSS rules, and tags are needed fro inline SVGs.
		echo Helpers::esc_css( $css_output ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}
}
