<?php
/**
 * Wrock Metro enqueue scripts
 *
 * @package Wrock Metro
 */

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

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

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