<?php
/**
 * This class handles CSS post message for Customizer previewer.
 *
 * @since 1.0.0
 */

namespace Seventhqueen\Typer\Customizer\Modules\Post_Message;

// Exit if accessed directly.
use Seventhqueen\Typer\Customizer\Helper;
use Seventhqueen\Typer\Customizer\Utils;
use function Seventhqueen\Typer\typer;

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

/**
 * Post message preview scripts.
 *
 * @since 1.0.0
 * @ignore
 * @access private
 *
 */
final class Module {

	/**
	 * Module activate condition.
	 *
	 * @since 1.0.0
	 *
	 * @return boolean Class active state.
	 */
	public static function active() {
		return class_exists( '\Kirki' );
	}

	/**
	 * Construct the class.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'customize_preview_init', [ $this, 'enqueue_preview_scripts' ] );
	}

	/**
	 * Enqueue preview styles and scripts.
	 *
	 * @since 1.0.0
	 */
	public function enqueue_preview_scripts() {
		wp_enqueue_script( 'typer-customizer-postmessage',
			Utils::get_assets_url() . '/js/post-message.js',
			[ 'jquery', 'kirki_auto_postmessage' ],
			typer()->get_asset_version( Utils::get_assets_path() . '/js/post-message.js' ),
			true
		);

		$settings = [];
		$fields = Helper::$fields;

		foreach ( $fields as $setting ) {
			if ( isset( $setting['transport'] ) && 'postMessage' === $setting['transport'] && isset( $setting['output'] ) && ! empty( $setting['output'] ) ) {
				$settings[] = $setting;
			}
		}

		wp_localize_script( 'typer-customizer-postmessage', 'typerPostMessage', [
			'settings'          => $settings,
			'responsiveDevices' => Helper::$responsive_devices,
		] );
	}
}
