<?php

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

/**
 * shrk_bind_wpb_composer_shortcodes maps custom theme shortocdes
 * @return none
 */
function shrk_bind_wpb_composer_shortcodes() {
	if ( !function_exists( 'vc_map' ) ) {
		//if visual composer not installed and active abort.
		return false;
	}

	require_once( 'vc_map.php' );
	require_once( 'vc_parameters.php' );

	$vc_maps = shrk_vc_maps();

	foreach ($vc_maps as $sc => $vc_map) {
		vc_map( $vc_map );
	}

	//Set custom shortcode templates directory
	vc_set_shortcodes_templates_dir( dirname(__FILE__) . '/vc_templates/' );

	shrk_vc_theme_styles();
	shrk_vc_custom_heading_params();
}
add_action( 'init', 'shrk_bind_wpb_composer_shortcodes', 15);

/**
 * Get (all) Woocommerce products for selector param
 * @return array
 */
function shrk_vc_get_products() {
	$args = array('posts_per_page' => -1, 'post_type' => 'product', 'orderby' => 'name', 'order' => 'ASC');
	$products = get_posts( $args );
	$array_out = array();

	foreach ($products as $product) {
		if( function_exists( 'wc_get_product' ) ) {
			$product_obj = wc_get_product( $product->ID );
		}
		else{
			$product_obj = get_product( $product->ID );
		}

		$sku = $product_obj->get_sku();
		$sku = $sku == '' ? '' : ' (SKU: '. $sku .')';
		$array_out[$product->ID] = $product->post_title . $sku;
	}

	return $array_out;
}

/**
 * Get woocommerce product categories for selector param
 * @return array of terms objects
 */
function shrk_vc_get_product_categories() {
	$terms = get_terms( 'product_cat', array( 'hide_empty' => false ) );
	return $terms;
}

/**
 * Get woocommerce product attributes
 * @return array 
 */
function shrk_vc_get_product_attributes() {
	if ( !function_exists('wc_get_attribute_taxonomies') ) {
		return array();
	}

	$attribute_taxonomies = wc_get_attribute_taxonomies();
	$arr = array();

	foreach ($attribute_taxonomies as $tax) {
		$arr[$tax->attribute_label] = $tax->attribute_name;
	}

	return $arr;
}

/**
 * shrk_child_vc_get_posts Generic fn to return posts
 * @param  [array] $args query arguments
 * @return [array]       [vc array]
 */
function shrk_child_vc_get_posts( $args ) {
	$defaults = array(
		'posts_per_page' => -1, 
		'post_type' => 'post', 
		'orderby' => 'name', 
		'order' => 'ASC',
		'suppress_filters' => 0 //wpml get only specific language
	);
	$args = wp_parse_args( $args, $defaults );

	$posts = get_posts( $args );
	$array_out = array();

	foreach ($posts as $post) {
		$array_out[$post->post_title] = $post->ID;
	}

	return $array_out;
}


/**
 * Appends theme color & style options to the elements below
 * @return none
 */
function shrk_vc_theme_styles() {
	$el_style = array( //TODO check other elements
		'vc_btn',
		'vc_tta_tabs',
		'vc_tta_accordion',
		'vc_tta_tour', 
		);

	$el_color = array(
		'vc_btn',
		'vc_separator',
		'vc_text_separator',
		'vc_icon',
		);

	foreach ($el_style as $vc_el) {
		shrk_add_vc_theme_style( $vc_el );
	}

	foreach ($el_color as $vc_el) {
		shrk_add_vc_theme_color( $vc_el );
	}
}

/**
 * Adds 'Theme style' option to given VC Elemeent
 * @param  $vc_element the vc elemeent to add to
 * @return none
 */
function shrk_add_vc_theme_style( $vc_element ) {
	$param = WPBMap::getParam( $vc_element, 'style');
	
	$param['value'][esc_html__( 'Theme style', 'dvl-uxshop-shortcodes' )] = 'theme-style';
	$param['std']                                = 'theme-style';
	vc_update_shortcode_param( $vc_element, $param );
}

/**
 * Adds 'Theme color' option to given VC Elemeent
 * @param  $vc_element the vc elemeent to add to
 * @return none
 */
function shrk_add_vc_theme_color( $vc_element ) {
	$param = WPBMap::getParam( $vc_element, 'color');
	
	$param['value'][esc_html__( 'Theme color', 'dvl-uxshop-shortcodes' )] = 'theme-color';
	$param['value'][esc_html__( 'Theme color (secondary)', 'dvl-uxshop-shortcodes' )] = 'theme-color-secondary';
	$param['std']                                = 'theme-color';
	vc_update_shortcode_param( $vc_element, $param );
}

