<?php
/**
 * Theme Options and meta-boxes support
 *
 * @package WordPress
 * @subpackage JACK_WELL
 * @since JACK_WELL 1.0.29
 */


// -----------------------------------------------------------------
// -- Meta-boxes
// -----------------------------------------------------------------

if ( !function_exists('jack_well_init_override') ) {
	add_action( 'after_setup_theme', 'jack_well_init_override' );
	function jack_well_init_override() {
		if ( is_admin() ) {
			add_action('admin_enqueue_scripts',	'jack_well_add_override_scripts');
			add_action('save_post',				'jack_well_save_override');
			add_action('jack_well_filter_override_options',  'jack_well_options_override_add_options');
		}
	}
}
	
// Load required styles and scripts for admin mode
if ( !function_exists( 'jack_well_add_override_scripts' ) ) {
	//Handler of the add_action("admin_enqueue_scripts", 'jack_well_add_override_scripts');
	function jack_well_add_override_scripts() {
		// If current screen is 'Edit Page' - load font icons
		$screen = function_exists('get_current_screen') ? get_current_screen() : false;
		if (is_object($screen) && jack_well_allow_override(!empty($screen->post_type) ? $screen->post_type : $screen->id)) {
			wp_enqueue_style( 'jack_well-icons',  jack_well_get_file_url('css/font-icons/css/fontello-embedded.css'), array(), null );
			wp_enqueue_script( 'jquery-ui-tabs', false, array('jquery', 'jquery-ui-core'), null, true );
			wp_enqueue_script( 'jquery-ui-accordion', false, array('jquery', 'jquery-ui-core'), null, true );
			wp_enqueue_script( 'jack_well-options', jack_well_get_file_url('theme-options/theme-options.js'), array('jquery'), null, true );
			wp_localize_script( 'jack_well-options', 'jack_well_dependencies', jack_well_get_theme_dependencies() );
		}
	}
}


// Check if meta box is allow
if (!function_exists('jack_well_allow_override')) {
	function jack_well_allow_override($post_type) {
		return apply_filters('jack_well_filter_allow_override', in_array($post_type, array('page', 'post')), $post_type);
	}
}

// Add overriden options
if (!function_exists('jack_well_options_override_add_options')) {
	add_filter('jack_well_filter_override_options', 'jack_well_options_override_add_options');
	function jack_well_options_override_add_options($list) {
		global $post_type;
		if (jack_well_allow_override($post_type)) {
			$list[] = array(sprintf('jack_well_override_options_%s', $post_type),
				esc_html__('Theme Options', 'jack-well'),
				'jack_well_show_override',
				$post_type,
				$post_type=='post' ? 'side' : 'advanced',
				'default'
			);
		}
		return $list;
	}
}

