<?php
/**
 * Poster enqueue scripts
 *
 * @package Poster
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
function poster_add_page_layout_meta_box( $post ){
    add_meta_box( 'poster_page_meta', __( '<span class="dashicons dashicons-layout"></span> Page Layout', 'poster' ), 'poster_build_page_layout_meta_box', 'page', 'side', 'high' );
}
add_action( 'add_meta_boxes', 'poster_add_page_layout_meta_box' );

function poster_build_page_layout_meta_box( $post ){
    // Make sure the form request comes from WordPress
    wp_nonce_field( basename( __FILE__ ), 'poster_meta_box_noncepage' );
    // Retrieve the _pagepost_poster current value
    $current_poster = get_post_meta( $post->ID, '_pagepost_poster', true );
    $layout_options = array(
        'rsd' => '<img src="' . get_template_directory_uri() . '/images/right.png" alt="Right Sidebar - Default">',
        'ls'  => '<img src="' . get_template_directory_uri() . '/images/left.png" alt="Left Sidebar">',
        'lr'  => '<img src="' . get_template_directory_uri() . '/images/bothsides.png" alt="Left - Right Sidebars">',
        'fc'  => '<img src="' . get_template_directory_uri() . '/images/fullnone.png" alt="Full Content - No Sidebar">'
    );
    ?>
           <?php foreach ($layout_options as $value => $image) : ?>
                <label>
                    <input type="radio" name="poster_layoutpage" value="<?php echo esc_attr($value); ?>" <?php checked( $current_poster, $value ); ?> />
                    <?php echo $image; ?>
                </label>
            <?php endforeach; ?>
    <?php
}

/**
 * Store custom field meta box data
 *
 * @param int $post_id The post ID.
 */
function poster_save_meta_page_data( $post_id ){
    // Verify meta box nonce
    if ( !isset( $_POST['poster_meta_box_noncepage'] ) || !wp_verify_nonce( $_POST['poster_meta_box_noncepage'], basename( __FILE__ ) ) ){
        return;
    }
    // Return if autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
        return;
    }
    // Check the user's permissions
    if ( ! current_user_can( 'edit_post', $post_id ) ){
        return;
    }
    // Store custom fields values
    if ( isset( $_POST['poster_layoutpage'] ) ) {
        update_post_meta( $post_id, '_pagepost_poster', sanitize_text_field( $_POST['poster_layoutpage'] ) );
    }
}
add_action( 'save_post', 'poster_save_meta_page_data' );
