<?php
/**
 * The template for displaying post sections
 *
 * @package WordPress
 * @subpackage Edition
 * @since Edition 1.0
 */

global
$tw_order_class,
$tw_section,
$type,
$post_ID,
$fields_installed;

$tw_order_class = 'first-section';
$post_ID        = $post->ID;

if ( is_category() ) {
	$category = get_category( get_query_var( 'cat' ) );
	$post_ID  = 'category_' . $category->cat_ID;
}
if ( is_tag() ) {
	$tag     = get_term_by( 'slug', get_query_var( 'tag' ), 'post_tag' );
	$post_ID = 'post_tag_' . $tag->term_id;
}
if ( function_exists( 'is_product_category' ) && is_product_category() ) {
	global $wp_query;
	$cat = $wp_query->get_queried_object();
	$post_ID = 'product_cat_' . $cat->term_id;
}
if (function_exists( 'is_product_tag' ) && is_product_tag() ) {
	global $wp_query;
	$cat = $wp_query->get_queried_object();
	$post_ID = 'product_tag_' . $cat->term_id;
}
if ( function_exists( 'is_shop' ) && is_shop() ) {
	$post_ID = get_option( 'woocommerce_shop_page_id' );
}

?>

<?php if ( $fields_installed && ( ! is_page_template( 'template-home.php' ) || get_field( 'homepage_layout' ) == 'custom' ) ) :

		$post_sections = $fields_installed ? get_field('sections', $post_ID) : false;

		if ( $post_sections ) :

			echo '<div class="section-wrapper">';

			$post_count = count($post_sections); // count the number of sections
			$counter 	= 1;

			if ($post_count == 1) {
				$tw_order_class = 'first-section last-section';
			}

			foreach($post_sections as $post): // variable must be called $post (IMPORTANT)
				setup_postdata($post);

				// get the section type
				$type = get_field('section_type');

				// create the correct page template
				switch ($type) {
					case 'section-grid':
						$layout_type = get_field('grid_type');
						$type = $layout_type ? $type . '-' . $layout_type : $type . '-full';
					break;
					case 'section-slider':
						$layout_type = get_field('full_slide_type');
						$type = $layout_type ? $type . '-' . $layout_type : $type . '-full';
					break;
					case 'section-full':
					    $layout_type = get_field('full_feature_type');
					    $type = $layout_type ? $type . '-' . $layout_type : $type . '-full';
					break;
					case 'section-content':
					    $layout_type = get_field('content_layout');
					    $type = $layout_type ? $type . '-' . $layout_type : $type . '-full';
					break;
				}

				// print the page template
				get_template_part( TW_TEMPLATES_DIR .'/sections/' . $type );

				// update the order
				$tw_order_class = 'not-first-section';

				if ($counter + 1 == $post_count) {
					$tw_order_class .= ' last-section';
				}

				$counter++;

			endforeach;

			// reset post data
			wp_reset_postdata();

			echo '</div>';

		endif;

	else : // default template layout
		echo '<div class="section-wrapper">';
			get_template_part( TW_TEMPLATES_DIR .'/sections/default-home');
		echo '</div>';
	endif;

	wp_reset_query(); // resetting query
?>
