<?php
// INITIALIZE GUTEN BLOCKS AND DEFINE HANDLERS



// register blocks
function gg_guten_register() {
	if(!function_exists('register_block_type')) {
        return;
    }

	// galleries array
	$args = array(
		'post_type' => 'gg_galleries',
		'numberposts' => -1,
		'post_status' => 'publish',
	);
	$galleries = get_posts($args);
	
	$GLOBALS['gg_guten_galls'] = array(); 
	foreach($galleries as $gallery) {
    	$GLOBALS['gg_guten_galls'][ $gallery->ID ] = $gallery->post_title;
        asort($GLOBALS['gg_guten_galls'], SORT_NATURAL);
    }
	
	
	//////
	
	
	$shortcodes = array(
		'gallery/gallery',
		'collection/collection',
		'carousel/carousel',
		'slider/slider',
		'itg/itg',
	);
	
	foreach($shortcodes as $ch) {
		include_once(GG_DIR .'/builders_integration/guten_elements/'. $ch .'.php');	
	}
}
add_action('init', 'gg_guten_register');





// register GG blocks category
function gg_guten_blocks_category($categories, $post) {
	return array_merge(
		$categories,
		array(
			array(
				'slug' 	=> 'lc-global-gallery',
				'title' => 'Global Gallery',
			),
		)
	);
}
add_filter('block_categories_all', 'gg_guten_blocks_category', 10, 2);






// enqueue scripts in gutenberg 
function gg_guten_scripts() {
    global $current_screen;

    //////// not for WP 5.8 widgets.. for now
    if($_SERVER["REQUEST_URI"] == '/wp-admin/widgets.php') {
        return;
    }
    ////////
    
    $deps = array(
        'wp-blocks',
        'wp-i18n',
        'wp-element',
    );  
    if($current_screen->base != 'widgets') {
        $deps[] = 'wp-editor';     
    }
    
    
    
	wp_enqueue_script(
		'lc_guten_toolkit',
		GG_URL .'/builders_integration/guten_elements/common.js',
		$deps,
		'1.2.3',
		true
	);
	
	
	
	$shortcodes = array(
		'g-gallery' 	=> 'gallery/gallery',
		'g-collection' 	=> 'collection/collection',
		'g-carousel' 	=> 'carousel/carousel',
		'g-slider' 		=> 'slider/slider',
		'g-itg' 		=> 'itg/itg',
	);
	
	foreach($shortcodes as $key => $script_name) {
		wp_enqueue_script(
			'lcweb/'. $key,
			GG_URL .'/builders_integration/guten_elements/'. $script_name .'.js',
			$deps,
			GG_VER, 
			true
		);
	}
	
	
	
	// Block panels
	$panels = array(
	'main' => array(
			'title' 	=> esc_html__('Main parameters', 'gg_ml'),
			'opened' 	=> true
		),
	);
	wp_localize_script('wp-blocks', 'gg_panels', $panels);
	
	
	
	
	// hook for additional scripts
	if(!did_action('lc_guten_scripts')) {
		$GLOBALS['lc_guten_scripts'] = true;
		do_action('lc_guten_scripts');
	}
}
add_action('enqueue_block_editor_assets', 'gg_guten_scripts');






// hook for custom scripts in gutenberg head
if(!function_exists('lc_scripts_in_guten_head')) {
	function lc_scripts_in_guten_head() {
		do_action('lc_scripts_in_guten_head');
	}
	add_action('admin_head', 'lc_scripts_in_guten_head', 999);
}






// remote handler for ServerSideRender blocks
function gg_guten_handler_common() {
	$code = '';
	
	if(get_option('gg_force_inline_css')) {
		$code .= '<style>'. gg_static::custom_css_less_parser() .'</style>';
	}
	return $code;
}

function gg_guten_atts_compile($atts) {
	$compiled = array();
	foreach($atts as $key => $val) {
		$val = ($val === true || $val === 'true') ? 1 : esc_attr($val);
		$compiled[] = $key .'="'. $val .'"'; 	
	}

	return implode(' ', $compiled);
}

