<?php
namespace TotalTheme\Integration\WPBakery;

defined( 'ABSPATH' ) || exit;

final class Inline_CSS {

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

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

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_filter( 'wpex_head_css', __CLASS__ . '::add_css' );
	}

	/**
	 * Hook into wpex_head_css to add inline CSS for WPBakery.
	 */
	public static function add_css( $css ) {
		$wpbakery_css = self::generate_css();
		if ( $wpbakery_css ) {
			$css .= $wpbakery_css;
		}
		return $css;
	}

	/**
	 * Get template ID's that we need to load CSS for.
	 *
	 * @todo add needed style tag inline instead.
	 */
	public static function get_template_ids() {
		$ids = array();

		if ( wpex_is_woo_shop() ) {
			$ids[] = wpex_parse_obj_id( wc_get_page_id( 'shop' ) );
		}

		/**
		 * Filters the ID's to grab inline vc CSS from.
		 *
		 * @param array $ids
		 */
		$ids = (array) apply_filters( 'wpex_vc_css_ids', $ids );

		$ids = array_map( 'intval', $ids );

		if ( $ids ) {
			return array_unique( array_filter( $ids ) );
		}
	}

	/**
	 * Generate CSS.
	 */
	public static function generate_css() {
		$css = '';

		$template_ids = (array) self::get_template_ids();

		foreach ( $template_ids as $id ) {

			// Conditional checks, some CSS isn't necessarily needed globally.
			if ( function_exists( 'is_shop' ) && is_shop() ) {
				$condition = true; // Always return true for the shop
			} else {
				$condition = ( $id == wpex_get_current_post_id() ) ? false : true;
			}

			if ( $condition && $vc_css = get_post_meta( $id, '_wpb_shortcodes_custom_css', true ) ) {
				$css .= '/*VC META CSS*/' . $vc_css;
			}
		}

		return $css;
	}

}