<?php
/**
 * metabox
 *
 * @package Theme Palace
 * @subpackage Personify Pro
 * @since Personify Pro 1.0
 */

/**
 * Adds a meta box to the post editing screen
 */
function personify_pro_custom_meta() {
    $post_types = array( 'post', 'page' );
    add_meta_box( 'personify_pro_sidebar_layout', esc_html__( 'Content Width', 'personify-pro' ), 'personify_pro_sidebar_position_callback', $post_types, 'side' );
}
add_action( 'add_meta_boxes', 'personify_pro_custom_meta' );


/**
 * Outputs the content of the sidebar position
 */
function personify_pro_sidebar_position_callback( $post ) {
    wp_nonce_field( basename( __FILE__ ), 'personify_pro_nonce' );
    $stored_sidebar_position = get_post_meta( $post->ID, 'personify-pro-sidebar-position', true );

    $sidebar_positions       = personify_pro_sidebar_position();
    foreach ( $sidebar_positions as $value => $url ) :
        echo '<label>';
        echo '<input type="radio" name="personify-pro-sidebar-position" value="' . esc_attr( $value ) . '" ' . checked( $stored_sidebar_position, $value, false ) . ' />';
        echo '<img src="' . esc_url( $url ) . '"/>';
        echo '</label>';
    endforeach;
    
}


/**
 * Saves the sidebar position input
 */
function personify_pro_meta_save( $post_id ) {

    // Checks save status
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ 'personify_pro_nonce' ] ) && wp_verify_nonce( sanitize_key( $_POST[ 'personify_pro_nonce' ] ), basename( __FILE__ ) ) ) ? 'true' : 'false';

    // Exits script depending on save status
    if ( $is_autosave || $is_revision || ! $is_valid_nonce ) {
        return;
    }

    // Checks for input and sanitizes/saves if needed
    if( isset( $_POST[ 'personify-pro-sidebar-position' ] ) ) {
        update_post_meta( $post_id, 'personify-pro-sidebar-position', sanitize_text_field( wp_unslash( $_POST[ 'personify-pro-sidebar-position' ] ) ) );
    }

}
add_action( 'save_post', 'personify_pro_meta_save' );