<?php

// Exit if accessed directly.
if (!defined('ABSPATH')) {
	exit;
}

//////////////////////////////////////////////////////////////////
// Functions to render conditional styles
//////////////////////////////////////////////////////////////////
$global_gs_options = get_option('gspb_global_settings');
function gspb_get_breakpoints()
{
	// defaults breakpoints.
	$gsbp_breakpoints = apply_filters('greenshift_responsive_breakpoints', array(
		'mobile' 	=> 576,
		'tablet' 	=> 768,
		'desktop' =>  992
	));

	$gs_settings = get_option('gspb_global_settings');

	if (!empty($gs_settings)) {
		$gsbp_custom_breakpoints = (!empty($gs_settings['breakpoints'])) ? $gs_settings['breakpoints'] : '';

		if (!empty($gsbp_custom_breakpoints['mobile'])) {
			$gsbp_breakpoints['mobile'] = trim($gsbp_custom_breakpoints['mobile']);
		}

		if (!empty($gsbp_custom_breakpoints['tablet'])) {
			$gsbp_breakpoints['tablet'] = trim($gsbp_custom_breakpoints['tablet']);
		}

		if (!empty($gsbp_custom_breakpoints['desktop'])) {
			$gsbp_breakpoints['desktop'] = trim($gsbp_custom_breakpoints['desktop']);
		}
	}

	return array(
		'mobile' 			=> intval($gsbp_breakpoints['mobile']),
		'mobile_down' 		=> intval($gsbp_breakpoints['mobile']) - 0.02,
		'tablet' 			=> intval($gsbp_breakpoints['tablet']),
		'tablet_down' 		=> intval($gsbp_breakpoints['tablet']) - 0.02,
		'desktop' 			=> intval($gsbp_breakpoints['desktop']),
		'desktop_down'		=> intval($gsbp_breakpoints['desktop']) - 0.02,
	);
}