/**
 * Add & modify options of the custom heading VC element
 * @return none
 */
function shrk_vc_custom_heading_params() {
	// Changes weights of default params
	$param = WPBMap::getParam( 'vc_custom_heading', 'source');
	$param['weight'] = 10;
	vc_update_shortcode_param( 'vc_custom_heading', $param );

	$param = WPBMap::getParam( 'vc_custom_heading', 'link');
	$param['weight'] = 7;
	vc_update_shortcode_param( 'vc_custom_heading', $param );

	$param = WPBMap::getParam( 'vc_custom_heading', 'font_container');
	$param['weight'] = 6;
	vc_update_shortcode_param( 'vc_custom_heading', $param );
	
	$param = WPBMap::getParam( 'vc_custom_heading', 'use_theme_fonts');
	$param['weight'] = 5;
	vc_update_shortcode_param( 'vc_custom_heading', $param );

	// replace default textarea with textarea_html
	vc_remove_param( 'vc_custom_heading', 'text');
	vc_add_param( 'vc_custom_heading', array(
		'type'        => 'textarea_html',
		'holder'      => 'div',
		'class'       => 'messagebox_text',
		'heading'     => esc_html__( 'Heading text', 'dvl-uxshop-shortcodes' ),
		'param_name'  => 'content',
		'value'       => esc_html__( 'I am a custom heading. Click edit button to change this text.', 'dvl-uxshop-shortcodes' ),
		'description' => esc_html__( 'Note: Enter simple text only and dont use any content alignment settings. Use the controls below for that. You can use bold/italics styling.', 'dvl-uxshop-shortcodes' ),
		'dependency'  => array(
			'element'  => 'source',
			'is_empty' => true,
		),
		'weight'      => 8
	) );

	// Add responsive heading setting
	vc_add_param( 'vc_custom_heading', array(
	    'type'       => 'dropdown',
	    'heading'    => "Responsive heading setting",
	    'param_name' => 'shrk_resp_heading',
	    'value'      => array( 
			'Not responsive'      => 'no', 
			'Responsive - Big'    => 'large', 
			'Responsive - Medium' => 'medium', 
			'Responsive - Small'  => 'small' 
		),
	    'weight'     => 0,
	    'std'        => 'no' 
	) );

	vc_add_param( 'vc_custom_heading', array(
	    'heading'    => "Theme font",
	    'param_name' => 'shrk_theme_font',
	    'type'       => 'shrk_font_family',
	    'weight'     => 4,
	    'dependency' => array(
	    	'element' => 'use_theme_fonts',
			'value'   => array('yes'),
    	), 
	) );
}

/**
 * Filter function to Modify shortcode classes for custom heading
 * VC elemeent
 *  
 * @param  string $classes the classes to filter
 * @param  string $base    the shortcode base as given by the filter
 * @param  array  $atts    the shortcode atts 
 * @return string          the filtered classes
 */
function shrk_vc_custom_heading_classes( $classes, $base, $atts ) {
	if ( isset( $base ) && $base == 'vc_custom_heading' ) {
		if ( isset( $atts['shrk_resp_heading'] ) && $atts['shrk_resp_heading'] != 'no' ) {
			$classes .= ' responsive-heading' . ' ' . esc_attr( $atts['shrk_resp_heading'] );
		}
	}

	return $classes;
}
add_filter( 'vc_shortcodes_css_class', 'shrk_vc_custom_heading_classes', 10, 3 );

/**
 * Get image dimension in image sizes array (vc)
 * @return array
 */
function shrk_vc_get_image_dimensions( $arr ) {
	global $_wp_additional_image_sizes;

	$sizes = array();
	$get_intermediate_image_sizes = $arr;

	foreach( $get_intermediate_image_sizes as $_size ) {
		if ( in_array( $_size, array( 'thumbnail', 'medium', 'large' ) ) ) {
			$sizes[ $_size . ' [' . get_option( $_size . '_size_w' ) . 'x' . get_option( $_size . '_size_h' ) . ((bool) get_option( $_size . '_crop' ) ? ' cropped' : '') . ']' ] = $_size;
		} elseif ( isset( $_wp_additional_image_sizes[ $_size ] ) ) {
			$sizes[ $_size . ' [' . $_wp_additional_image_sizes[ $_size ]['width'] . 'x' . $_wp_additional_image_sizes[ $_size ]['height'] . ((bool) $_wp_additional_image_sizes[ $_size ]['crop'] ? ' cropped' : '') . ']'  ] = $_size;
		}
	}

	return $sizes;
}

/**
 * Get public post types for vc parameters
 * in a vc compatible array.
 * @return array
 */
