<?php

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

function shrk_sc_section($atts) {

	extract( shortcode_atts( array(
		'section_id'    => false,
	), $atts ) );

	ob_start();

	if ( !function_exists( 'shrk_get_sections' ) ) {
		return '<div>' . esc_html__('Your theme does not support the section shortcode.', 'dvl-uxshop-shortcodes') . '</div>';
	}

	echo '<div class="row sections">';
	shrk_get_sections( $section_id );
	echo '</div>';

	return ob_get_clean();

}

add_action( 'init', function () {
	add_shortcode('shrk_section', 'shrk_sc_section');
});

add_filter( 'shrk_filter_vc_mappings', function ( $shrk_vc_shortcodes ) {

	$shrk_vc_shortcodes["shrk_section"] =  array(
		"name" => esc_html__("Page Section", 'dvl-uxshop-shortcodes'),
		"base" => "shrk_section",
		"icon" => "icon-wpb-shrk",
		"category" => esc_html__('Theme Specific', 'dvl-uxshop-shortcodes'),
		"content_element" => true,
		"params" => array(
			array(
				"type" => "dropdown",
				"class" => "",
				"heading" => esc_html__("Section", 'dvl-uxshop-shortcodes'),
				"param_name" => "section_id",
				"value" => shrk_child_vc_get_posts( array( 'post_type' => 'pagesections' ) )
			)
		),
		'js_view' => 'shrkSectionView',
		'custom_markup' => '<h4 class="wpb_element_title"><i class="vc_element-icon icon-wpb-shrk"></i><span>'. esc_html__( "Section: ", 'dvl-uxshop-shortcodes' ) .'</span><span name="section_id"></span></h4><a href="#" class="edit-section-link" target="_blank">' . esc_html__( 'Edit section', 'dvl-uxshop-shortcodes' ) . '</a>',
	);

	return $shrk_vc_shortcodes;
} );


function shrk_sc_section_scripts() {
	ob_start();
	?>(function ( $ ) {
		if ( typeof(vc) !== 'undefined' ) {
			window.shrkSectionView = vc.shortcode_view.extend( {
				changeShortcodeParams: function ( model ) {
					var params;
					var admin_url = '<?php echo get_admin_url(); ?>';
					//window.shrkSectionView.__super__.changeShortcodeParams.call( this, model );
					params = model.get( 'params' );
					if ( _.isObject( params ) && _.isString( params.section_id ) ) {
						//get selected option text
						var txt = shrk_getKeyByValue( model.view.params.section_id.value, parseInt(params.section_id, 10) );
						this.$el.find( '> .wpb_element_wrapper [name="section_id"]' ).html(txt);

						// section edit link
						this.$el.find( '> .wpb_element_wrapper .edit-section-link' ).attr('href', admin_url+'post.php?post='+params.section_id+'&action=edit');
					}
				}
			} );
		}
	})( window.jQuery );<?php 
	$script = ob_get_clean();

	wp_add_inline_script( 'vc-backend-min-js', $script );
}
add_action( 'admin_enqueue_scripts', 'shrk_sc_section_scripts', 200 );

?>