// Callback function to show fields in meta box
if (!function_exists('jack_well_show_override')) {
	function jack_well_show_override($post=false, $args=false) {
		if (empty($post) || !is_object($post) || empty($post->ID)) {
			global $post, $post_type;
			$mb_post_id = $post->ID;
			$mb_post_type = $post_type;
		} else {
			$mb_post_id = $post->ID;
			$mb_post_type = $post->post_type;
		}
		if (jack_well_allow_override($mb_post_type)) {
			// Load saved options 
			$meta = get_post_meta($mb_post_id, 'jack_well_options', true);
			$tabs_titles = $tabs_content = array();
			global $JACK_WELL_STORAGE;
			// Refresh linked data if this field is controller for the another (linked) field
			// Do this before show fields to refresh data in the $JACK_WELL_STORAGE
			foreach ($JACK_WELL_STORAGE['options'] as $k=>$v) {
				if (!isset($v['override']) || strpos($v['override']['mode'], $mb_post_type)===false) continue;
				if (!empty($v['linked'])) {
					$v['val'] = isset($meta[$k]) ? $meta[$k] : 'inherit';
					if (!empty($v['val']) && !jack_well_is_inherit($v['val']))
						jack_well_refresh_linked_data($v['val'], $v['linked']);
				}
			}
			// Show fields
			foreach ($JACK_WELL_STORAGE['options'] as $k=>$v) {
				if (!isset($v['override']) || strpos($v['override']['mode'], $mb_post_type)===false || $v['type'] == 'hidden') continue;
				if (empty($v['override']['section']))
					$v['override']['section'] = esc_html__('General', 'jack-well');
				if (!isset($tabs_titles[$v['override']['section']])) {
					$tabs_titles[$v['override']['section']] = $v['override']['section'];
					$tabs_content[$v['override']['section']] = '';
				}
				$v['val'] = isset($meta[$k]) ? $meta[$k] : 'inherit';
				$tabs_content[$v['override']['section']] .= jack_well_options_show_field($k, $v, $mb_post_type);
			}
			if (count($tabs_titles) > 0) {
				?>
				<div class="jack_well_options jack_well_override">
					<input type="hidden" name="meta_box_post_nonce" value="<?php echo esc_attr(wp_create_nonce(admin_url())); ?>" />
					<input type="hidden" name="meta_box_post_type" value="<?php echo esc_attr($mb_post_type); ?>" />
					<div id="jack_well_options_tabs" class="jack_well_tabs">
						<ul><?php
							$cnt = 0;
							foreach ($tabs_titles as $k=>$v) {
								$cnt++;
								?><li><a href="#jack_well_options_<?php echo esc_attr($cnt); ?>"><?php echo esc_html($v); ?></a></li><?php
							}
						?></ul>
						<?php
							$cnt = 0;
							foreach ($tabs_content as $k=>$v) {
								$cnt++;
								?>
								<div id="jack_well_options_<?php echo esc_attr($cnt); ?>" class="jack_well_tabs_section jack_well_options_section">
									<?php jack_well_show_layout($v); ?>
								</div>
								<?php
							}
						?>
					</div>
				</div>
				<?php		
			}
		}
	}
}


// Save data from meta box
if (!function_exists('jack_well_save_override')) {
	//Handler of the add_action('save_post', 'jack_well_save_override');
	function jack_well_save_override($post_id) {

		// verify nonce
		if ( !wp_verify_nonce( jack_well_get_value_gp('meta_box_post_nonce'), admin_url() ) )
			return $post_id;

		// check autosave
		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
			return $post_id;
		}

		$post_type = wp_kses_data(wp_unslash(isset($_POST['meta_box_post_type']) ? $_POST['meta_box_post_type'] : $_POST['post_type']));

		// check permissions
		$capability = 'page';
		$post_types = get_post_types( array( 'name' => $post_type), 'objects' );
		if (!empty($post_types) && is_array($post_types)) {
			foreach ($post_types  as $type) {
				$capability = $type->capability_type;
				break;
			}
		}
		if (!current_user_can('edit_'.($capability), $post_id)) {
			return $post_id;
		}

		// Save meta
		$meta = array();
		$options = jack_well_storage_get('options');
		foreach ($options as $k=>$v) {
			// Skip not overriden options
			if (!isset($v['override']) || strpos($v['override']['mode'], $post_type)===false) continue;
			// Skip inherited options
			if (!empty($_POST["jack_well_options_inherit_{$k}"])) continue;
			// Get option value from POST
			$meta[$k] = isset($_POST["jack_well_options_field_{$k}"])
							? jack_well_get_value_gp("jack_well_options_field_{$k}")
							: ($v['type']=='checkbox' ? 0 : '');
		}
		$meta = apply_filters( 'jack_well_filter_update_post_meta', $meta, $post_id );
		update_post_meta($post_id, 'jack_well_options', $meta);
		
		// Save separate meta options to search template pages
		if ($post_type=='page' && !empty($_POST['page_template']) && $_POST['page_template']=='blog.php') {
			update_post_meta($post_id, 'jack_well_options_post_type', isset($meta['post_type']) ? $meta['post_type'] : 'post');
			update_post_meta($post_id, 'jack_well_options_parent_cat', isset($meta['parent_cat']) ? $meta['parent_cat'] : 0);
		}
	}
}
?>