function gg_guten_async_render_check_cap() {
    if(!isset($_POST['page_url'])) {
        wp_die('missing page URL param');   
    }
    
    $query_string = parse_url($_POST['page_url'], PHP_URL_QUERY);
    parse_str($query_string, $query_vars);
    $post_id = isset($query_vars['post']) ? (int)$query_vars['post'] : null;
    
    if(!$post_id || !current_user_can('edit_post', $post_id)) {
        wp_die('forbidden access');   
    }   
}






// fixes WP > 5.5 fields type declaration deprecation 
function gg_fix_block_defs($array) {
    foreach($array as $fid => $fdata) {
        $array[$fid]['lc_type'] = $array[$fid]['type'];
        $array[$fid]['type'] = (in_array($array[$fid]['type'], array('number', 'slider'))) ? 'number' : 'string';    
    }
    
    return $array;
}




// fixing Gutenberg front rendering issue with ToggleControl field
function gg_guten_ToggleControl_val_fix($parsed_block) {
    if(isset($parsed_block['blockName']) && strpos($parsed_block['blockName'], 'lcweb/') !== false && isset($parsed_block['attrs']) && is_array($parsed_block['attrs'])) {
        
        foreach($parsed_block['attrs'] as $key => $val) {
  
            if($val === true) {
                $parsed_block['attrs'][$key] = '1';    
            }
            elseif($val === false) {
                $parsed_block['attrs'][$key] = '';    
            }        
        } 
    }
    
    return $parsed_block;
}
add_filter('render_block_data', 'gg_guten_ToggleControl_val_fix', 10);






///////////////////////////////////////////////////////////////////






function gg_gallery_guten_handler($atts) {
	$code = gg_guten_handler_common();
	return $code . do_shortcode('[g-gallery '. gg_guten_atts_compile($atts) .']');
}



function gg_collection_guten_handler($atts) {
	$code = gg_guten_handler_common();
	return $code . do_shortcode('[g-collection '. gg_guten_atts_compile($atts) .']');
}




function gg_carousel_guten_handler($atts) {
	$code = gg_guten_handler_common();
	
	$code .= '<noscript class="gg_car_guten_atts" data-atts="'. esc_attr(json_encode($atts)) .'"></noscript>';
	return $code . do_shortcode('[g-carousel '. gg_guten_atts_compile($atts) .']');
}
// ajax handler to execute dynamic javascript code on box choice
function gg_car_guten_async_render() {
    gg_guten_async_render_check_cap();
    
	$raw_atts = json_decode(stripslashes($_POST['guten_atts']), true);
	wp_die(
        do_shortcode('[g-carousel '. gg_guten_atts_compile($raw_atts) .']')
    );
}
add_action('wp_ajax_gg_car_guten_async_render', 'gg_car_guten_async_render');




function gg_slider_guten_handler($atts) { 
	// value + unit concat
	$atts['width'] = $atts['width'] . $atts['w_type']; 
	$atts['height'] = $atts['height'] . $atts['h_type']; 
	unset($atts['w_type'], $atts['h_type']);
	
	$code = gg_guten_handler_common();
	return $code . do_shortcode('[g-slider '. gg_guten_atts_compile($atts) .']');
}




function gg_itg_guten_handler($atts) {
	$code = gg_guten_handler_common();
    
	// value + unit concat
	$atts['width'] = $atts['width'] . $atts['w_type']; 
	$atts['img_h'] = $atts['img_h'] . $atts['h_type']; 
	$contents = $atts['ol_txt'];
	
	unset($atts['w_type'], $atts['h_type'], $atts['ol_txt']);
	$code .= '<noscript class="gg_itg_guten_atts" data-atts="'. esc_attr(json_encode($atts)) .'">'. $contents .'</noscript>';
	
	return $code . do_shortcode('[g-itg '. gg_guten_atts_compile($atts) .']'. $contents .'[/g-itg]');
}
// ajax handler to execute dynamic javascript code on box choice
function gg_itg_guten_async_render() {
    gg_guten_async_render_check_cap();
    
	$raw_atts = json_decode(stripslashes($_POST['guten_atts']), true);
	wp_die(
        do_shortcode('[g-itg '. gg_guten_atts_compile($raw_atts) .']'. stripslashes($_POST['ol_txt']) .'[/g-itg]')
	);
}
add_action('wp_ajax_gg_itg_guten_async_render', 'gg_itg_guten_async_render');
