<?php

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

if( !function_exists( 'shrk_get_theme_option' ) ) {
	function shrk_get_theme_option( $var, $default=false ) {
		global $shrk_options;

		if ( empty( $shrk_options ) || !isset( $shrk_options[$var] ) ) {
			if ( class_exists( 'ReduxFramework' ) && !isset( $shrk_options ) && !( isset ( $_POST ) && isset ( $_POST['action'] ) && $_POST['action'] == 'heartbeat' ) ) {
				trigger_error('Theme options not set.', E_USER_NOTICE );
			}
			return $default;
		} else {
			return $shrk_options[$var];
		}
	}
}

if(!function_exists('shrk_get_meta_option')) {
	/**
	 * shrk_get_meta_option return specified meta option for given or current postID
	 * @param  string $var   	meta option name
	 * @param  int $post_id 	postID
	 * @return mixed 			meta option value
	 */
	function shrk_get_meta_option( $var, $post_id=null ) {
		global $post;
		$output = '';
		
		if( $post_id ) {
			$output = get_post_meta( $post_id, 'shrk_' . $var, true );
		}

		if ( '' == $output && isset($post->ID) ) {
			$output = get_post_meta( $post->ID, 'shrk_' . $var, true );
		}
		
		if ( '' != $output ) {
			return $output;
		} else {
			return false;
		}
	}
}

if(!function_exists('shrk_set_meta_option')) {
	/**
	 * shrk_set_meta_option set specified meta option for given or current postID
	 * @param  string $var   	meta option name
	 * @param  mixed  $new  	New meta option value
	 * @param  int    $post_id 	postID
	 * @return none
	 */
	function shrk_set_meta_option( $var, $new, $post_id=null ) {
		global $post;
		
		if( $post_id ) {
			update_post_meta( $post_id, 'shrk_' . $var, $new );
		} else {
			update_post_meta( $post->ID, 'shrk_' . $var, $new );
		}
	}
}


if(!function_exists('shrk_get_mso')) {
	/**
	 * shrk_get_mso Gets multiscope options ( tag: mso_var )
	 * Return meta option > theme option singular posttype > theme option posttype > theme option global > $default
	 * if meta option doesnt exist, gets theme option for post type, if theme option for post type
	 * doesnt exist, gets default theme option. 
	 * 
	 * @param  string	$option_name 	option name, for meta and theme options
	 * @param  int 		$postID      	postID
	 * @return mixed					valid result or NULL
	 */
	function shrk_get_mso( $option_name, $postID = null, $default = null ) {
		global $shrk_options;
		global $post;

		$postID = apply_filters( 'shrk_mso_postid', $postID );

		if ( !$postID && @isset($post->ID) ) {
			$postID = $post->ID;
		}

		//Check for post meta option
		if ( $postID && ( get_post_type( $postID ) == 'post' || get_post_type( $postID ) == 'page' ) ) {
			if ( shrk_get_meta_option( $option_name, $postID ) && 'default' <> shrk_get_meta_option( $option_name, $postID )) {
				//return post meta option
				return shrk_get_meta_option( $option_name, $postID );
			} 
		}

		//Check for post_type global & singular option
		if ( $postID && get_post_type( $postID ) ) {

			$pt = get_post_type( $postID );
			$pt_option = $option_name . '_' . $pt;
			$pt_option_singular = $option_name . '_' . $pt . '_singular';

			if ( isset($shrk_options[$pt_option_singular]) && is_singular() ) {
				//return theme option for post type (singular)
				return $shrk_options[$pt_option_singular];
			} 

			if ( isset($shrk_options[$pt_option]) && !is_singular() ) {
				//return theme option for post type
				return $shrk_options[$pt_option];
			} 
		}

		//Check for global option
		if ( isset($shrk_options[$option_name]) ) {
			return $shrk_options[$option_name];
		}

		//No option set!
		return $default;

	}
}

/**
 * Gets page's section from stored meta options
 * returns array of page sections ids
 * or false
 */
if(!function_exists('shrk_get_page_sections')) {
	function shrk_get_page_sections($postID = false) {
		global $shrk_options;
		global $post;

		if ( !$postID ) {        
			if ( isset($post->ID) ) {
				$postID = $post->ID;
			} else {
				$postID = false;
			}
		}
		
		if ( $postID ) {
			$page_sections = shrk_get_mso( 'pagesections', $postID, null);
		}
		
		if ( !empty( $page_sections ) && is_string( $page_sections ) ) {
			$page_sections = explode( ',', $page_sections ); 
		}
		
		if ( !empty( $page_sections ) && is_array( $page_sections ) && count( $page_sections ) > 0 ) {
			return $page_sections;
		} else {
			return false;
		}

	}
}


/**
 * shrk_get_sections()
 * Echoes given sections
 * @param  array/int $sections 	array of section ids or section id
 * @return prints html
 */
