<?php

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






function shrk_add_meta_boxes($cpt) {
	$i = 0;
	
	if( !function_exists( 'add_meta_box' ) ) {
		return false;
	}
	
	$metabox_sections = shrk_get_cpt_meta_options($cpt);
	
	if( !$metabox_sections ) { return false; }
	
	foreach ($metabox_sections as $metabox_section) {
		$i++;
		$context  = isset( $metabox_section['ms_context'] ) ? $metabox_section['ms_context'] : 'advanced';
		$priority = isset( $metabox_section['ms_priority'] ) ? $metabox_section['ms_priority'] : 'high';
		add_meta_box( $cpt . '_' . $i, $metabox_section['ms_label'], 'shrk_create_meta_options', $cpt, $context, $priority, array('fields' => $metabox_section['ms_fields']) );
	}
}

function shrk_get_cpt_meta_options($cpt) {
	$meta_options = shrk_get_meta_options();
	
	if ( !empty ( $meta_options ) && isset( $meta_options[$cpt] ) ) {
		return $meta_options[$cpt];
	}

	return false;
}

function shrk_create_meta_options($post, $metabox) {
	global $post;

	$output = '<input type="hidden" name="shrk_meta_box_nonce" value="' . wp_create_nonce(basename(__FILE__)) . '" />';

	$counter = 0;
	$menu = '';
	$show_default_value = true;

	foreach ($metabox['args']['fields'] as $field_id => $value) :

		$counter++;
		$val          = '';
		$dep_string   = '';
		$class        = array();
		$class_string = '';

		if (isset($value['class'])) {
			$class = explode(' ', $value['class']);
		}

		if ( !empty($field_id) ) {
			$class[] = $field_id;
		}

		if ( !empty($value['dependency']) ) {
			$class[] = 'depents_on';
			$data_deps = array();
			$dep_elem = $value['dependency']['element'];

			foreach ($value['dependency']['value'] as $dep_value) {
				$data_deps[] = $dep_elem . ':' . $dep_value;
			}

			$dep_string = 'data-depend="' . esc_attr( implode('|', $data_deps) ) . '"'; 
		}

		foreach ($class as $c) {
			if (!empty($c)) {
				$class_string .= 'op_' . $c . ' ';                    
			}
		}
		
		$value['name']             = isset( $value['name'] ) ? esc_attr( $value['name'] ) : NULL;
		$value['class']            = isset( $value['class'] ) ? esc_attr( $value['class'] ) : NULL;
		$value['type']             = isset( $value['type'] ) ? esc_attr( $value['type'] ) : NULL;
		$value['std']              = isset( $value['std'] ) ? esc_attr( $value['std'] ) : NULL;
		$value['filetype_allowed'] = isset( $value['filetype_allowed'] ) ? esc_attr( $value['filetype_allowed'] ) : NULL;

		$output .= '<div class="section section-' . $value['type'] . ' ' . esc_attr( $class_string ) . '" ' . $dep_string . '>' . "\n";

		$output .= '<div class="metabox_table">';

		if ( !empty($value['name']) ) {
			$output .= '<div class="heading">';
			$output .= '<h4>' . $value['name'] . '</h4>' . "\n";
			$output .= '</div>';
		}

		$output .= '<div class="option">';

		if ( !empty($field_id) ) {
			$field_id = esc_attr( $field_id );
			$meta_box_value = shrk_get_meta_option( $field_id, $post->ID );
		}

		if ( empty($value['class']) ) {
			$value['class'] = '';
		}

		$value['class'] .= ' shrk-input ';

		$select_value = '';

		switch ( $value['type'] ) :

			case 'text' :
				$std = get_option($field_id);
				if ($std != "") {
					$val = $std;
				}

				$output .= '<input class="of-input ' . esc_attr( $value['class'] ) . '" name="' . esc_attr( $field_id ) . '" id="' . esc_attr( $field_id ) . '" type="' . esc_attr( $value['type'] ) . '" value="' . esc_attr( $meta_box_value ) . '" />';
				break;

			case 'select' :
				$output .= '<select class="' . esc_attr( $value['class'] ) . '" name="' . esc_attr( $field_id ) . '" id="' . esc_attr( $field_id ) . '">';
				$selected_value = shrk_get_meta_option( $field_id, $post->ID );

				if ( empty($selected_value) && !empty($value['std']) ) {
					$selected_value = $value['std'];
				}

				foreach ($value['options'] as $option_value => $option) {
					$selected = '';

					if ($selected_value == $option_value) {
						$selected = ' selected="selected"';
					}

					$output .= '<option' . $selected . ' value="' . esc_attr( $option_value ) . '">';
					$output .= esc_attr( $option );
					$output .= '</option>';
				}
				$output .= '</select>';

				break;

			case 'select_sidebar' :

				$sidebars_array = shrk_get_sidebars();
				
				$output .= '<select class="of-input ' . esc_attr( $value['class'] ) . '" name="' . esc_attr( $field_id ) . '" id="' . esc_attr( $field_id ) . '">';

				$selected_value = shrk_get_meta_option( $field_id, $post->ID );

				$output .= '<option value="default">default</option>';

				if ( $sidebars_array && !empty($sidebars_array ) ) {
					foreach ( $sidebars_array as $option_id => $option_name ) {
						$selected = '';
						if ($selected_value == $option_id) { $selected = ' selected="selected"';
						}
						$output .= '<option' . $selected . ' value="' . esc_attr( $option_id ) . '">';
						$output .= esc_attr( $option_name );
						$output .= '</option>';
					}
				}
				$output .= '</select>';

				break;

			case 'toggle' :
				$post_meta = shrk_get_meta_option( $field_id, $post->ID );

				if (isset($value['std'])) {
					if ($value['std'] == 'on') {
						$checked = ' checked="checked"';
					}
				}
				if (isset($value['std'])) {
					if ($value['std'] == 'off') {
						$checked = '';
					}
				}
				if ($post_meta == 'on') {
					$checked = ' checked="checked"';
				}
				if ($post_meta == 'off') {
					$checked = '';
				}
				
				$output .= '<input name="' . esc_attr( $field_id ) . '" type="checkbox" class="ibutton ' . esc_attr( $value['class'] ) . '" ' . $checked . '/>';

				break;

			case 'range' :
				$output .= '<div class="range-input-container">';
				$output .= '<input type="range" name="' . esc_attr( $field_id ) . '" class="range_value ' . esc_attr( $value['class'] ) . '" value="';

				$val = $value['std'];
				$std = shrk_get_meta_option( $field_id, $post->ID );

				if ($std) {
					$val = $std;
				}

				$output .= esc_attr( $val );

				if (isset($value['min']))
					$output .= '" min="' . esc_attr( $value['min'] );
				if (isset($value['max']))
					$output .= '" max="' . esc_attr( $value['max'] );
				if (isset($value['step']))
					$output .= '" step="' . esc_attr( $value['step'] );

				$output .= '" />';
				$output .= '<input type="text" name="' . esc_attr( $field_id ) . '_preview" readonly="readonly" class="range_preview" value="'.esc_attr( $std ).'"> ';

				if (isset($value['unit']))
					$output .= '<span>' . esc_attr( $value['unit'] ) . '</span>';

				$output .= '</div>';

				$output .= '<div class="clearboth"></div>';

				break;


			case 'radio' :
				$select_value = shrk_get_meta_option( $field_id, $post->ID );

				foreach ($value['options'] as $key => $option) {

					$checked = '';
					if ($select_value != '') {
						if ($select_value == $key) { $checked = ' checked';
						}
					} else {
						if ($value['std'] == $key) { $checked = ' checked';
						}
					}
					$output .= '<input class="of-input of-radio ' . esc_attr( $value['class'] ) . '" type="radio" name="' . esc_attr( $field_id ) . '" value="' . esc_attr( $key  ). '" ' . $checked . ' />' . esc_attr( $option ) . '<br />';

				}

				break;

			case 'upload_image' :
				$output .= '<div class="op-upload-wrap">';
				$output .= shrk_media_uploader_function( $field_id );
				$output .= '</div>';

				break;

			case 'upload_video' :
				$output .= '<div class="op-upload-wrap">';
				$output .= shrk_media_uploader_function( $field_id, '', 'video', $value['filetype_allowed'] );
				$output .= '</div>';
				
				break;

			case 'color' :
				wp_enqueue_style( 'wp-color-picker' );
				wp_enqueue_script( 'wp-color-picker' );
				$val = $value['std'];
				$stored = get_option($field_id);
				if ($stored != "") { $val = $stored; }
				
				$output .= '<div id="' . esc_attr( $field_id ) . '_picker" class="colorSelector"><div></div></div>';
				$output .= '<input class="shrk-input of-color" name="' . esc_attr( $field_id ) . '" id="' . esc_attr( $field_id ) . '" type="text" value="' . esc_attr( $meta_box_value ) . '" />';

				break;

			case 'color-alpha' :
				wp_enqueue_script( 'redux-spectrum-js' );
				wp_enqueue_style( 'redux-spectrum-css' );
				$val = $value['std'];
				$stored = get_option($field_id);
				if ($stored != "") { $val = $stored;
				}
				$output .= '<div id="' . esc_attr( $field_id ) . '_picker" class="colorSelector"><div></div></div>';
				$output .= '<input class="shrk-input of-color-alpha wp-color-result" name="' . esc_attr( $field_id ) . '" id="' . esc_attr( $field_id ) . '" type="text" value="' . esc_attr( $meta_box_value ) . '" placeholder="' . esc_html__( 'Click to set color', 'ux-shop' ) . '" />';
				break;

			case 'info' :
				$default = $value['std'];
				$output .= esc_attr( $default );
				
				break;

			case 'separator' :
				$output .= '<hr class="shrk-separator">';
			
				break;

		endswitch;

		$output .= '</div>';

		$default_val_str = '';
		if ( $show_default_value === true && isset( $value['std'] )) {
			$default_val_str = ' <span class="default-value">(Default: ' . esc_attr( $value['std'] ) . ')</span>';
		}

		$desc_string = ( !empty($value['desc']) ? $value['desc'] : '' );

		if ( $value['type'] != 'info' && $value['type'] != 'separator' ) {
			$output .= '<div class="description">' . wp_kses( $desc_string, shrk_kses_allowed( 'field_desc' ) ) . $default_val_str . '</div>';
		}

		$output .= '</div></div>';

	endforeach;

	echo $output; // Output html tags (escaped above)
}


