<?php
namespace TotalTheme;

defined( 'ABSPATH' ) || exit;

/**
 * Adds custom CSS to the site from Customizer settings.
 *
 * @package TotalTheme
 * @version 5.4
 */
final class Inline_CSS {

	/**
	 * Instance.
	 *
	 * @access private
	 * @var object Class object.
	 */
	private static $instance;

	/**
	 * Create or retrieve the instance of our class.
	 */
	public static function instance() {
		if ( is_null( static::$instance ) ) {
			static::$instance = new self();
		}

		return static::$instance;
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Hook into actions and filters.
	 */
	public function init_hooks() {

		// Add custom CSS to head tag.
		add_action( 'wp_head', array( $this, 'ouput_css' ), 9999 );

		// Minify custom CSS on front-end only.
		// Note: Can't minify on backend or messes up the Custom CSS panel.
		if ( ! is_admin() && ! is_customize_preview() && apply_filters( 'wpex_minify_inline_css', true ) ) {
			add_filter( 'wp_get_custom_css', 'wpex_minify_css' );
		}

	}

	/**
	 * Add all custom CSS into the WP Header.
	 */
	public function ouput_css( $css = '' ) {

		/**
		 * Hook: wpex_hook_head_css.
		 *
		 * @todo Add and update all functions that hook into "wpex_head_css" filter to instead hook into here.
		 *
		ob_start();
			do_action( 'wpex_hook_head_css' );
		$css_action = ob_get_clean();

		if ( $css_action ) {
			$css .= $css . $css_action;
		}
		*/

		/**
		 * Filters the CSS added to the site head.
		 *
		 * @param string $css
		 */
		$css = apply_filters( 'wpex_head_css', $css );

		// Custom CSS panel => Add last after all filters to make sure it always overrides.
		// Deprecated in 4.0 - the theme now uses native WP additional css function for the custom css.
		if ( $custom_css = get_theme_mod( 'custom_css', null ) ) {
			$css .= '/*CUSTOM CSS*/' . $custom_css;
		}

		// Minify and output CSS in the wp_head.
		if ( ! empty( $css ) ) {

			// Sanitize output | important don't use esc_attr because it breaks quotes in custom fonts.
			$css = wp_strip_all_tags( wpex_minify_css( $css ) );

			// Echo output.
			// Don't rename #wpex-css or things will break !!! Important !!!
			echo '<style data-type="wpex-css" id="wpex-css">' . trim( $css ) . '</style>';

		}

	}

}