if(!function_exists('shrk_get_sections')) {
	function shrk_get_sections($sections = array()) {
		global $shrk_options;
		global $post;

		if ( !post_type_exists( 'pagesections' ) ) {
			return;
		}

		if ( isset($sections) && !is_array($sections) ) {
			$sections = array( intval($sections) );
		}

		if ( !empty($sections) ) {
			$section_posts = new WP_Query(array( 'post_type' => 'pagesections', 'post__in' => $sections, 'nopaging' => true, 'orderby' => 'post__in' ));    
		} 

		if ( isset($section_posts) && $section_posts->have_posts() ) {
			if ( function_exists( 'shrk_vc_enqueue_style' ) ) {
				shrk_vc_enqueue_style( true ); //TODO optimize
			} 
			while ($section_posts->have_posts()) : $section_posts->the_post(); 
				get_template_part( 'content', 'section' ); 
			endwhile; // end of the loop. 
			wp_reset_postdata(); 
		}
	}
}






function shrk_has_visible_sections() {
	$pcv = shrk_get_mso( 'page_content_visibility', null, 'sections_content' );
	return ( $pcv == 'sections' || $pcv == 'sections_content' ) && shrk_has_sections() ? true : false;
}


function shrk_has_sections() {
	return shrk_get_page_sections() ? true : false;
}


if(!function_exists('shrk_remove_empty_from_array')) {
	function shrk_remove_empty_from_array($arr) {
		$new_arr = array();
		
		foreach ($arr as $key => $value) {
			if ( !empty($value) && trim($value) != '' ) {
				$new_arr[] = $value;
			}
		}
		
		// WARNING: also removes keys.
		return $new_arr;
	}
}

if(!function_exists('shrk_get_tax_slug_list')) {
	function shrk_get_tax_slug_list($postid, $taxonomy) {
		$arr = wp_get_post_terms( $postid, $taxonomy );
		$new_arr = array();

		foreach ($arr as $key => $value) {
			$new_arr[] = $value->slug;
		}
		
		return implode(' ', $new_arr);
	}
}

/**
 * Javascript objects
 */
if(!function_exists('shrk_setup_javascript_objects')) {
	function shrk_setup_javascript_objects() {
		global $shrk_options;
		
		$shrk_ajax_errors = array(
			'general_error' => esc_html__('Error loading the selected element.', 'ux-shop'),
		);

		$shrk_js_text_strings = array(
			'new_label' => esc_html_x('New', 'Label for new menu items', 'ux-shop'),
			);
		
		$shrk_options_js = array(
			'theme_dir_url'     => get_template_directory_uri()
		);

		$redux_options_to_js = apply_filters( 'shrk_redux_options_to_js', array('sections_padding', 'sections_radius', 'main_theme_color' ) );

		foreach ($redux_options_to_js as $option) {
			if ( !empty( $shrk_options[$option] ) ) {
				$shrk_options_js[$option] = $shrk_options[$option];
			}
		}

		$wp = array();
		if ( WP_DEBUG ) {
			$wp['wp_debug'] = true;
		}

		$scr_handle = is_admin() ? 'shrk-admin-scripts.js' : 'shrk-theme-js';

		wp_localize_script( $scr_handle, 'shrk', array( 
			'ajax'          => array( 
				'ajaxurl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'shrk_nonce' )
				),
			'ajax_errors'   => $shrk_ajax_errors,
			'wp'            => $wp,
			'theme_options' => $shrk_options_js,
			'text_strings'  => $shrk_js_text_strings
		) );
			
	}
	add_action( 'wp_enqueue_scripts', 'shrk_setup_javascript_objects', 20 ); //priority after main wp_enqueue_scripts call
	add_action( 'admin_enqueue_scripts', 'shrk_setup_javascript_objects', 20 ); //priority after main wp_enqueue_scripts call
}

if(!function_exists('shrk_get_portfolio_taxonomies')) {
	function shrk_get_portfolio_taxonomies() { // used initially in gallery shortcode
		$arr = array();
		foreach ( get_terms( 'portfolio'.'-tax' ) as $tax_term ) :
			if ( empty($tax_term->name) ) { continue; }
			$arr[$tax_term->name] = $tax_term->slug;  
		endforeach;
		
		return $arr;
	}
}

if(!function_exists('shrk_ago')) {
	function shrk_ago($time) {
		$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
		$lengths = array("60","60","24","7","4.35","12","10");
		
		$now = time();
		
		$difference     = $now - $time;
		$tense         = "ago";
		
		for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
			$difference /= $lengths[$j];
		}
		
		$difference = round($difference);
		
		if($difference != 1) {
			$periods[$j].= "s";
		}
		
		return "$difference $periods[$j] ago ";
	}
}

function shrk_simple_minify($str) {
	return preg_replace( '/\r|\n|\t/', '', $str );
}

/**
 * Returns an array with all the menu items that
 * have the mega menu property set.
 * 
 * @return array            Array of menu items
 */