function shrk_save_meta($post_id) {

	global $post;
	$options          = array();
	$metabox_sections = shrk_get_cpt_meta_options( get_post_type( $post ) );
	
	if( !$metabox_sections ) { return false; }
	
	foreach ($metabox_sections as $metabox_section) {
		$options = array_merge($options, $metabox_section['ms_fields']);
	}
	
	if( empty( $options ) || !post_type_exists( get_post_type( $post ) ) ){
		return $post_id;
	}
	
	// verify nonce
	if(!isset($_POST['shrk_meta_box_nonce'])) { 
		return $post_id; 
	}
	
	if (!wp_verify_nonce($_POST['shrk_meta_box_nonce'], 'global.php')) {
		return $post_id;
	}
	
	// check autosave
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
		return $post_id;
	}

	// check permissions
	if (!current_user_can('edit_post', $post_id)) {
		return $post_id;
	}
	
	foreach ($options as $option_id => $option) {
		if ( !isset($option_id) ) {
			continue;
		}

		$old = shrk_get_meta_option( $option_id, $post_id );
		$new='';
		if( isset($option_id) && isset($_POST[$option_id])) {
			$new = $_POST[$option_id];
		}

		// Sanitize input
		$new = sanitize_option( $option['type'], $new );

		if ($new != $old)  {
			shrk_set_meta_option( $option_id, $new, $post_id );
		}
		if ($new == '' && $option['type']=='toggle') {
			shrk_set_meta_option( $option_id, 'off', $post_id );
		}
	}
}
add_action('save_post', 'shrk_save_meta');