function shrk_vc_get_public_posttypes( $keys_only = false ) {
	array_merge( array('post', 'page'), get_post_types( array( 'public' => true, '_builtin' => false ) ) );

	$retval = array();
	$exclude = array( 'pagesections', 'attachment' );
	$posttypes = get_post_types( array( 'public' => true ), 'objects' );

	foreach ($posttypes as $pt_key => $pt) {
		if ( !in_array($pt_key, $exclude) ) {
			if ( $keys_only ) {
				$retval[] = $pt_key;
			} else {
				$retval[$pt->labels->name] = $pt_key;				
			}
		}
	}

	return $retval;
}

/**
 * Get taxonomy terms for specific post type and related taxonomy in shrk_vc_get_mini_pt_tax_map
 */
function shrk_vc_get_carousel_taxonomies( $pt ) {
	$retval = array();
	$pt_tax_map = shrk_vc_get_mini_pt_tax_map();

	if ( post_type_exists( $pt) ) {
		if ( isset( $pt_tax_map[$pt] ) ) {
			$terms = get_terms( $pt_tax_map[$pt] );
			foreach ($terms as $term) {
				$retval[$term->name] = $term->slug;
			}

			return $retval;
		}
	} 	

	return null;
}

/**
 * Returns an array with the posttype -> taxonomies mappings for the content carousel filter
 */
function shrk_vc_get_mini_pt_tax_map() {
	return array(
		"post" => "category",
		"portfolio" => "portfolio-tax",
		"product" => "product_cat"
	);
}

/**
 * shrk_vc_enqueue_style enqueues vc stylesheet in pages where vc doesnt
 * @param  boolean $force_enqueue	force enqueue regardless of post content
 * @param  [type]  $post          	post to check content for vc elements if force=false
 * @return none
 */
function shrk_vc_enqueue_style( $force_enqueue = false ,$post = null ) {
	if( $force_enqueue || ( $post && preg_match('/vc_row/', $post->post_content) ) ) {
		wp_enqueue_style('js_composer_front');
	}
	wp_enqueue_style('js_composer_custom_css');	
}

/* Disable update and license nags. The plugin is bundled. */
function shrk_vc_disable_update_nags() {
	if ( function_exists( 'vc_license' ) ) {
		$vc_license = vc_license();
		remove_action( 'admin_notices', array( $vc_license, 'adminNoticeLicenseActivation' ) );
	}
}
add_action( 'vc_after_init', 'shrk_vc_disable_update_nags', 50 );

/* Set post types to enable VC for */
function shrk_vc_init_set_content_types() {
	// Setup which post types VC will be activated for
	update_option('wpb_js_content_types', array('page', 'pagesections', 'product', 'portfolio'));
}
add_action( 'shrk_theme_first_install', 'shrk_vc_init_set_content_types' );

/**
 * Hook vc functions to handle css output for printed sections
 * used in section output
 * 
 * @return none
 */
function shrk_vc_sections_frontcss() {
	$css_parts        = array();
	$sections_printed = shrk_vc_get_sections_to_print();

	if ( empty( $sections_printed ) || !function_exists( 'shrk_simple_minify' ) ) {
		return;
	}
	
	foreach ($sections_printed as $section_id) {
		$css_parts[] = shrk_vc_addPageCustomCss( $section_id );
		$css_parts[] = shrk_vc_addShortcodesCustomCss( $section_id );
	}

	if ( !empty( $css_parts ) ) {
		$vc_css = shrk_simple_minify( implode(' ', $css_parts) );
		wp_add_inline_style( 'shrk-style-overrides', $vc_css );
	}
}

/**
 * Returns an array with all the page sections used in the current page
 *
 * @since 1.0.2
 * 
 * @return array An array of post Id's
 */
function shrk_vc_get_sections_to_print() {
	global $shrk_options, $post;
	$sections = array();

	if ( !function_exists( 'shrk_get_mso' ) ) {
		return array();
	}

	if ( isset( $shrk_options['footer_pre_sections'] ) && is_array( $shrk_options['footer_pre_sections'] ) ) {
		$sections = array_merge( $sections, $shrk_options['footer_pre_sections'] );
	}

	if ( isset( $shrk_options['footer_widgets_sections'] ) && is_array( $shrk_options['footer_widgets_sections'] ) ) {
		$sections = array_merge( $sections, $shrk_options['footer_widgets_sections'] );
	}

	if ( isset( $shrk_options['footer_socket_sections'] ) && is_array( $shrk_options['footer_socket_sections'] ) ) {
		$sections = array_merge( $sections, $shrk_options['footer_socket_sections'] );
	}
	
	if ( shrk_get_mso( 'pagesections' ) && is_array( shrk_get_mso( 'pagesections' ) ) ) {
		$sections = array_merge( $sections, shrk_get_mso( 'pagesections' ) );
	}
	
	// Get section id's from shortcodes in post's content
	$sections = array_merge( $sections, shrk_vc_get_sections_printed( $post ) );
	
	if ( is_array( $sections ) ) {
		foreach ($sections as $key => $section) {
			$sections[$key] = absint( $section );
		}
	}

	return $sections;
}