function shrk_get_mmenu_items() {
	$mmenu_items = array();
	$args = array(
		'post_type'  => 'nav_menu_item',
		'meta_query' => array(
			array(
				'key'     => '_shrk_menu_mmenu_active',
				'value'   => '1',
				'compare' => '=',
				)
			)
		);
	$query = new WP_Query($args);
	
	while($query->have_posts()) : $query->the_post();
		$menu_id    = get_the_ID();
		$menu_title = get_the_title();
		$fw         = get_post_meta( $menu_id, '_shrk_menu_mmenu_fullwidth', true );

		if ( empty( $menu_title ) ) {
			$post_id    = get_post_meta( $menu_id, '_menu_item_object_id', true );
			$menu_title = get_the_title( $post_id );
		}

		$mmenu_items[$menu_id] = array(
			'menu_title' => $menu_title,
			'fullwidth'  => $fw
			);
	endwhile;
	wp_reset_postdata();

	return $mmenu_items;
}

/**
 * Return allowed html tags
 * for use in wp_kses in relation to $context
 * 
 * @param  string $context the context to get allowed tags for
 * @return array           the array of allowed tags
 */
function shrk_kses_allowed( $context = NULL ) {
	global $allowedposttags;
	$default = array(
		'a' => array(
			'href'  => array(),
			'class' => array(),
			'title' => array(),
			),
		'span' => array(
			'class' => array(),
			),
		'time' => array(
			'datetime' => array()
			),
		'abbr' => array( 
			'title' => true 
			),
		);

	switch ( $context ) {
		case 'field_desc':
			return array(
				'strong' => array(),
				'em'     => array(),
				'b'      => array(),
				'i'      => array(),
				'br'     => array(),
				'a'      => array(
					'href' => array()
					)
				);
			break;
		case 'meta':
			return $default;
			break;
		case 'link':
			return array( 'a' => array(
				'href'   => array(),
				'class'  => array(),
				'title'  => array(),
				'target' => array(),
				)
			); 
			break;
		case 'shortcode': 
			$post_tags = $allowedposttags;

			$post_tags['a'] = array(
				'href'              => true,
				'rel'               => true,
				'rev'               => true,
				'name'              => true,
				'target'            => true,
				'class'             => true,
				'data-product-id'   => true,
				'data-product_id'   => true,
				'data-product_sku'  => true,
				'data-product-type' => true
				);

			$post_tags['div'] = array(
				'align'             => true,
				'dir'               => true,
				'lang'              => true,
				'xml:lang'          => true,
				'style'             => true,
				'class'             => true
				);

			$post_tags['input'] = array(
				'value'            => true,
				'name'             => true,
				'type'             => true,
				'id'               => true,
				'class'            => true,
				'placeholder'      => true,
				'data-loader-icon' => true,
				'data-min-char'    => true
				);

			return $post_tags;
			break;
		default:
			return $default;
			break;
	}
}

/**
 * Get size information for all currently-registered image sizes.
 *
 * @global $_wp_additional_image_sizes
 * @uses   get_intermediate_image_sizes()
 * @return array $sizes Data for all currently-registered image sizes.
 */
function shrk_get_image_sizes_array() {
	global $_wp_additional_image_sizes;

	$sizes = array();

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

	return $sizes;
}

/**
 * Get size information for a specific image size.
 *
 * @uses   get_image_sizes()
 * @param  string $size The image size for which to retrieve data.
 * @return bool|array $size Size data about an image size or false if the size doesn't exist.
 */
function shrk_get_image_size( $size ) {
	$sizes = shrk_get_image_sizes_array();

	if ( isset( $sizes[ $size ] ) ) {
		return $sizes[ $size ];
	}

	return false;
}

/**
 * Returns the image ratio for a give image id and size.
 * Uses values returned by wp_get_attachment_image_src or
 * PHP's getimagesize if height is > 9999, as WC may filter
 * it to have uncropped thumbnails (after WC 3.3)
 * 
 * @param  int $image_id The ID of the attachment
 * @param  string $size  The requested image size
 * @return float         The image's aspect ratio
 */
function shrk_get_image_ratio( $image_id, $size = 'thumbnail' ) {
	$image_obj = wp_get_attachment_image_src( $image_id, $size );

	if ( empty( $image_obj ) ) {
		return false;
	}

	if ( empty( $image_obj[2] ) ) {
		$ratio = 1; // Avoid division by zero
	} elseif( $image_obj[2] > 9999 ) {
		$image_size = getimagesize( $image_obj[0] );
		$ratio = !empty( $image_size[0] ) && !empty( $image_size[1] ) ? round( $image_size[0] / $image_size[1], 2 ) : 1;
	} else {
		$ratio = round( $image_obj[1] / $image_obj[2], 2 );
	}

	return $ratio ? $ratio : 1;
}


?>