/**
 * Add Sanitization filters for saved input meta
 */
add_filter( 'sanitize_option_text',           'sanitize_text_field' );
add_filter( 'sanitize_option_select',         'sanitize_key' );
add_filter( 'sanitize_option_toggle',         'sanitize_key' );
add_filter( 'sanitize_option_select_sidebar', 'sanitize_key' );
add_filter( 'sanitize_option_range',          'shrk_sanitize_absint' );
add_filter( 'sanitize_option_radio',          'sanitize_key' );
add_filter( 'sanitize_option_upload_image',   'shrk_sanitize_absint' );
add_filter( 'sanitize_option_upload_video',   'shrk_sanitize_absint' );
add_filter( 'sanitize_option_color',          'sanitize_text_field' );
add_filter( 'sanitize_option_color-alpha',    'sanitize_text_field' );
add_filter( 'sanitize_option_info',           'sanitize_text_field' );
add_filter( 'sanitize_option_separator',      'sanitize_text_field' );

/**
 * Sanitization functions
 */
function shrk_sanitize_absint( $input ) {
	$output = absint( $input );
	return $output;
}

/*
 * SMOF modified optionsframework_media_uploader_function
 */
function shrk_media_uploader_function( $id, $std = '', $mod = '', $allowed = '' ){
	$uploader = '';
	$upload = '';
	if ( shrk_get_meta_option( $id ) ) {
		$upload = shrk_get_meta_option( $id );
	}
	
	$hide = '';
	
	if ( $upload != "" ) { $val = $upload; } else { $val = $std; }
	
	$uploader .= '<input class="hidden upload of-input'. ( $allowed != '' ? ' allowed_only allow_' . esc_attr( $allowed ) : '').'" name="'. esc_attr( $id ).'" id="'. esc_attr( $id ) .'" value="'. esc_attr( $val ) .'" />';   
	//Upload controls DIV
	$uploader .= '<div class="upload_button_div">';
	//If the user has WP3.5+ show upload/remove button
	if ( function_exists( 'wp_enqueue_media' ) ) {
		$uploader .= '<span class="button media_upload_button" id="' . esc_attr( $id ) .'">Upload</span>';
		
		$hide = !empty($upload) ? '' : 'hidden';
		$uploader .= '<span class="button remove-image '. $hide.'" id="reset_'. esc_attr( $id ) .'" title="' . esc_attr( $id ) . '">Remove</span>';
	}
	else {
		$output .= '<p class="upload-notice"><i>Upgrade your version of WordPress for full media support.</i></p>';
	}

	$uploader .='</div>' . "\n";

	if ( $mod != 'video' ) {

		//Preview
		if(!empty($upload)){    
			$uploader .= '<div class="screenshot">';
			$uploader .= '<img class="of-option-image" id="image_' . esc_attr( $id ) . '" src="'. esc_url( wp_get_attachment_url( $upload ) ) . '" alt="" />';
			$uploader .= '</div>';
		} else {
			$uploader .= '<div class="screenshot" style="display: none;"></div>';
		}  
		
		$uploader .= '<div class="clear"></div>' . "\n"; 
		

	} else {        
		if ( !empty($upload) ) {
			$uploader .= '<div class="video_preview">'; 
			$uploader.= wp_video_shortcode( 
				array( 
				'src'    => esc_url( wp_get_attachment_url( $upload ) ),
				'width'  => '320',
				) 
			);
			$uploader .= '</div>';
		} else {
			$uploader .= '<div class="video_preview" style="display: none;"></div>'; 
		}
		
		$uploader .= '<div class="clear"></div>' . "\n";
		
	}
	return $uploader;
}

