<?php
/**
 * Author Info metabox.
 *
 * Prints the box content.
 *
 * @package Ef Practical
 * 
 * @param WP_Post $post The object for the current post/page.
 */
function practical_author_info_cb( $post ) {
    
    $author_info = array(
        'default' => esc_html__( 'Default (from Theme Options)', 'ef-practical' ),
        'show'    => esc_html__( 'Show', 'ef-practical' ),
        'hide'    => esc_html__( 'Hide', 'ef-practical' ),
    );
    
    // Add a nonce field so we can check for it later.
	wp_nonce_field( 'practical_author_info_save', 'practical_author_info_nonce' );
    
    /*
	 * Use get_post_meta() to retrieve an existing value
	 * from the database and use the value for the form.
	 */
    $store_author_info_option = get_post_meta( $post->ID, 'practical-author-info', true );
    if( ! $store_author_info_option ) { $store_author_info_option = 'default'; }
    
    $author_info_options = $author_info;
?>
    
    <p>
        <select name="practical-author-info" id="practical-author-info">
            <?php foreach ( $author_info_options as $author_info_option => $value ) { ?>
                <option value="<?php echo esc_attr( $author_info_option );?>"
                    <?php if ( isset ( $store_author_info_option ) ) selected( $store_author_info_option, $author_info_option ); ?>><?php echo esc_html( $value ); ?>
                </option>
            <?php } ?>
        </select>
    </p>
    
<?php
}

/**
 * When the post is saved, saves our custom data.
 *
 * @param int $post_id The ID of the post being saved.
 */
function practical_author_info_save( $post_id ) {
    
    // Check if our nonce is set.
	if ( ! isset( $_POST['practical_author_info_nonce'] ) ) {
		return;
	}
    
    // Verify that the nonce is valid.
	if ( ! wp_verify_nonce( sanitize_key( $_POST[ 'practical_author_info_nonce' ] ), 'practical_author_info_save' ) ) {
		return;
	}
    
    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
    
    // Check the user's permissions.
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}
    
    if( isset( $_POST[ 'practical-author-info' ] ) ) {
        update_post_meta( $post_id, 'practical-author-info', sanitize_text_field( wp_unslash( $_POST[ 'practical-author-info' ] ) ) );
    }
    
}
add_action( 'save_post', 'practical_author_info_save' );