<?php
/**
Template Name: Blog
**/

$full_width = get_post_meta($post->ID, 'enable_fullwidth', true);
$sidebar_position = get_post_meta($post->ID, 'sidebar_position', true);

if(!$full_width) {
	$full_width = 'col-lg-8 col-md-8 col-sm-12';
} else {
	$full_width = 'col-lg-12';
}

$item_count = get_post_meta($post->ID, 'blog_item_limit', true);
$order = get_post_meta($post->ID,'blog_item_order', true);
$orderby = get_post_meta($post->ID,'blog_item_orderby', true);
$offset = get_post_meta($post->ID,'blog_item_offset', true);
$blog_show_category = get_post_meta($post->ID,'blog_show_category', true);

?>

<?php get_header(); ?>

<?php if($full_width && $sidebar_position === 'left') { get_sidebar(); } ?>

    <!-- Blog Content Starts -->
    <div class="<?php echo $full_width; ?>">
			<?php

			// $paged = get_query_var('paged') ? get_query_var('paged') : 1;
			// $wpbp = new WP_Query(array('post_type' => 'post', 'posts_per_page' => $item_count, 'category_name' => $blog_show_category, 'paged' => $paged, 'offset' => $offset, 'orderby' => $orderby, 'order' => $order));

			// Pagination Issue Fixed
			global $paged;
			if( get_query_var( 'paged' ) )
				$my_page = get_query_var( 'paged' );
			else {
				if( get_query_var( 'page' ) )
					$my_page = get_query_var( 'page' );
				else
					$my_page = 1;
				set_query_var( 'paged', $my_page );
				$paged = $my_page;
			}

			// default loop here, if applicable, followed by wp_reset_query();

			$args = array(
				// other query params here,
				'paged' => esc_attr($my_page),
				'post_type' => 'post',
				'posts_per_page' => (int)$item_count,
				'category_name' => esc_attr($blog_show_category),
				'offset' => (int)$offset,
				'orderby' => esc_attr($orderby),
				'order' => esc_attr($order)
			);

			$wpbp = new WP_Query( $args );

			if ($wpbp->have_posts()) : while ($wpbp->have_posts()) : $wpbp->the_post(); ?>
				<?php get_template_part( 'content', get_post_format() ); ?>
			<?php endwhile; ?>

			<?php else : ?>
				<?php get_template_part( 'content', 'none' ); ?>
			<?php endif; ?>

			<!-- Paged navigation -->
			<div class="post-navigation">
				<?php
					if ( function_exists('wp_pagenavi')) {
							wp_pagenavi(array( 'query' => $wpbp ) );
							wp_reset_postdata();	// avoid errors further down the page
					}
				?>
			</div>

		</div> <!-- end col-lg-8 -->

<?php if($full_width && $sidebar_position === 'right') { get_sidebar(); } ?>

<?php get_footer(); ?>