function shrk_get_sidebars() {
	$sidebars = array();
	$sb_names = shrk_get_theme_option( 'shrk_sidebars' );

	if ( $sb_names ) {
		foreach ($sb_names as $sb_name) {
			if ( !empty( $sb_name ) ) {
				$sidebars[sanitize_title($sb_name)] = $sb_name;
			}
		}
	}

	return !empty( $sidebars ) ? $sidebars : false;
}

/**
 * shrk show_sidebar based on selected layout
 */
function shrk_show_sidebar() {
	return apply_filters( 'shrk_show_sidebar', shrk_get_sidebar_class( shrk_get_mso( 'page_layout' ) ) );
}

function shrk_get_sidebar_class( $case, $default = 'right' ) {
	switch ( $case ) {
		case 'no_sidebar':
			return false;
			break;
		case 'left_sidebar':
			return 'left';
			break;
		case 'right_sidebar':
			return 'right';
			break;
		default:
			return $default;                    
			break;
	}
}

function shrk_get_sidebar_id() {
	global $post;
	$sb = 'sidebar-1';  //default sidebar
	
	if ( is_singular() ) {
		$post_sb = shrk_get_meta_option( 'sidebar', $post->ID );
		if ( $post_sb && $post_sb != 'default' ) {
			$sb = $post_sb;
		}
	}

	if ( is_post_type_archive( 'product' ) ) {
		$sb = 'sidebar-products';
	}

	if ( is_singular( 'product' ) ) {
		$sb = 'sidebar-products';
	}

	return $sb;  
}

function shrk_get_main_inner_class() {
	$classes = '';
	$sb = shrk_show_sidebar();

	
	switch ($sb) {
		case 'left':
			$classes .= 'col-lg-9 pull-right';            
			break;
		case 'right':
			$classes .= 'col-lg-9';
			break;
		default:
			$classes .= 'col-lg-12';            
			break;
	}
	
	return $classes;
}

?>