function gspb_get_final_css($gspb_css_content)
{
	$get_breakpoints = gspb_get_breakpoints();

	if ($get_breakpoints['mobile'] != 576) {
		$gspb_css_content = str_replace('@media (max-width: 575.98px)', '@media (max-width: ' . $get_breakpoints["mobile_down"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (min-width: 576px)', '@media (min-width: ' . $get_breakpoints["mobile"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (max-width:575.98px)', '@media (max-width: ' . $get_breakpoints["mobile_down"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (min-width:576px)', '@media (min-width: ' . $get_breakpoints["mobile"] . 'px)', $gspb_css_content);
	}

	if ($get_breakpoints['tablet'] != 768) {
		$gspb_css_content = str_replace('and (max-width: 767.98px)', 'and (max-width: ' . $get_breakpoints["tablet_down"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (min-width: 768px)', '@media (min-width: ' . $get_breakpoints["tablet"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('and (max-width:767.98px)', 'and (max-width: ' . $get_breakpoints["tablet_down"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (min-width:768px)', '@media (min-width: ' . $get_breakpoints["tablet"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (max-width:767.98px)', '@media (max-width: ' . $get_breakpoints["tablet_down"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (max-width: 767.98px)', '@media (max-width: ' . $get_breakpoints["tablet_down"] . 'px)', $gspb_css_content);
	}

	if ($get_breakpoints['desktop'] != 992) {
		$gspb_css_content = str_replace('and (max-width: 991.98px)', 'and (max-width: ' . $get_breakpoints["desktop_down"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('and (max-width:991.98px)', 'and (max-width: ' . $get_breakpoints["desktop_down"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (min-width: 992px)', '@media (min-width: ' . $get_breakpoints["desktop"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (min-width:992px)', '@media (min-width: ' . $get_breakpoints["desktop"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (max-width:991.98px)', '@media (max-width: ' . $get_breakpoints["desktop_down"] . 'px)', $gspb_css_content);
		$gspb_css_content = str_replace('@media (max-width: 991.98px)', '@media (max-width: ' . $get_breakpoints["desktop_down"] . 'px)', $gspb_css_content);
	}

	return apply_filters('gspb_get_final_css', $gspb_css_content);
}

//////////////////////////////////////////////////////////////////
// CSS minify
//////////////////////////////////////////////////////////////////
function gspb_quick_minify_css($css)
{
	$css = preg_replace('/\s+/', ' ', $css);
	$css = preg_replace('/\/\*[^\!](.*?)\*\//', '', $css);
	$css = preg_replace('/(,|:|;|\{|}) /', '$1', $css);
	$css = preg_replace('/ (,|;|\{|})/', '$1', $css);
	$css = preg_replace('/(:| )0\.([0-9]+)(%|em|ex|px|in|cm|mm|pt|pc)/i', '${1}.${2}${3}', $css);
	//$css = preg_replace( '/(:| )(\.?)0(%|em|ex|px|in|cm|mm|pt|pc)/i', '${1}0', $css );
	return trim($css);
}


//////////////////////////////////////////////////////////////////
// Functions to render conditional scripts
//////////////////////////////////////////////////////////////////

// Hook: Frontend assets.
add_action('init', 'gspb_greenShift_register_scripts_blocks');
add_filter('render_block', 'gspb_greenShift_block_script_assets', 10, 2);
add_filter('register_block_type_args', 'gspb_enable_full_align_for_html_block', 10, 2);
function gspb_enable_full_align_for_html_block($args, $block_type)
{
	if ('core/html' !== $block_type) {
		return $args;
	}

	if (empty($args['supports']) || !is_array($args['supports'])) {
		$args['supports'] = array();
	}

	$args['supports']['align'] = array('wide', 'full');

	return $args;
}

$enable_head_inline = !empty($global_gs_options['enable_head_inline']) ? $global_gs_options['enable_head_inline'] : '';
//$enable_head_inline = function_exists('wp_is_block_theme') && wp_is_block_theme();

if($enable_head_inline){
	add_filter('render_block', 'gspb_greenShift_block_inline_head', 10, 2);
}else{
	add_filter('render_block', 'gspb_greenShift_block_inline_styles', 10, 2);
}

function gspb_greenShift_register_scripts_blocks(){

	wp_register_script( 'gspb-js-blocks', '', array(), '1.0', true );

	wp_register_script(
		'jslazyload',
		GL_DIR_URL . 'libs/lazyloadjs/lazyload-scripts.min.js',
		array(),
		'1.0',
		true
	);

	wp_register_script(
		'gspb-cook',
		GL_DIR_URL . 'libs/cook/index.js',
		array(),
		'1.0',
		true
	);

	wp_register_script(
		'gsf-filter-block',
		GL_DIR_URL . 'libs/filter-block/jsf.js',
		array(),
		'1.0',
		true
	);

	// aos script
	wp_register_script(
		'greenShift-aos-lib',
		GL_DIR_URL . 'libs/aos/aoslight.js',
		array(),
		'4.0',
		true
	);

	wp_register_script(
		'greenShift-aos-lib-clip',
		GL_DIR_URL . 'libs/aos/aoslightclip.js',
		array(),
		'4.0',
		true
	);

	// swiper
	wp_register_script(
		'gspb-swiper',
		GL_DIR_URL . 'libs/swiper/swiper-bundle.min.js',
		array(),
		'9.3.3',
		true
	);
	wp_register_script(
		'gs-swiper-init',
		GL_DIR_URL . 'libs/swiper/init.js',
		array(),
		'8.9.9.5',
		true
	);
	wp_localize_script(
		'gs-swiper-init',
		'gs_swiper',
		array(
			'breakpoints' => gspb_get_breakpoints()
		)
	);
	wp_register_script(
		'gs-swiper-loader',
		GL_DIR_URL . 'libs/swiper/loader.js',
		array(),
		'7.3.5',
		true
	);
	wp_localize_script(
		'gs-swiper-loader',
		'gs_swiper_params',
		array(
			'pluginURL' => GL_DIR_URL,
			'breakpoints' => gspb_get_breakpoints()
		)
	);
	wp_register_style('gspb-swiper', GL_DIR_URL . 'libs/swiper/swiper-bundle.min.css', array(), '8.4');

	wp_register_script(
		'gspb-chartinit',
		GL_DIR_URL . 'libs/apexchart/init.js',
		array(),
		'1.2',
		true
	);
	wp_localize_script(
		'gspb-chartinit',
		'gs_chart_params',
		array(
			'pluginURL' => GL_DIR_URL
		)
	);

	wp_register_script(
		'gspb-lightbox',
		GL_DIR_URL . 'libs/greenlightbox/index.js',
		array(),
		'1.3',
		true
	);

	wp_register_script(
		'gspb-greenpanel',
		GL_DIR_URL . 'libs/greenpanel/index.js',
		array(),
		'2.0',
		true
	);

	wp_register_script(
		'greenshift-split-text',
		GL_DIR_URL . 'libs/utility/splittext.js',
		array(),
		'1.0',
		true
	);

	wp_register_script(
		'greenshift-scroll-scrub',
		GL_DIR_URL . 'libs/utility/scroll-scrub.js',
		array(),
		'1.2',
		true
	);

	wp_register_script(
		'scroll-view-polyfill',
		GL_DIR_URL . 'libs/utility/scroll-timeline-init.js',
		array(),
		'1.0',
		true
	);
	wp_localize_script(
		'scroll-view-polyfill',
		'gspb_scroll_params',
		array(
			'gspbLibraryUrl' => GL_DIR_URL
		)
	);

	wp_register_script(
		'anchor-polyfill',
		GL_DIR_URL . 'libs/utility/anchor-init.js',
		array(),
		'1.1',
		true
	);
	wp_localize_script(
		'anchor-polyfill',
		'gspb_anchor_params',
		array(
			'gspbLibraryUrl' => GL_DIR_URL
		)
	);

	wp_register_script(
		'gspb_api',
		GL_DIR_URL . 'libs/api/index.js',
		array(),
		'1.9',
		true
	);

	// Add nonce to gspb_api script
	wp_localize_script('gspb_api', 'gspbApiSettings', array(
		'nonce' => wp_create_nonce('wp_rest'),
	));

	wp_register_script(
		'gspb_interactions',
		GL_DIR_URL . 'libs/interactionlayer/index.js',
		array(),
		'5.0',
		true
	);

	wp_register_script(
		'gspb_motion_spring',
		GL_DIR_URL . 'build/gspbMotionSpring.js',
		array(),
		'12.6',
		true
	);

	wp_register_script(
		'gspb_motion_one',
		GL_DIR_URL . 'build/gspbMotion.js',
		array(),
		'12.6',
		true
	);

	wp_register_script(
		'gspb-apiconnector',
		GL_DIR_URL . 'libs/api-connector/index.js',
		array(),
		'1.2',
		true
	);

	wp_register_script(
		'gspbajaxpagination',
		GL_DIR_URL . 'libs/filterpanel/ajaxpagination.js',
		array(),
		'2.4',
		true
	);

	wp_register_script(
		'gsap-animation',
		GL_DIR_URL . 'libs/gsap/gsap.min.js',
		array(),
		'3.12.2',
		true
	);
	// scroll trigger
	wp_register_script(
		'gsap-scrolltrigger',
		GL_DIR_URL . 'libs/gsap/ScrollTrigger.min.js',
		array('gsap-animation'),
		'3.12.2',
		true
	);

	wp_register_script(
		'gsapsplittext',
		GL_DIR_URL . 'libs/gsap/SplitText.min.js',
		array('gsap-animation'),
		'3.12.2',
		true
	);

	wp_register_script(
		'gsapsvgdraw',
		GL_DIR_URL . 'libs/gsap/DrawSVGPlugin.min.js',
		array('gsap-animation'),
		'3.12.2',
		true
	);
	wp_register_script(
		'gsapsvgmorph',
		GL_DIR_URL . 'libs/gsap/MorphSVGPlugin.min.js',
		array('gsap-animation'),
		'3.12.2',
		true
	);
	wp_register_script(
		'gsapsvgpath',
		GL_DIR_URL . 'libs/gsap/MotionPathPlugin.min.js',
		array('gsap-animation'),
		'3.12.2',
		true
	);
	wp_register_script(
		'gsapcustomease',
		GL_DIR_URL . 'libs/gsap/CustomEase.min.js',
		array(),
		'3.12.2',
		true
	);

	// gsap init
	wp_register_script(
		'gsap-animation-init',
		GL_DIR_URL . 'libs/gsap/gsap-init.js',
		array('gsap-animation'),
		'4.9',
		true
	);

	//gsap mousefollow init
	wp_register_script(
		'gsap-mousefollow-init',
		GL_DIR_URL . 'libs/gsap/gsap-mousefollow.js',
		array('gsap-animation'),
		'3.12.2',
		true
	);

	// Filters

	wp_register_script(
		'gspb-filterblock',
		GL_DIR_URL . 'libs/filter-block/filter-index.js',
		array(),
		'2.3',
		true
	);

	wp_register_script(
		'gspb-map-filter',
		GL_DIR_URL . 'libs/map-filter/view.js',
		array(),
		'1.1.0',
		true
	);
	wp_register_script( 'gsmapfilterpin', '', [], '', true );


	// gspb library css
	wp_register_style(
		'greenShift-library-editor',
		GL_DIR_URL . 'build/gspbLibrary.css',
		'',
		'12.9'
	);
	wp_register_style(
		'greenShift-block-css', // Handle.
		GL_DIR_URL . 'build/index.css', // Block editor CSS.
		array('greenShift-library-editor', 'wp-edit-blocks'),
		'12.9'
	);
	wp_register_style(
		'greenShift-stylebook-css', // Handle.
		GL_DIR_URL . 'build/gspbStylebook.css', // Block editor CSS.
		array(),
		'12.9'
	);
	wp_register_style(
		'greenShift-admin-css', // Handle.
		GL_DIR_URL . 'templates/admin/style.css', // admin css
		array(),
		'12.9'
	);

	//Script for ajax reusable loading
	wp_register_script('gselajaxloader',  GL_DIR_URL . 'libs/reusable/index.js', array(), '2.4', true);
	wp_register_style('gspreloadercss',  GL_DIR_URL . 'libs/reusable/preloader.css', array(), '1.2');
	wp_register_script( 'greenshiftloop', '', [], '', true );


	//register blocks on server side with block.json
	register_block_type(__DIR__ . '/blockrender/swiper');
	register_block_type(__DIR__ . '/blockrender/swipe');


	// admin settings scripts and styles
	wp_register_script('gsadminsettings',  GL_DIR_URL . 'libs/admin/settings.js', array(), '1.2', true);
	wp_register_style('gsadminsettings',  GL_DIR_URL . 'libs/admin/settings.css', array(), '1.1');
	wp_localize_script(
		'gsadminsettings',
		'greenShift_params',
		array(
			'ajaxUrl' => admin_url('admin-ajax.php')
		)
	);

	// Register Stylebook
	$blocktemplate = array(
		array( 'greenshift-blocks/stylebook', array() ),
	);
	$args = array(
		'public'                =>	true,
		'show_in_rest'          =>  true,
		'hierarchical'          =>  false,
		'exclude_from_search'	=>	true,
		'publicly_queryable' 	=>  false,
		'show_in_menu'			=> 	false,
		'show_in_nav_menus'		=> 	false,
		'show_in_admin_bar'		=> 	false,
		'supports'              =>  array( 'editor' ),
		'has_archive'           =>  false,
		'delete_with_user'      =>  false,	
		'template' 				=>  $blocktemplate,
		'template_lock'         =>  'all',
		'label'    				=>  esc_html__( 'GreenShift Stylebook', 'gl-page-builder' ),
	);
	register_post_type( 'gspbstylebook', $args );

}

//////////////////////////////////////////////////////////////////
// Register server side
//////////////////////////////////////////////////////////////////
require_once GL_DIR_PATH . 'query.php';
require_once GL_DIR_PATH . 'rest.php';
require_once GL_DIR_PATH . 'filterindexer.php';
require_once GL_DIR_PATH . 'integrations.php';
require_once GL_DIR_PATH . 'visibility.php';


require_once GL_DIR_PATH . 'blockrender/element/block.php';
require_once GL_DIR_PATH . 'blockrender/querygrid/block.php';
require_once GL_DIR_PATH . 'blockrender/repeater/block.php';
require_once GL_DIR_PATH . 'blockrender/filter-block/block.php';
require_once GL_DIR_PATH . 'blockrender/filter-results-count/block.php';
require_once GL_DIR_PATH . 'blockrender/filter-sorting/block.php';

function gspb_greenShift_block_script_assets($html, $block)
{
	// phpcs:ignore

	//Main styles for blocks are loaded via Redux. Can be found in src/customJS/editor/store/index.js

	if (!is_admin()) {

		$blockname = $block['blockName'];

		// looking for swiper
		if ($blockname === 'greenshift-blocks/swiper') {
			if (!empty($block['attrs']['smartloader'])) {
				wp_enqueue_script('gs-swiper-loader');
			} else {
				wp_enqueue_script('gspb-swiper');
				wp_enqueue_script('gs-swiper-init');
			}
		}

		else if ($blockname == 'greenshift-blocks/filter-block') {
			// Store pre-select parameters for filter block
			$pre_select = array();

			if ( is_tax() || is_tag() || is_category()) {
				$category = get_queried_object();
				$pre_select['currentTaxonomoy'] = $category->slug;
			}

			$rest_vars = array(
				'rest_url'             => esc_url_raw( rest_url( 'greenshift/v1/get-gs-posts/' ) ),
				'indexing_rest_url'    => esc_url_raw( rest_url( 'greenshift/v1/indexer-count/' ) ),
				'refresh_filterchips'  => esc_url_raw( rest_url( 'greenshift/v1/refresh-filterchips/' ) ),
				'map_filter_refresher' => esc_url_raw( rest_url( 'greenshift/v1/map-filter-refresher/' ) ),
				'preSelect'            => $pre_select,
			);

			wp_localize_script( 'gspb-filterblock', 'RESTVARS', $rest_vars );
			wp_enqueue_script( 'gspb-filterblock' );
		}
		else if ( $blockname == 'greenshift-blocks/map-filter' ) {

			$map_provider = !empty($block['attrs']['mapTileProvider']) ? $block['attrs']['mapTileProvider'] : 'leaflet';
			if($map_provider == 'google') {
				$gspb_global_settings = get_option( 'gspb_global_settings', array() );
				$google_maps_api_key  = isset( $gspb_global_settings['googleapi'] ) ? $gspb_global_settings['googleapi'] : '';
				wp_enqueue_script( 'google-maps', 'https://maps.googleapis.com/maps/api/js?key=' . $google_maps_api_key . '&libraries=marker', array(), null, true );
			}else{
				wp_enqueue_script( 'leaflet-js', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js', array(), '1.9.4', true );
				wp_enqueue_style( 'leaflet-css', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css', array(), '1.9.4' );
			}
			wp_enqueue_script( 'gspb-map-filter' );

			$rest_vars = array(
				'map_pins_onload_url' => esc_url_raw( rest_url( 'greenshift/v1/map-pins-on-load/' ) ),
				'map_pin_click'       => esc_url_raw( rest_url( 'greenshift/v1/map-pin-click/' ) )
			);
			if($map_provider == 'google') {
				$rest_vars['google_map_key'] = $google_maps_api_key;
			}
			wp_localize_script( 'gspb-map-filter', 'REST_OBJ', $rest_vars );

			$block_instance = ( is_array( $block ) ) ? $block : $block->parsed_block;
			$json_block     = rawurlencode( json_encode( $block_instance['innerBlocks'] ) );
			$html           = str_replace( 'action=""', 'action="' . home_url() . '"', $html );

			wp_enqueue_script( 'gsmapfilterpin' );

			$blockid = 'gspb-map-filter-pin-' . $block['attrs']['id'];
			$blockid = str_replace( '-', '_', $blockid );

			wp_add_inline_script( 'gsmapfilterpin', 'var ' . $blockid . '="' . $json_block . '"', 'before' );
		}


		if (!empty($block['attrs']['animation']['usegsap'])) {
			wp_enqueue_script('gsap-animation');
			wp_enqueue_script('gsap-scrolltrigger');
			if (!empty($block['attrs']['animation']['type']) && $block['attrs']['animation']['type'] == 'text_transformations') {
				wp_enqueue_script('gsapsplittext');
			}
			if (!empty($block['attrs']['animation']['type']) && $block['attrs']['animation']['type'] == 'svg' && !empty($block['attrs']['animation']['svg_draw']) && $block['attrs']['animation']['svg_draw'] == true) {
				wp_enqueue_script('gsapsvgdraw');
			}
			if (!empty($block['attrs']['animation']['type']) && $block['attrs']['animation']['type'] == 'svg' && !empty($block['attrs']['animation']['path'])) {
				wp_enqueue_script('gsapsvgpath');
			}
			wp_enqueue_script('gsap-animation-init');
		}



		// aos script
		if (!empty($block['attrs']['animation']['type']) && empty($block['attrs']['animation']['usegsap']) && empty($block['attrs']['animation']['onclass_active'])) {
			if(!empty($block['attrs']['animation']['type']) && ($block['attrs']['animation']['type'] == 'display-in' || $block['attrs']['animation']['type'] == 'display-in-slide' || $block['attrs']['animation']['type'] == 'display-in-zoom' || $block['attrs']['animation']['type'] == 'custom' || $block['attrs']['animation']['type'] == 'clip-down' || $block['attrs']['animation']['type'] == 'clip-up' || $block['attrs']['animation']['type'] == 'clip-left' || $block['attrs']['animation']['type'] == 'clip-right' || $block['attrs']['animation']['type'] == 'slide-left' || $block['attrs']['animation']['type'] == 'slide-right' || $block['attrs']['animation']['type'] == 'slide-top' || $block['attrs']['animation']['type'] == 'slide-bottom' )){
				wp_enqueue_script('greenShift-aos-lib-clip');
			}else{
				wp_enqueue_script('greenShift-aos-lib');
			}
			if(!empty($block['attrs']['animation']['onscrub'])){
				wp_enqueue_script('greenshift-scroll-scrub');
			}
			if(!empty($block['attrs']['animation']['onsplit'])){
				wp_enqueue_script('greenshift-split-text');
			}
		}

		//Load polyfills from classes
		if (!empty($block['attrs']['dynamicGClasses'])) {
			foreach ($block['attrs']['dynamicGClasses'] as $class) {
				if(!empty($class['attributes']['styleAttributes']['animationTimeline'])){
					wp_enqueue_script('scroll-view-polyfill');
				}
				if(!empty($class['attributes']['styleAttributes']['anchorName'])){
					wp_enqueue_script('anchor-polyfill');
				}
				if(!empty($class['selectors'])){
					foreach($class['selectors'] as $selector){
						if(!empty($selector['attributes']['styleAttributes']['animationTimeline'])){
							wp_enqueue_script('scroll-view-polyfill');
						}
						if(!empty($selector['attributes']['styleAttributes']['anchorName'])){
							wp_enqueue_script('anchor-polyfill');
						}
					}
				}
			}
		}


		if(!empty($block['attrs']['interactionLayers'])){
			//Animations
			foreach($block['attrs']['interactionLayers'] as $layer){
				$actions = $layer['actions'];
				if(!empty($actions)){
					foreach($actions as $action){
						if(!empty($action['actionname']) && $action['actionname'] == 'animation'){
							wp_enqueue_script('gspb_motion_one');
							if(!empty($action['aprops']) && is_array($action['aprops'])){
								foreach($action['aprops'] as $prop){
									if(!empty($prop['type']) && $prop['type'] == 'easing' && !empty($prop['value']) && $prop['value'] == 'spring'){
										wp_enqueue_script('gspb_motion_spring');
									}
								}
							}
						}
						if(!empty($action['actionname']) && $action['actionname'] == 'customapi'){
							wp_enqueue_script('gspb_api');
						}
					}
				}
			}
			//Interactions script
			wp_enqueue_script('gspb_interactions');

			//Other scripts
			foreach($block['attrs']['interactionLayers'] as $layer){
				$actions = $layer['actions'];
				if(!empty($actions)){
					foreach($actions as $action){
						if(!empty($action['actionname']) && $action['actionname'] == 'lightbox'){
							wp_enqueue_script('gspb-lightbox');
						}
						if(!empty($action['actionname']) && ($action['actionname'] == 'panel' || $action['actionname'] == 'popup')){
							wp_enqueue_script('gspb-greenpanel');
						}
						if(!empty($action['actionname']) && ($action['actionname'] == 'popover')){
							wp_add_inline_script('gspb_interactions', '
							let popovers = document.querySelectorAll("[popover-control]");
							if(popovers && popovers.length > 0){
								popovers.forEach(popover => {
									let actions = popover.getAttribute("data-gspbactions");
									let trigger = "";
									if(actions){
										actions = JSON.parse(actions);
										actions.forEach(action => {
											if(action?.actions){
												action.actions.forEach(subaction => {
													if(subaction?.actionname === "popover" && action?.triggerData?.trigger){
														trigger = action.triggerData.trigger;
													}
												});
											}
										});
									}
									let targetselector = popover.getAttribute("popover-control");
									let target = document.getElementById(targetselector);
									if(trigger == "mouse-enter"){
										popover.addEventListener("mouseleave", (event) => {
											popover.classList.remove("gs-popover-open");
											if(target){
												target.classList.remove("active");
												target.hidePopover();
											}
										});
										let windowWidth = window.innerWidth;
										if(windowWidth < 768){
											popover.addEventListener("click", (event) => {
												popover.classList.toggle("gs-popover-open");
												if(target){
													target.classList.toggle("active");
													target.togglePopover();
												}
											});
										}
									}
									document.addEventListener("keydown", (event) => {
										if(event.key === "Escape"){
											popover.classList.remove("gs-popover-open");
											if(target){
												target.classList.remove("active");
												target.hidePopover();
											}
										}
									});
								});
							}
							');
						}
						if(!empty($action['selector']) && $blockname != 'greenshift-blocks/element'){
							$name = $action['selector'];
							
							if(strpos($name, 'ref-') !== false){
								$id = str_replace('ref-', '', $name);
								$id = (int)$id;
								$post = get_post($id);
								if($post){
									$settings = new GSPB_GreenLight_Settings;
									$post_content = $settings->gspb_template_shortcode_function(array('id' => $id));
									$random_id = 'gspb'.wp_generate_uuid4();
									$html = str_replace($name, '#'.$random_id, $html);
									$post_content = str_replace($name, $random_id, $post_content);
									$html = $html . $post_content;
								}
							}
						}
					}
				}
			}
		}
	}

	return $html;
}
function gspb_greenShift_block_inline_styles($html, $block){
	if (!is_admin()) {

		if (!empty($block['attrs']['dynamicGClasses'])) {
			foreach ($block['attrs']['dynamicGClasses'] as $class) {
				if(!empty($class['type'])){
					$type = $class['type'];
					if($type == 'preset' && !empty($class['value'])){
						$css = greenshift_get_style_from_class_array($class['value'], $type, $inline = true);
						if($css){
							$class_style = $css;
							$class_style = gspb_get_final_css($class_style);
							$class_style = htmlspecialchars_decode($class_style);
							$class_style = '<style>' . wp_strip_all_tags($class_style) . '</style>';
							$html = $html . $class_style;
						}
					}
				}
			}
		}

		if (!empty($block['attrs']['inlineCssStyles']) || ($block['blockName'] == 'core/block' && !empty($block['attrs']['ref'])) || !empty($block['attrs']['CSSRender']) ) {
			if($block['blockName'] == 'core/block' && !empty($block['attrs']['ref'])){
				$dynamic_style = get_post_meta((int)$block['attrs']['ref'], '_gspb_post_css', true);
				$dynamic_style = apply_filters('gspb_reusable_inline_styles', $dynamic_style);
			} else if(!empty($block['attrs']['CSSRender'])){
				$dynamic_style = '';
				if(!empty($block['attrs']['styleAttributes']) && !empty($block['attrs']['localId'])){
					$dynamic_style = gspb_render_style_attributes($block['attrs']['styleAttributes'], '.'.$block['attrs']['localId'], '', isset($block['attrs']['enableSpecificity']) ? $block['attrs']['enableSpecificity'] : false);
				}
				if(!empty($block['attrs']['dynamicGClasses'])){
					foreach ($block['attrs']['dynamicGClasses'] as $class) {
						if(!empty($class['type']) && $class['type'] == 'local'){
							if(!empty($class['css'])){
								$dynamic_style .= $class['css'];
							}
							if(!empty($class['selectors'])){
								foreach ($class['selectors'] as $sub_selector) {
									if(!empty($sub_selector['css'])){
										$dynamic_style .= $sub_selector['css'];
									}
								}
							}
						}
					}
				}
			} else{
				$dynamic_style = $block['attrs']['inlineCssStyles'];
			}
			$dynamic_style = gspb_get_final_css($dynamic_style);
			$dynamic_style = gspb_quick_minify_css($dynamic_style);
			$dynamic_style = htmlspecialchars_decode($dynamic_style);
			if (function_exists('GSPB_make_dynamic_image') && !empty($block['attrs']['background']['dynamicEnable'])) {
				$dynamic_style = GSPB_make_dynamic_image($dynamic_style, $block['attrs'], $block, $block['attrs']['background'], $block['attrs']['background']['image']);
			}
			$dynamic_style = '<style>' . wp_strip_all_tags($dynamic_style) . '</style>';
			$html = $dynamic_style . $html;
		}
	}
	return $html;
}
function gspb_greenShift_block_inline_head($html, $block){
	if (!is_admin()) {

		if (!empty($block['attrs']['dynamicGClasses'])) {
			foreach ($block['attrs']['dynamicGClasses'] as $class) {
				if(!empty($class['type'])){
					$type = $class['type'];
					if(($type == 'preset' || $type == 'global') && !empty($class['value'])){
						$css = greenshift_get_style_from_class_array($class['value'], $type, $inline = false);
						if($css){
							// Decode entities first, then sanitize to prevent entity-encoded XSS
							$css = htmlspecialchars_decode($css);
							$class_style = '<style>' . wp_strip_all_tags($css) . '</style>';
							$class_style = gspb_get_final_css($class_style);
							$html = $html . $class_style;
						}
					}
				}
			}
		}

		if (!empty($block['attrs']['inlineCssStyles']) || ($block['blockName'] == 'core/block' && !empty($block['attrs']['ref'])) || !empty($block['attrs']['CSSRender']) ) {
			$styleStore = GreenShiftStyleStore::getInstance();
			if($block['blockName'] == 'core/block' && !empty($block['attrs']['ref'])){
				$dynamic_style = get_post_meta((int)$block['attrs']['ref'], '_gspb_post_css', true);
			}else if(!empty($block['attrs']['CSSRender'])){
				$dynamic_style = '';
				if(!empty($block['attrs']['styleAttributes']) && !empty($block['attrs']['localId'])){
					$dynamic_style = gspb_render_style_attributes($block['attrs']['styleAttributes'], '.'.$block['attrs']['localId'], '', isset($block['attrs']['enableSpecificity']) ? $block['attrs']['enableSpecificity'] : false);
				}
				if(!empty($block['attrs']['dynamicGClasses'])){
					foreach ($block['attrs']['dynamicGClasses'] as $class) {
						if(!empty($class['type']) && $class['type'] == 'local'){
							if(!empty($class['css'])){
								$dynamic_style .= $class['css'];
							}
							if(!empty($class['selectors'])){
								foreach ($class['selectors'] as $sub_selector) {
									if(!empty($sub_selector['css'])){
										$dynamic_style .= $sub_selector['css'];
									}
								}
							}
						}
					}
				}
			}else{
				// Decode entities first, then sanitize to prevent entity-encoded XSS
				$dynamic_style = htmlspecialchars_decode($block['attrs']['inlineCssStyles']);
				$dynamic_style = wp_strip_all_tags($dynamic_style);
			}
			$dynamic_style = gspb_get_final_css($dynamic_style);
			$dynamic_style = gspb_quick_minify_css($dynamic_style);
			if (function_exists('GSPB_make_dynamic_image') && !empty($block['attrs']['background']['dynamicEnable'])) {
				$dynamic_style = GSPB_make_dynamic_image($dynamic_style, $block['attrs'], $block, $block['attrs']['background'], $block['attrs']['background']['image']);
			}
			if($block['blockName'] == 'core/block' && !empty($block['attrs']['ref'])){
				$styleStore->addClassStyle('ref_'.greenshift_sanitize_id_key($block['attrs']['ref']), $dynamic_style);
			}else{
				$styleStore->addClassStyle(greenshift_sanitize_id_key($block['attrs']['id']), $dynamic_style);
			}
			//echo $styleStore->getStyles();
		}
	}
	return $html;
}

//////////////////////////////////////////////////////////////////
// Enqueue Gutenberg block assets for backend editor.
//////////////////////////////////////////////////////////////////



// Hook: Editor assets.
add_action('enqueue_block_editor_assets', 'gspb_greenShift_editor_assets');

function gspb_greenShift_editor_assets()
{
	// phpcs:ignor

	$index_asset_file = include(GL_DIR_PATH . 'build/index.asset.php');
	$library_asset_file = include(GL_DIR_PATH . 'build/gspbLibrary.asset.php');

	wp_register_script(
		'greenShift-site-editor-js',
		GL_DIR_URL . 'build/gspbSiteEditor.js',
		array('greenShift-library-script','wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-data', 'wp-plugins'),
		$library_asset_file['version'],
		false
	);
	wp_set_script_translations('greenShift-site-editor-js', 'gl-page-builder');
	wp_enqueue_script('greenShift-site-editor-js');

	// gspb library script
	wp_register_script(
		'greenShift-library-script',
		GL_DIR_URL . 'build/gspbLibrary.js',
		array('wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-data', 'wp-plugins'),
		$library_asset_file['version'],
		false
	);
	wp_set_script_translations('greenShift-library-script', 'gl-page-builder');

	// Custom Editor JavaScript
	wp_register_script(
		'greenShift-editor-js',
		GL_DIR_URL . 'build/gspbCustomEditor.js',
		array('greenShift-library-script', 'jquery', 'wp-data', 'wp-element'),
		$index_asset_file['version'],
		true
	);
	wp_set_script_translations('greenShift-editor-js', 'gl-page-builder');

	$gspb_css_save = get_option('gspb_css_save');
	$sitesettings = get_option('gspb_global_settings');
	$row = (!empty($sitesettings['breakpoints']['row'])) ? (int)$sitesettings['breakpoints']['row'] : 1200;
	$localfont = (!empty($sitesettings['localfont'])) ? $sitesettings['localfont'] : array();
	$googleapi = (!empty($sitesettings['googleapi'])) ? esc_attr($sitesettings['googleapi']) : '';
	$default_attributes = (!empty($sitesettings['default_attributes'])) ? $sitesettings['default_attributes'] : '';
	$global_classes = (!empty($sitesettings['global_classes'])) ? $sitesettings['global_classes'] : [];
	$global_interactions = (!empty($sitesettings['global_interactions'])) ? $sitesettings['global_interactions'] : [];
	$framework_classes = (!empty($sitesettings['framework_classes'])) ? $sitesettings['framework_classes'] : [];
	$preset_classes = greenshift_render_preset_classes();
	$global_variables = (!empty($sitesettings['variables'])) ? $sitesettings['variables'] : [];
	$colours = (!empty($sitesettings['colours'])) ? $sitesettings['colours'] : '';
	$elements = (!empty($sitesettings['elements'])) ? $sitesettings['elements'] : '';
	$gradients = (!empty($sitesettings['gradients'])) ? $sitesettings['gradients'] : '';
	$hide_local_styles = (!empty($sitesettings['hide_local_styles'])) ? $sitesettings['hide_local_styles'] : '';
	$default_unit = (!empty($sitesettings['default_unit'])) ? $sitesettings['default_unit'] : '';
	$variables = greenshift_render_variables($global_variables);
	$addonlink = 'https://shop.greenshiftwp.com/downloads/greenlight-pro/';
	$updatelink = $addonlink;
	$theme = wp_get_theme();
	if ($theme->parent_theme) {
		$template_dir =  basename(get_template_directory());
		$theme = wp_get_theme($template_dir);
	}
	$themename = $theme->get('TextDomain');
	$local_wp_fonts = greenshift_get_wp_local_fonts();

	//Framework custom classes
	$custom_options = [];
	$custom_options = apply_filters('gspb_framework_classes', $custom_options);
	if(!empty($custom_options)){
		$preset_classes = array_merge($preset_classes, $custom_options);
	}

	//Core Framework Utility
	$cf_utility_on = !empty($sitesettings['cf_utility_on']) ? $sitesettings['cf_utility_on'] : '';
	if($cf_utility_on && class_exists('CoreFramework\Helper')){
		//$cf_classes = get_option('core_framework_grouped_classes');
		$cf_classes = false; // removing this option in favor of CF core component
		if(!empty($cf_classes)){
			foreach($cf_classes as $cf_sections){
				if(!empty($cf_sections)){
					foreach ($cf_sections as $key=>$section){
						$array_classes = [];
						if(!empty($section)){
							$unique_classes = array_unique($section);
							foreach ($unique_classes as $class){
								$array_classes[] = [
									'value'=> $class,
									'label'=> $class,
									'type' => "framework"
								];
							}
							if(!empty($array_classes)){
								$preset_classes[] = [
									'label' => $key,
									'options' => $array_classes
								];
							}
						}
					}
				}
			}
		}

		$helper = new CoreFramework\Helper(); 
		$variablesCF = $helper->getVariables();
		$variablesCFArray = [];
    
		foreach ($variablesCF as $key => $value) {
			switch ($key) {
				case 'colorStyles':
					foreach ($value as $item) {
						$variablesCFArray[] = [
							'label' => ucfirst($item),
							'value' => 'var(--' . $item . ')',
							'variable' => '--' . $item,
							'variable_value' => '',  // You can add actual value here if available
							'group' => 'color'
						];
					}
					break;
					
				case 'typographyStyles':
					foreach ($value as $item) {
						$variablesCFArray[] = [
							'label' => strtoupper(str_replace('text-', '', $item)) . '',
							'value' => 'var(--' . $item . ')',
							'variable' => '--' . $item,
							'variable_value' => '',  // You can add actual value here if available
							'group' => 'size'
						];
					}
					break;
					
				case 'spacingStyles':
					foreach ($value as $item) {
						$size = strtoupper(str_replace('space-', '', $item));
						$variablesCFArray[] = [
							'label' => $size,
							'value' => 'var(--' . $item . ')',
							'variable' => '--' . $item,
							'variable_value' => '',  // You can add actual value here if available
							'group' => 'spacing'
						];
					}
					break;
					
				case 'designStyles':
					foreach ($value as $item) {
						$variablesCFArray[] = [
							'label' => ucfirst($item),
							'value' => 'var(--' . $item . ')',
							'variable' => '--' . $item,
							'variable_value' => '',  // You can add actual value here if available
							'group' => 'design'
						];
					}
					break;
					
				case 'layoutsStyles':
					foreach ($value as $item) {
						$variablesCFArray[] = [
							'label' => ucfirst($item),
							'value' => 'var(--' . $item . ')',
							'variable' => '--' . $item,
							'variable_value' => '',  // You can add actual value here if available
							'group' => 'layout'
						];
					}
					break;
					
				case 'componentsStyles':
					foreach ($value as $item) {
						$variablesCFArray[] = [
							'label' => ucfirst($item),
							'value' => 'var(--' . $item . ')',
							'variable' => '--' . $item,
							'variable_value' => '',  // You can add actual value here if available
							'group' => 'component'
						];
					}
					break;
					
				case 'otherStyles':
					foreach ($value as $item) {
						$variablesCFArray[] = [
							'label' => ucfirst($item),
							'value' => 'var(--' . $item . ')',
							'variable' => '--' . $item,
							'variable_value' => '',  // You can add actual value here if available
							'group' => 'other'
						];
					}
					break;
					
				default:
					foreach ($value as $item) {
						$variablesCFArray[] = [
							'label' => ucfirst($item),
							'value' => 'var(--' . $item . ')',
							'variable' => '--' . $item,
							'variable_value' => '',  // You can add actual value here if available
							'group' => 'extra'
						];
					}
					// Do nothing for keys without specified group
					break;
			}
		}

		if(!empty($variablesCFArray)){
			$variables = array_merge($variables, $variablesCFArray);
		}
	}

	$stylebook_post_id = get_option( 'gspb_stylebook_id' );
	if( $stylebook_post_id ){
		$stylebook_url = get_edit_post_link( $stylebook_post_id );
		if(!$stylebook_url){
			$stylebook_url = admin_url('admin.php?page=greenshift_stylebook');
		}
	}else{
		$stylebook_url = admin_url('admin.php?page=greenshift_stylebook');
	}

	$current_user = wp_get_current_user();
	$current_user_roles = $current_user->roles;
	$block_manager_settings = isset($sitesettings['block_manager']) ? $sitesettings['block_manager'] : array();
	$disabled_blocks = array();
	$disabled_variations = array();
	$simplified_panels = false;
	foreach($current_user_roles as $current_user_role){
		if(!empty($block_manager_settings[$current_user_role])){
			$disabled_blocks = (isset($block_manager_settings[$current_user_role]['disabled_blocks'])) ? array_merge($disabled_blocks, $block_manager_settings[$current_user_role]['disabled_blocks']) : $disabled_blocks;
			$disabled_variations = (isset($block_manager_settings[$current_user_role]['disabled_variations'])) ? array_merge($disabled_variations, $block_manager_settings[$current_user_role]['disabled_variations']) : $disabled_variations;
			$simplified_panels = (!empty($block_manager_settings[$current_user_role]['simplified_panels'])) ? true : false;
		}
	}
	$disabled_blocks = array_unique($disabled_blocks);
	$disabled_variations = array_unique($disabled_variations);

	//$updatelink = str_replace('greenshift_dashboard-addons', 'greenshift_dashboard-pricing', $addonlink);
	$localize_array = 		array(
		'ajaxUrl' => admin_url('admin-ajax.php'),
		'pluginURL' => GL_DIR_URL,
		'rowDefault' => apply_filters('gspb_default_row_width_px', $row),
		'theme' => $themename,
		'isRehub' => ($themename == 'rehub-theme'),
		'isSaveInline' => (!empty($gspb_css_save) && $gspb_css_save == 'inlineblock') ? '1' : '',
		'default_attributes' => $default_attributes,
		'addonLink' => $addonlink,
		'updateLink' => $updatelink,
		'localfont' => apply_filters('gspb_local_font_array', $localfont),
		'googleapi' => apply_filters('gspb_google_api_key', $googleapi),
		'global_classes' => apply_filters('gspb_global_classes', $global_classes),
		'global_interactions' => apply_filters('gspb_global_interactions', $global_interactions),
		'framework_classes' => apply_filters('gspb_framework_classes', $framework_classes),
		'preset_classes' => $preset_classes,
		'isGreenLight' => true,
		'colours' => $colours,
		'elements' => $elements,
		'variables' => $variables,
		'gradients' => $gradients,
		'enabledcroll' => (function_exists('gl_check_cron_exec')) ? '1' : '',
		'stylebook_url' => $stylebook_url,
		'hide_local_styles' => $hide_local_styles,
		'default_unit' => $default_unit,
		'local_wp_fonts' => $local_wp_fonts,
		'apis' => current_user_can('manage_options') ? array(
			'openaiapi' => !empty($sitesettings['openaiapi']) ? $sitesettings['openaiapi'] : '',
			'openaiapimodel' => !empty($sitesettings['openaiapimodel']) ? $sitesettings['openaiapimodel'] : '',
			'claudeapi' => !empty($sitesettings['claudeapi']) ? $sitesettings['claudeapi'] : '',
			'deepseekapi' => !empty($sitesettings['deepseekapi']) ? $sitesettings['deepseekapi'] : '',
			'geminiapi' => !empty($sitesettings['geminiapi']) ? $sitesettings['geminiapi'] : '',
			'aihelpermodel' => !empty($sitesettings['aihelpermodel']) ? $sitesettings['aihelpermodel'] : '',
			'aiimagemodel' => !empty($sitesettings['aiimagemodel']) ? $sitesettings['aiimagemodel'] : '',
			'aidesignmodel' => !empty($sitesettings['aidesignmodel']) ? $sitesettings['aidesignmodel'] : '',
			'googleapi' => !empty($sitesettings['googleapi']) ? $sitesettings['googleapi'] : '',
		) : array(),
		'nonce' => wp_create_nonce('gspb_nonce'),
		'isDarkMode' => !empty($sitesettings['dark_mode']) ? '1' : '',
		'disabled_blocks' => $disabled_blocks,
		'disabled_variations' => $disabled_variations,
		'simplified_panels' => $simplified_panels,
	);
	
	wp_localize_script(
		'greenShift-library-script',
		'greenShift_params',
		$localize_array
	);

	// Blocks Assets Scripts
	wp_register_script(
		'greenShift-block-js', // Handle.
		GL_DIR_URL . 'build/index.js',
		array('greenShift-editor-js', 'greenShift-library-script', 'wp-block-editor', 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-data'),
		$index_asset_file['version'],
		true
	);
	wp_set_script_translations('greenShift-block-js', 'gl-page-builder');
	wp_enqueue_script('greenShift-block-js');

	$licenses = gl_edd_check_all_licenses();
    $is_active = gl_edd_has_premium_access($licenses);

	$check = '';
	if ($is_active) {
		$check = 1;
	}
	$lc = array('can_use_premium_code' => $check);
	if(defined('\ContentEgg\PLUGIN_PATH') && class_exists('\ContentEgg\application\components\GreenshiftIntegrator')){
		$lc['ce_enabled'] = 1;
		$filters = \ContentEgg\application\components\GreenshiftIntegrator::getAllowedFilters();
		if(!empty($filters['modules']['allowed_values'])){
			$lc['ce_modules'] = $filters['modules']['allowed_values'];
		}
	}
    wp_localize_script('greenShift-block-js', 'greenshiftQUERY', $lc);
    wp_localize_script('greenShift-block-js', 'greenshiftGSAP', $lc);


	if('gspbstylebook' == get_post_type()){
		wp_enqueue_script('greenShift-stylebook-js', GL_DIR_URL . 'build/gspbStylebook.js', array('wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor', 'wp-data'), $index_asset_file['version'], true);
		wp_set_script_translations('greenShift-stylebook-js', 'gl-page-builder');
	}

		// gsap animation
		wp_enqueue_script('gsap-animation');
		wp_enqueue_script('gsap-scrolltrigger');
		wp_enqueue_script('gsapcustomease');
		wp_enqueue_script('gsapsplittext');
		wp_enqueue_script('gsapsvgdraw');
		wp_enqueue_script('gsapsvgpath');
		wp_enqueue_script('gsapsvgmorph');

		// gsap init
		wp_enqueue_script('gsap-animation-init');

	//wp_enqueue_script('anchor-polyfill');
	//wp_enqueue_script('scroll-view-polyfill');

}


//////////////////////////////////////////////////////////////////
// Helper Functions to save conditional assets to meta
//////////////////////////////////////////////////////////////////

// Meta Data For CSS Post.

function gspb_register_post_meta()
{
	register_meta(
		'post',
		'_gspb_post_css',
		array(
			'show_in_rest' => true,
			'single'       => true,
			'type'         => 'string',
			'auth_callback' => function () {
				return current_user_can('edit_posts');
			}
		)
	);
}
add_action('init', 'gspb_register_post_meta', 10);

add_action('wp_enqueue_scripts', 'gspb_save_inline_css', apply_filters('greenshift_dynamic_css_priority', 10));
function gspb_save_inline_css()
{
	// Get the css registred for the post
	$post_id          = get_queried_object_id();
	$gspb_css_content = get_post_meta($post_id, '_gspb_post_css', true);

	if ($gspb_css_content) {
		$gspb_saved_css_content = gspb_get_final_css($gspb_css_content);
		$final_css = $gspb_saved_css_content;

		wp_register_style('gspb-post-css', false);
		wp_enqueue_style('gspb-post-css');
		wp_add_inline_style('gspb-post-css', $final_css);
	}
}

//PolyLang Fix
add_filter('pll_copy_post_metas', 'gspb_exclude_specific_meta_field', 999, 4);
function gspb_exclude_specific_meta_field($metas, $sync, $from, $to) {
    // Check if the specified meta field is present in the array
    if (in_array('_gspb_post_css', $metas)) {
        // Remove the specified meta field from the array
        unset($metas[array_search('_gspb_post_css', $metas)]);
    }
    return $metas;
}

//////////////////////////////////////////////////////////////////
// Global assets init
//////////////////////////////////////////////////////////////////

add_action('enqueue_block_assets', 'gspb_global_assets');
function gspb_global_assets()
{

	//root styles
	$options = get_option('gspb_global_settings');
	$gs_global_css = '';
			
	if (!is_admin()) {
		//Front assets

		//Custom CSS
		if (!empty($options['custom_css'])) {
			$custom_css = $options['custom_css'];
			$gs_global_css = $gs_global_css . $custom_css;
		}
		
		//Local fonts
		if (!empty($options['localfontcss'])) {
			$gs_global_css = $gs_global_css . $options['localfontcss'];
		}

		//Colors
		if (!empty($options['colours'])) {
			$color_css = ':root{';
			foreach ($options['colours'] as $key=>$element) {
				if (!empty($element)) {
					$color_css .= '--gs-color'.$key . ':' . $element . ';';
				}
			}
			$color_css .= '}';
			$gs_global_css = $gs_global_css . $color_css;
		}

		//Dark mode colors
		if (!empty($options['darkmodecolors'])) {
			$dark_color_css = ':root[data-color-mode*="dark"], body.darkmode{';
			foreach ($options['darkmodecolors'] as $key=>$element) {
				if (!empty($element)) {
					$dark_color_css .= $key . ':' . $element . ';';
				}
			}
			$dark_color_css .= '}';
			$gs_global_css = $gs_global_css . $dark_color_css;
		}

		//Gradients
		if (!empty($options['gradients'])) {
			$gradient_css = ':root{';
			foreach ($options['gradients'] as $key=>$element) {
				if (!empty($element)) {
					$gradient_css .= '--gs-gradient'.$key . ':' . $element . ';';
				}
			}
			$gradient_css .= '}';
			$gs_global_css = $gs_global_css . $gradient_css;
		}

		//Elements
		if (!empty($options['elements'])) {
			foreach ($options['elements'] as $element) {
				if (!empty($element['css'])) {
					$gs_global_css = $gs_global_css . $element['css'];
				}
			}
		}

		//Variables
		$variablearray = !empty($options['variables']) ? $options['variables'] : '';
		$variables = greenshift_render_variables($variablearray);
		if(!empty($variables)){
			$variables_css = '';
			foreach ($variables as $key=>$variable) {
				if (!empty($variable['variable']) && !empty($variable['variable_value'])) {
					$variables_css .= $variable['variable'] . ':' . $variable['variable_value'] . ';';
				}
			}
			if($variables_css){
				$variables_css = 'body{'.$variables_css.'}';
				$gs_global_css = $gs_global_css . $variables_css;
			}
		}

		//Global classes if we don't use Merged Inline Option
		$global_classes = !empty($options['global_classes']) ? $options['global_classes'] : '';
		$enable_head_inline = !empty($options['enable_head_inline']) ? $options['enable_head_inline'] : '';
		if(!empty($global_classes) && !$enable_head_inline){
			$global_class_style = '';
			foreach ($global_classes as $class) {
				if(!empty($class['css'])){
					$global_class_style .= $class['css'];
				}
				if(!empty($class['selectors'])){
					foreach ($class['selectors'] as $selector) {
						if(!empty($selector['css'])){
							$global_class_style .= $selector['css'];
						}
					}
				}
			}
			if($global_class_style){
				$gs_global_css = $gs_global_css . $global_class_style;
			}
		}
	
		if ($gs_global_css) {
			$gs_global_css = gspb_get_final_css($gs_global_css);
			$gs_global_css = gspb_quick_minify_css($gs_global_css);
			$gs_global_css = htmlspecialchars_decode($gs_global_css);
			wp_register_style('greenshift-global-css', false);
			wp_enqueue_style('greenshift-global-css');
			wp_add_inline_style('greenshift-global-css', $gs_global_css);
		}

		//Style presets and global class render if we use Merged Inline Option
		$styleStore = GreenShiftStyleStore::getInstance();
		$styles = $styleStore->renderStyles();
		$classstyles = $styleStore->renderClassStyles();
		if($styles || $classstyles){
			$styles = $styles . $classstyles;
			wp_register_style('greenshift-style-presets', false);
			wp_enqueue_style('greenshift-style-presets');
			wp_add_inline_style('greenshift-style-presets', $styles);
		}

		if (!empty($options['global_interactions']) && is_array($options['global_interactions'])) {
			$has_value = false;			
			$script = '';
			foreach ($options['global_interactions'] as $index => $value) {
				if(!empty($value)){
					$has_value = true;
					$script .= 'GSPB_Trigger_Actions("front", document.querySelectorAll(".'.esc_attr($index).'"), window, document, null, \''.wp_json_encode($value).'\');';
				}
			}
			if($has_value){
				wp_enqueue_script('gspb_motion_one');
				wp_enqueue_script('gspb_interactions');
				wp_add_inline_script('gspb_interactions', $script, 'after');
			}
		}

	}else{
		//Here we inject our scripts into editor > WP 6.3

		$stylesrender = '';

		$hidelandscape = apply_filters('greenshift_hide_landscape_breakpoint', false);
		if($hidelandscape){
			if(empty($options['enable_landscape'])){
				$stylesrender .= '.gspb_inspector_device-icons__icon[data-device="landscape-mobile"], .gspb_inspector_toggle_landscapemobile_hide{display:none !important;}';
			}
		}

		if (!empty($options['custom_css'])) {
			$custom_css = $options['custom_css'];
			$gs_global_css = $gs_global_css . $custom_css;
		}

		if (!empty($options['localfontcss'])) {
			$gs_global_css = $gs_global_css . $options['localfontcss'];
		}
	
		if ($gs_global_css) {
			$gs_global_css = gspb_get_final_css($gs_global_css);
			$stylesrender .= $gs_global_css;
		}

		$presets = greenshift_render_preset_classes();
		foreach ($presets as $key=>$option) {
			if(!empty($option['options']) && is_array($option['options'])){
				foreach ($option['options'] as $class) {
					if(!empty($class['css'])){
						$stylesrender .= $class['css'];
					}
				}
			}
		}

		if($stylesrender){
			wp_register_style('greenshift-editor-css', false);
			wp_enqueue_style('greenshift-editor-css');
			wp_add_inline_style('greenshift-editor-css', $stylesrender);
		}

		$global_classes = !empty($options['global_classes']) ? $options['global_classes'] : '';
		if(!empty($global_classes)){
			foreach ($global_classes as $class) {
				$global_class_style = '';
				$global_class_value = '';
				if(!empty($class['value'])){
					$global_class_value = $class['value'];
				}	
				if(!empty($class['css'])){
					$global_class_style .= $class['css'];
				}
				if(!empty($class['selectors'])){
					foreach ($class['selectors'] as $selector) {
						if(!empty($selector['css'])){
							$global_class_style .= $selector['css'];
						}
					}
				}
				if(!empty($global_class_style) && $global_class_value){
					$cleanTopvalue = preg_replace('/[^a-zA-Z0-9]/', '', $global_class_value);

					wp_register_style('greenshift-global-class-id-'.$cleanTopvalue, false);
					wp_enqueue_style('greenshift-global-class-id-'.$cleanTopvalue);
					wp_add_inline_style('greenshift-global-class-id-'.$cleanTopvalue, $global_class_style);

				}
			}
		}

		if (!empty($options['elements'])) {
			foreach ($options['elements'] as $key=>$element) {
				if (!empty($element['admincss'])) {
					$element_css =  $element['admincss'];
					wp_register_style('greenshift-global-element-id-'.$key, false);
					wp_enqueue_style('greenshift-global-element-id-'.$key);
					wp_add_inline_style('greenshift-global-element-id-'.$key, $element_css);
				}
			}
		}

		if (!empty($options['colours'])) {
			$color_css = 'body{';
			foreach ($options['colours'] as $key=>$element) {
				if (!empty($element)) {
					$color_css .= '--gs-color'.$key . ':' . $element . ';';
				}
			}
			$color_css .= '}';
			wp_register_style('greenshift-global-colors', false);
			wp_enqueue_style('greenshift-global-colors');
			wp_add_inline_style('greenshift-global-colors', $color_css);
		}

		if (!empty($options['darkmodecolors'])) {
			$nightcolor_css = ':root[data-color-mode*="dark"], body.darkmode, .editor-styles-wrapper:has(.gspb_inspector_btn--darkmode--active),
			body:has(.gspb_inspector_btn--darkmode--active) .editor-styles-wrapper{';
			foreach ($options['darkmodecolors'] as $key=>$element) {
				if (!empty($element)) {
					$nightcolor_css .= $key . ':' . $element . ';';
				}
			}
			$nightcolor_css .= '}';
			wp_register_style('greenshift-global-night-colors', false);
			wp_enqueue_style('greenshift-global-night-colors');
			wp_add_inline_style('greenshift-global-night-colors', $nightcolor_css);
		}

		if (!empty($options['gradients'])) {
			$gradient_css = 'body{';
			foreach ($options['gradients'] as $key=>$element) {
				if (!empty($element)) {
					$gradient_css .= '--gs-gradient'.$key . ':' . $element . ';';
				}
			}
			$gradient_css .= '}';
			wp_register_style('greenshift-global-gradients', false);
			wp_enqueue_style('greenshift-global-gradients');
			wp_add_inline_style('greenshift-global-gradients', $gradient_css);
		}

		$variablearray = !empty($options['variables']) ? $options['variables'] : '';
		$variables = greenshift_render_variables($variablearray);
		if(!empty($variables)){
			$variables_css = '';
			foreach ($variables as $key=>$variable) {
				if (!empty($variable['variable']) && !empty($variable['variable_value'])) {
					$variables_css .= $variable['variable'] . ':' . $variable['variable_value'] . ';';
				}
			}
			if($variables_css){
				$variables_css = 'body{'.$variables_css.'}';
				wp_register_style('greenshift-global-variables', false);
				wp_enqueue_style('greenshift-global-variables');
				wp_add_inline_style('greenshift-global-variables', $variables_css);
			}
		}

		//Swiper lib
		wp_enqueue_script('gspb-swiper');
		//animated text
		wp_enqueue_script('gstextanimate');
		// interactions
		wp_enqueue_script('gspb_motion_spring');
		wp_enqueue_script('gspb_motion_one');
		wp_enqueue_script('gspb_interactions');


		if (!empty($options['global_interactions']) && is_array($options['global_interactions'])) {
			$has_value = false;			
			$script = '';
			foreach ($options['global_interactions'] as $index => $value) {
				if(!empty($value)){
					$has_value = true;
					$script .= 'GSPB_Trigger_Actions("front", document.querySelectorAll(".'.esc_attr($index).'"), window, document, null, \''.wp_json_encode($value).'\');';
				}
			}
			if($has_value){
				wp_add_inline_script('gspb_interactions', $script, 'after');
			}
		}

		if(!empty($options['dark_mode'])){
			wp_enqueue_style('greenShift-dark-accent-css', GL_DIR_URL . 'templates/admin/black.css', array(), '1.3');
		}
	}
}

//////////////////////////////////////////////////////////////////
// REST routes to save and get settings
//////////////////////////////////////////////////////////////////

function greenshift_app_pass_validation( $request ) {
    // Verify the application password
    $user_id = wp_validate_application_password( false );
    
    if ( $user_id ) {
        // Application password is valid, now check user role
        $user = get_user_by( 'id', $user_id );
        
        // Check if user is administrator or editor
        if ( $user && in_array( 'administrator', $user->roles ) ) {
            return true;
        } else {
            // User doesn't have required role
            return new WP_Error( 'rest_forbidden', esc_html__( 'Insufficient permissions. Only administrators are allowed.', 'gl-page-builder' ), array( 'status' => 403 ) );
        }
    } else {
        // Application password is invalid, deny access
        return new WP_Error( 'rest_forbidden', esc_html__( 'Invalid application password.', 'gl-page-builder' ), array( 'status' => 401 ) );
    }
}

//////////////////////////////////////////////////////////////////
// USDZ support until WP will have it
//////////////////////////////////////////////////////////////////

function gspb_enable_extended_upload($mime_types = array())
{
	$mime_types['txt'] = 'application/text';
	$mime_types['json'] = 'application/json';
	$mime_types['glb']  = 'application/octet-stream';
	$mime_types['usdz']  = 'application/octet-stream';
	$mime_types['splinecode'] = 'application/octet-stream';
	$mime_types['gltf']  = 'text/plain';
	$mime_types['riv'] = 'application/octet-stream';
	$mime_types['lottie'] = 'application/octet-stream';
	return $mime_types;
}
add_filter('upload_mimes', 'gspb_enable_extended_upload');


//////////////////////////////////////////////////////////////////
// Template Library
//////////////////////////////////////////////////////////////////

const TEMPLATE_SERVER_URL = 'https://greenshift.wpsoul.net/';

add_action('wp_ajax_gspb_get_layouts', 'gspb_get_all_layouts');
add_action('wp_ajax_gspb_get_layout_by_id', 'gspb_get_layout');
add_action('wp_ajax_gspb_get_categories', 'gspb_get_categories');
add_action('wp_ajax_gspb_get_saved_block', 'gspb_get_saved_block');

if (!function_exists('gspb_get_all_layouts')) {
	function gspb_get_all_layouts()
	{
		$get_args  = array('timeout' => 200, 'sslverify' => false);
		$category  = intval($_POST['category_id']);
		$page      = !empty($_POST['page']) ? intval($_POST['page']) : 1;
		$per_page  = 12;
		$term      = isset($_POST['term']) ? sanitize_text_field($_POST['term']) : null;
		$tag       = isset($_POST['tag']) ? sanitize_text_field($_POST['tag']) : null;
		// if term is available, category will be only term 
		if (isset($term) && $term !== "All") {
			$category = $term;
		}

		$apiUrl    = TEMPLATE_SERVER_URL . 'wp-json/wp/v2/posts/?_embed&categories=' . $category . '&per_page=' . $per_page . '&page=' . $page;
		// Append tag to the API URL if it's available and not equal to "All"
		if (!is_null($tag) && $tag !== '' && $tag !== 'All') {
			$apiUrl .= '&tags=' . $tag;
		}
		$apiUrl .= '&isgreenlight=132';

		$response  = wp_safe_remote_get($apiUrl, $get_args);
		$body      = wp_remote_retrieve_body($response);
		$headers   = wp_remote_retrieve_headers($response);
		$request_result = $body;

		if ($request_result === '') {
			return false;
		} else {
			$total_pages = isset($headers['x-wp-totalpages']) ? intval($headers['x-wp-totalpages']) : 1;
			$decoded_data = json_decode($request_result, true);

			$response_data = array(
				'total_pages' => $total_pages,
				'data' => $decoded_data,
			);

			echo json_encode($response_data);
		}

		wp_die();
	}
}

function gspb_isIncludedDomain($url, $included_domains) {
    $parsed_url = parse_url($url);
    if (!isset($parsed_url['host'])) {
        return false; // Not a valid URL
    }
    
    $host = $parsed_url['host'];

    foreach ($included_domains as $domain) {
        if (substr($host, -strlen($domain)) === $domain) {
            return true;
        }
    }

    return false;
}

if (!function_exists('gspb_get_layout')) {
	function gspb_get_layout()
	{
		if(!current_user_can('manage_options')) return false;
		check_ajax_referer('gspb_nonce', 'security');
		$get_args = array(
			'timeout'   => 200,
			'sslverify' => false,
		);
		$id       = intval($_POST['gspb_layout_id']);
		$public_assets_url = '';
		if(!empty($_POST['download_url']) || !empty($_POST['download_url_animated'])){
			if(!empty($_POST['download_animated']) && $_POST['download_animated'] == 'yes' && !empty($_POST['download_url_animated'])){
				$apiUrl   = esc_url($_POST['download_url_animated']);
			}else{
				$apiUrl   = esc_url($_POST['download_url']);
			}
			$included_domains = ["wpsoul.net", "greenshiftwp.com", "wpsoul.com"];
			if (gspb_isIncludedDomain($apiUrl, $included_domains)) {
				// It's fine, we get link from trusted domains
			} else {
				return '';
			}

			$urlarray = explode('/wp-json', $apiUrl);
			if(is_array($urlarray) && !empty($urlarray[0]) && !empty($_POST['download_assets']) && $_POST['download_assets'] == 'yes'){
				$siteUrl = $urlarray[0];
				$public_assets_url = $siteUrl . '/wp-json/greenshift/v1/public_assets';
			}
		}else{
			$apiUrl   = TEMPLATE_SERVER_URL . '/wp-json/greenshift/v1/layout/' . $id;
		}
		$response = wp_safe_remote_get($apiUrl, $get_args);
		$request_result = wp_remote_retrieve_body($response);
		if ($request_result == '') {
			return false;
		} else {
			if($public_assets_url){
				$public_assets = wp_safe_remote_get($public_assets_url, $get_args);
				$public_assets_result = wp_remote_retrieve_body($public_assets);
				if ($public_assets_result != '') {
					$defaults = get_option('gspb_global_settings');
					$public_assets_result = json_decode($public_assets_result, true);
					$public_assets_result = !empty($public_assets_result['settings']) ? $public_assets_result['settings'] : [];

					if(!empty($public_assets_result['colours'])){
						$figma_colors = $public_assets_result['colours'];
						$colours = !empty($defaults['colours']) ? $defaults['colours'] : [];
			
						foreach($figma_colors as $key=>$value){
							$colours[$key] = $value;
						}
						$colours = $colours;
						$settings['colours'] = $colours;
						update_option('gspb_global_settings', $settings);
					}
					if(!empty($public_assets_result['gradients'])){
						$figma_gradients = $public_assets_result['gradients'];
						$gradients = !empty($defaults['gradients']) ? $defaults['gradients'] : [];
			
						foreach($figma_gradients as $key=>$value){
							$gradients[$key] = $value;
						}
						$gradients = $gradients;
						$settings['gradients'] = $gradients;
						update_option('gspb_global_settings', $settings);
					}
					if(!empty($public_assets_result['localfont'])){

						$fonts = json_decode($public_assets_result['localfont'], true);
						$localfont = !empty($defaults['localfont']) ? json_decode($defaults['localfont'], true) : [];
						$localfontcss = !empty($defaults['localfontcss']) ? $defaults['localfontcss'] : '';
						$newfonts = false;
			
						foreach($fonts as $key=>$value){
							$fontName = $key;
							if(!$fontName || in_array($fontName, $localfont)){
								continue;
							}
							$fontFile = '';
							foreach ($value as $fonturl){
								if(!empty($fonturl)){
									$fontFile = $fonturl;
									break;
								}
							}
							if(!$fontFile){
								continue;
							}
							$fontExtension = pathinfo($fontFile, PATHINFO_EXTENSION);
							$allowed_font_ext = [
								'woff2',
								'woff',
								'tiff',
								'ttf',
							]; 
							if(!$fontExtension || !in_array($fontExtension, $allowed_font_ext)){
								continue;
							}
							$newfilename = basename($fontFile);
							$ext = $fontExtension;
							$upload_dir = wp_upload_dir();
							$dir = trailingslashit($upload_dir['basedir']) . 'GreenShift/'; 
							if ($newfilename = greenshift_download_file_localy($fontFile, $dir, $newfilename, $ext)) {
								$fonturl = trailingslashit($upload_dir['url']) .$newfilename;
								$localfont[$fontName] = [
									'woff2' => ($fontExtension == 'woff2') ? $fonturl : '',
									'woff' => ($fontExtension == 'woff') ? $fonturl : '',
									'tiff' => ($fontExtension == 'tiff') ? $fonturl : '',
									'ttf' => ($fontExtension == 'ttf') ? $fonturl : '',
								];
			
								$localfontcss .= '@font-face {';
									$localfontcss .= 'font-family: "' . $fontName . '";';
									$localfontcss .= 'src: ';
									if ($fontExtension == 'woff2') {
										$localfontcss .= 'url(' . $fonturl . ') format("woff2"), ';
									}
									if ($fontExtension == 'woff') {
										$localfontcss .= 'url(' . $fonturl . ') format("woff"), ';
									}
									if ($fontExtension == 'ttf') {
										$localfontcss .= 'url(' . $fonturl . ') format("truetype"), ';
									}
									if ($fontExtension == 'tiff') {
										$localfontcss .= 'url(' . $fonturl . ') format("tiff"), ';
									}
									$localfontcss .= ';';
								$localfontcss .= 'font-display: swap;}';
								$newfonts = true;
							} else {
								continue;
							}
			
						}
			
						if($newfonts){
							$localfontcss = str_replace(', ;', ';', $localfontcss);
							$localfont = json_encode($localfont);
							$settings['localfont'] = $localfont;
							$settings['localfontcss'] = $localfontcss;
							update_option('gspb_global_settings', $settings);
						}

					}
					if(!empty($public_assets_result['elements']) && is_array($public_assets_result['elements'])){
						$figma_elements = $public_assets_result['elements'];
						$elements = $figma_elements;
						$settings['elements'] = $elements;
						update_option('gspb_global_settings', $settings);
					}
				}
			}
			$request_result = greenshift_replace_ext_images($request_result);
			$type = sanitize_text_field($_POST['type']);
			if($type == 'home' || $type == 'header' || $type == 'footer' || $type == 'single' || $type == 'archive' || $type == 'archiveproduct' || $type == 'singleproduct' || $type == 'searchproduct'){
				$pageid = (int)$_POST['pageid'];
				$post_content = json_decode($request_result, true);
				$post_content = wp_slash($post_content);
				if($type == 'single' || $type == 'archive' || $type == 'archiveproduct' || $type == 'singleproduct'|| $type == 'searchproduct'){
					$post_content = '<!-- wp:template-part {"slug":"header","theme":"greenshift","tagName":"header","className":"site-header"} /-->'.$post_content.'<!-- wp:template-part {"slug":"footer","theme":"greenshift","tagName":"footer","className":"site-footer is-style-no-margin"} /-->';
				}
				
				wp_update_post(array(
					'ID' => $pageid,
					'post_content' => $post_content,
				));
				if($type == 'home'){
					$cssUrl = str_replace('layout', 'layoutcss', $apiUrl);
					$responsecss = wp_safe_remote_get($cssUrl, $get_args);
					$request_resultcss = wp_remote_retrieve_body($responsecss);
					if ($request_resultcss) {
						$layout_styles = strip_tags($request_resultcss);
						$layout_styles = trim($layout_styles, '"');
						update_post_meta($pageid, '_gspb_post_css', $layout_styles);
					}
				}
				echo $request_result;
			}else{
			echo $request_result;
			}
		}
		wp_die();
	}
}

if (!function_exists('gspb_get_categories')) {
	function gspb_get_categories()
	{
		$get_args = array(
			'timeout'   => 200,
			'sslverify' => false,
		);
		$id       = intval($_POST['category_id']);
		$apiUrl   = TEMPLATE_SERVER_URL . '/wp-json/wp/v2/categories?parent=' . $id;
		$response = wp_safe_remote_get($apiUrl, $get_args);
		$request_result = wp_remote_retrieve_body($response);
		if ($request_result == '') {
			return false;
		} else {
			echo wp_remote_retrieve_body($response);
		}
		wp_die();
	}
}

function gspb_get_saved_block()
{
	$args = array(
		'post_type'   => 'wp_block',
		'post_status' => 'publish',
		'posts_per_page' => 100
	);
	$id       = (!empty($_POST['block_id'])) ? intval($_POST['block_id']) : '';
	$id       = (!empty($_POST['gspb_layout_id'])) ? intval($_POST['gspb_layout_id']) : $id;
	if ($id) {
		$args['p'] = $id;
	}
	$r         = wp_parse_args(null, $args);
	$get_posts = new WP_Query();
	$wp_blocks = $get_posts->query($r);
	$response = array(
		'blocks' => $wp_blocks,
		'admin' => admin_url()
	);
	wp_send_json_success($response);
}


//////////////////////////////////////////////////////////////////
// Model viewer script type
//////////////////////////////////////////////////////////////////

add_filter('script_loader_tag','greenshift_new_add_type_to_script', 10, 3);
function greenshift_new_add_type_to_script($tag, $handle, $source){
	if ('anchor-polyfill' === $handle) {
        $tag = '<script src="'. $source .'" type="module"></script>';
    } 
	if ('google-maps' === $handle) {
        $tag = '<script src="'. $source .'" async></script>';
    } 
    return $tag;
}

//add_filter( 'wp_default_autoload_value', 'gspb_large_value_autoload', 10, 2 );
function gspb_large_value_autoload( $autoload, $option ) {
    if ( 'gspb_global_settings' === $option ) {
        return true;
    }
    return $autoload;
}