<?php

function blog_func( $atts, $content ) {
	extract(shortcode_atts( array(
		'per_page'    => 5,
		'categories'  => '',
		'type'        => 'default',
		'pagination'  => 'default',
		'wrapper'     => 'on',
		'page'        => '',
		'ids'         => ''
	), $atts ));

	global $post, $image_size;
	$class = '';
	$content = 'content';
	$return = '';
	$wrapper_class = 'row blog-wrapper';
	$current_page = (get_query_var('paged')) ? get_query_var('paged') : 1;

	if( $page ) {
		$current_page = $page;
	}

	$args = array(
		'posts_per_page' => $per_page,
		'post_type'      => 'post',
		'cat'            => $categories,
		'paged'          => $current_page
	);

	if( $ids != '' ) {
		$args = array(
			'post_type'      => 'any',
			'posts_per_page' => $per_page,
			'post__in'       => explode(',', $ids),
		);
	}

	$blog = new WP_Query($args);

	$max_page = ceil($blog->found_posts / (int) $per_page);

	switch($type) {
		case 'masonry-3-columns': $class='col-md-4 col-xs-6'; $wrapper_class .= ' blog-masonry'; break;
		case 'masonry-4-columns': $class='col-md-3 col-xs-6'; $wrapper_class .= ' blog-masonry'; break;
	}

	if( $wrapper == 'on' ) {
		$return .= '<div class="' . $wrapper_class . '" data-per-page="' . $per_page . '" data-categories="' . $categories . '" data-type="' . $type . '" data-max-page="' . $max_page . '">';
	}

	if ( $blog->have_posts() ) {
		$counter = 0;

		while ( $blog->have_posts() ) { $blog->the_post();
			/* Set image sizes and add wrapper around masonry type posts */
			if( $type == 'masonry-3-columns' || $type == 'masonry-4-columns' ) {
				$return .= '<div class="' . $class . '">';
				$content = 'content-masonry';

				if( $counter %2 == 0 ) {
					$image_size = 'blog';
				} else {
					$image_size = 'portfolio-post';
				}

				$counter++;
			} else {
				$image_size = 'blog';
			}
			
			/* Return individual posts */
			ob_start();
			get_template_part( $content, get_post_format() );
			$return .= ob_get_clean();

			/* Close wrapper for masonry type posts */
			if( $type == 'masonry-3-columns' || $type == 'masonry-4-columns' ) {
				$return .= '</div>';
			}
		}
	}
	wp_reset_postdata();

	if( $wrapper == 'on' ) {
		$return .= '</div>';
	}

	/* Pagination */

	if( $pagination == 'default' ) {
		$return .= '<nav class="page-nav">';
		$args = array(
			'type'      => 'list',
			'next_text' => '<i class="fa fa-angle-right"></i>',
			'prev_text' => '<i class="fa fa-angle-left"></i>',
			'current'   => $current_page,
			'total'     => $max_page
		);

		$return .= paginate_links( $args );
		$return .= '</nav>';
	} elseif ( $pagination == 'ajax' ) {
		$disabled = '';

		if( $max_page < 2 ) {
			$disabled = ' disabled="disabled"';
		}

		$return .= '<div class="row">
			<div class="col-md-12 text-center">
				<button class="btn btn-lg blog-load-more"' . $disabled . '>' . __( 'Load More', 'gfxbucket-shortcodes' ) . '</button>
			</div>
		</div>';
	}

	return $return;
}
add_shortcode( 'blog', 'blog_func' );