/**
 * Returns an array of all pagesection Id's
 * found in shortcode args used in the content 
 * of the given post.
 *
 * @since 1.0.2
 * 
 * @param  object $post the post object whose content to search in
 * @return array An array of post Id's
 */
function shrk_vc_get_sections_printed( $post ) {
	// Shortcode regex patter to return only `shrk_section` shortcodes
	$pattern  = '\[(\[?)(shrk_section)(?![\w-])([^\]\/]*(?:\/(?!\])[^\]\/]*)*?)(?:(\/)\]|\](?:([^\[]*+(?:\[(?!\/\2\])[^\[]*+)*+)\[\/\2\])?)(\]?)';
	$sections = array();

	if ( isset( $post->post_content ) && preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) ) {
		foreach ( $matches[3] as $val ) {
			$args = explode( '=', $val );
			if ( trim( $args[0] ) == 'section_id' && absint( str_replace( '"', '', $args[1] ) ) ) {
				$sections[] = absint( str_replace( '"', '', $args[1] ) );
			}
		}
	}

	return array_unique( $sections );
}

/**
 * Add VC page custom css
 *
 * method stolen from Vc_Base class, modified to work on non singular pages
 * that have VC elements in pagesections
 * 
 * @param integer $id the object (post) id
 * @return string of css rules
 * 
 */
function shrk_vc_addPageCustomCss( $id = null ) {
	if ( ! $id ) {
		return '';
	}

	$post_custom_css = get_post_meta( $id, '_wpb_post_custom_css', true );
	if ( ! empty( $post_custom_css ) ) {
		$post_custom_css = strip_tags( $post_custom_css );
		return $post_custom_css;
	}
}

/**
 * Add VC custom shortcode css
 *
 * method stolen from Vc_Base class, modified to work on non singular pages
 * that have VC elements in pagesections
 * 
 * @param integer $id the object (post) id
 * @return string of css rules
 * 
 */
function shrk_vc_addShortcodesCustomCss( $id = null ) {
	if ( ! $id ) {
		return '';
	}

	$shortcodes_custom_css = get_post_meta( $id, '_wpb_shortcodes_custom_css', true );
	if ( ! empty( $shortcodes_custom_css ) ) {
		$shortcodes_custom_css = strip_tags( $shortcodes_custom_css );
		return $shortcodes_custom_css;
	}
}

function shrk_vc_extend_WPBShortcodes_classes() {
	if ( class_exists('WPBakeryShortCodesContainer') ) {
		class WPBakeryShortCode_shrk_section_slider extends WPBakeryShortCodesContainer {
		}
	}

	if ( class_exists('WPBakeryShortCode') ) {
		class WPBakeryShortCode_shrk_section extends WPBakeryShortCode {
		}
	}
}
add_action( 'init', 'shrk_vc_extend_WPBShortcodes_classes' );

function shrk_vc_disable_nonce_check() {
	// For guests only
	if ( !is_user_logged_in() ) {
		add_filter('vc_grid_get_grid_data_access','__return_true');
	}
}
add_action( 'init', 'shrk_vc_disable_nonce_check' );

/**
 * Filter to add styles to VC Custom heading shortcode
 * for theme fonts
 * 
 * @param  array $styles The styles to filter
 * @param  array $atts   The shortcodes attributes
 * @return array         The filtered array of styles
 */
function shrk_vc_custom_heading_font_styles( $styles, $atts ) {
	
	if ( isset( $atts['shrk_theme_font'] ) && 'default' !== $atts['shrk_theme_font'] ) {

		$shrk_theme_font = explode( '|', $atts['shrk_theme_font'] );
		
		if ( !empty( $shrk_theme_font[0] ) ) {
			$styles[] = 'font-family: ' . $shrk_theme_font[0];
		}

		if ( !empty( $shrk_theme_font[1] ) ) {
			$font_variants = explode( ':', $shrk_theme_font[1] );

			if ( !empty( $font_variants[0] ) ) {
				$styles[] = 'font-style: ' . $font_variants[0];
			}

			if ( !empty( $font_variants[1] ) ) {
				$styles[] = 'font-weight: ' . $font_variants[1];
			}
		}
	}

	return $styles;
}
add_filter( 'shrk_vc_custom_heading_styles', 'shrk_vc_custom_heading_font_styles', 10, 2 );

?>