<?php
/**
 * Xpro enqueue scripts
 *
 * @package Xpro
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'xpro_scripts' ) ) {
	/**
	 * Load theme's JavaScript and CSS sources.
	 */
	function xpro_scripts() {

		// Get the theme data.
		$dir_uri = get_template_directory_uri();

		//CSS
		wp_enqueue_style( 'bootstrap-grid', $dir_uri . '/assets/css/bootstrap-grid.min.css', null, '5.2.0' );

		if ( is_archive() || is_author() || is_category() || is_home() || is_single() || is_tag() || is_search() || is_active_sidebar( 'xpro-main-sidebar' ) ) {
			wp_enqueue_style( 'xpro-theme-blog', $dir_uri . '/assets/css/blog.min.css', null, XPRO_VERSION );
		}

		if ( class_exists( 'woocommerce' ) ) {
			wp_enqueue_style( 'xpro-theme-woocommerce', $dir_uri . '/assets/css/woocommerce.min.css', null, XPRO_VERSION );
		}

		wp_enqueue_style( 'xpro-theme-style', $dir_uri . '/assets/css/style.min.css', null, XPRO_VERSION );

		//JS
		wp_enqueue_script( 'xpro-theme-function', $dir_uri . '/assets/js/functions.min.js', array( 'jquery' ), XPRO_VERSION, true );

		wp_script_add_data( 'xpro-theme-function', 'async', true );

		if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
			wp_enqueue_script( 'comment-reply' );
		}

	}
}

add_action( 'wp_enqueue_scripts', 'xpro_scripts' );

/**
 * Enqueue supplemental block editor styles.
 */

add_action( 'enqueue_block_editor_assets', 'xpro_block_editor_styles', 1, 1 );

if ( ! function_exists( 'xpro_block_editor_styles' ) ) {

	function xpro_block_editor_styles() {

		// Enqueue the editor styles.
		wp_enqueue_style( 'xpro-block-editor-styles', get_theme_file_uri( '/admin/css/editor-style-block.css' ), array(), XPRO_VERSION, 'all' );

	}
}

/**
 * Load theme's JavaScript and CSS sources For Admin.
 */

add_action( 'customize_controls_enqueue_scripts', 'xpro_admin_scripts', 99 );

if ( ! function_exists( 'xpro_admin_scripts' ) ) {

	function xpro_admin_scripts() {
		wp_enqueue_style( 'xpro-theme-customizer', get_theme_file_uri( '/admin/css/customizer.css' ), array(), XPRO_VERSION, 'all' );

	}
}


/**
 * Generate custom css base on customizer settings
 */

if ( ! function_exists( 'xpro_generate_custom_css' ) ) {

	function xpro_generate_custom_css() {

		$output_css = '';
		ob_start();

		/* Include custom css */
		require_once XPRO_THEME_DIR . '/lib/customizer/customizer-output/custom-css.php';
		$output_css = ob_get_contents();

		ob_end_clean();

		// 1. Remove comments.
		$output_css = preg_replace( '#/\*.*?\*/#s', '', $output_css );
		// 2. Remove whitespace.
		$output_css = preg_replace( '/\s*([{}|:;,])\s+/', '$1', $output_css );
		// 3. Remove starting whitespace.
		$output_css = preg_replace( '/\s\s+(.*)/', '$1', $output_css );

		wp_add_inline_style( 'xpro-theme-style', $output_css );

	}
}

add_action( 'wp_enqueue_scripts', 'xpro_generate_custom_css', 999 );

