<?php
/**
 * Core functions for admin side
 *
 * @package Plug Shop WordPress Theme
 * @author Pressfore - www.pressfore.com
 *
 */

/**
 *  Register Dynamic post template selection
 *
 */
function plug_shop_register_post_meta() {
	add_meta_box(
			'plug_shop_pmeta',
			esc_html__('Post Type Rendering', 'plug-shop'),
			'plug_shop_meta_cb',
			'page',
			'normal',
			'default'
	);
}
add_action('add_meta_boxes', 'plug_shop_register_post_meta');


/**
 * Dynamic post type callback
 *
 * Add a selection of the available post
 * types so that user can select
 * which custom post type want to integrate
 * into this template which will keep original
 * template layout but list custom post type
 */
function plug_shop_meta_cb($post) {
	wp_nonce_field( 'plug_shop_nonce_dynamic', 'plug_shop_meta_page_noncename' );

	$name = 'dynamic_post_type';
	$selected = get_post_meta($post->ID, $name, true );
	$selection = plug_shop_dynamic_post_selection($name, $selected);

	echo wp_kses($selection, array(
		'select' => array(
			'name' => true,
			'id'   => true
		),
		'option' => array(
			'value'    => true,
			'selected' => true
		),
		'p'  => array(
			'class' => true
		)
	));

	do_action( 'plug_shop_dynamic_meta_box', $post->ID );
}

/**
* Post meta save
*
*/
function plug_shop_save_post_meta($post_id) {
	if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
		return $post_id;
	}

	if ( empty( $_POST ) && ! wp_verify_nonce( 'plug_shop_nonce_dynamic', 'plug_shop_meta_page_noncename' ) ) {
		return false;
	}

    if( isset( $_POST['post_type'] ) ) {
        // Check permissions to edit pages and/or posts
	    if ( 'page' == $_POST['post_type'] ) {
	        if ( !current_user_can( 'edit_page', $post_id ) || !current_user_can( 'edit_post', $post_id ))
	          return $post_id;
	    } 

		$names = apply_filters( 'plug_shop_post_meta_save', array( 'dynamic_post_type' ) );

	    foreach( $names as $name ) {
		    $meta = isset( $_POST[$name] ) ? wp_unslash( $_POST[$name] ) : false;

		    update_post_meta( $post_id, $name, sanitize_text_field($meta) );
	    }
	}
}
add_action('save_post', 'plug_shop_save_post_meta');