<?php
/**
 * Title Bar metabox.
 *
 * Prints the box content.
 *
 * @package Ef Practical
 * 
 * @param WP_Post $post The object for the current post/page.
 */
function practical_title_bar_cb( $post ) {
    
    $title_bar = 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_title_bar_save', 'practical_title_bar_nonce' );
    
    /*
	 * Use get_post_meta() to retrieve an existing value
	 * from the database and use the value for the form.
	 */
    $store_title_bar_option = get_post_meta( $post->ID, 'practical-title-bar', true );
    if( ! $store_title_bar_option ) { $store_title_bar_option = 'default'; }
    
    $title_bar_options = $title_bar;
?>
    
    <p>
    <select name="practical-title-bar" id="practical-title-bar">
        <?php foreach ( $title_bar_options as $title_bar_option => $value ) { ?>
            <option value="<?php echo esc_attr( $title_bar_option );?>"
                <?php if ( isset ( $store_title_bar_option ) ) selected( $store_title_bar_option, $title_bar_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_title_bar_save( $post_id ) {
    
    // Check if our nonce is set.
	if ( ! isset( $_POST['practical_title_bar_nonce'] ) ) {
		return;
	}
    
    // Verify that the nonce is valid.
	if ( ! wp_verify_nonce( sanitize_key( $_POST[ 'practical_title_bar_nonce' ] ), 'practical_title_bar_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-title-bar' ] ) ) {
        update_post_meta( $post_id, 'practical-title-bar', sanitize_text_field( wp_unslash( $_POST[ 'practical-title-bar' ] ) ) );
    }
    
}
add_action( 'save_post', 'practical_title_bar_save' );