<?php
/**
 * Magazine Style enqueue scripts
 *
 * @package Magazine Style
 */

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

function magazinestyle_build_page_layout_meta_box( $post ){
    // Make sure the form request comes from WordPress
    wp_nonce_field( basename( __FILE__ ), 'magazinestyle_meta_box_noncepage' );
    // Retrieve the _pagepost_magazinestyle current value
    $current_magazinestyle = get_post_meta( $post->ID, '_pagepost_magazinestyle', 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="magazinestyle_layoutpage" value="<?php echo esc_attr($value); ?>" <?php checked( $current_magazinestyle, $value ); ?> />
                    <?php echo $image; ?>
                </label>
            <?php endforeach; ?>
    <?php
}

/**
 * Store custom field meta box data
 *
 * @param int $post_id The post ID.
 */
function magazinestyle_save_meta_page_data( $post_id ){
    // Verify meta box nonce
    if ( !isset( $_POST['magazinestyle_meta_box_noncepage'] ) || !wp_verify_nonce( $_POST['magazinestyle_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['magazinestyle_layoutpage'] ) ) {
        update_post_meta( $post_id, '_pagepost_magazinestyle', sanitize_text_field( $_POST['magazinestyle_layoutpage'] ) );
    }
}
add_action( 'save_post', 'magazinestyle_save_meta_page_data' );
