<?php
/**
 * The template to display the widgets area in the header
 *
 * @package PANTRY
 * @since PANTRY 1.0
 */

// Header sidebar
$pantry_header_name    = pantry_get_theme_option( 'header_widgets' );
$pantry_header_present = ! pantry_is_off( $pantry_header_name ) && is_active_sidebar( $pantry_header_name );
if ( $pantry_header_present ) {
	pantry_storage_set( 'current_sidebar', 'header' );
	$pantry_header_wide = pantry_get_theme_option( 'header_wide' );
	ob_start();
	if ( is_active_sidebar( $pantry_header_name ) ) {
		dynamic_sidebar( $pantry_header_name );
	}
	$pantry_widgets_output = ob_get_contents();
	ob_end_clean();
	if ( ! empty( $pantry_widgets_output ) ) {
		$pantry_widgets_output = preg_replace( "/<\/aside>[\r\n\s]*<aside/", '</aside><aside', $pantry_widgets_output );
		$pantry_need_columns   = strpos( $pantry_widgets_output, 'columns_wrap' ) === false;
		if ( $pantry_need_columns ) {
			$pantry_columns = max( 0, (int) pantry_get_theme_option( 'header_columns' ) );
			if ( 0 == $pantry_columns ) {
				$pantry_columns = min( 6, max( 1, pantry_tags_count( $pantry_widgets_output, 'aside' ) ) );
			}
			if ( $pantry_columns > 1 ) {
				$pantry_widgets_output = preg_replace( '/<aside([^>]*)class="widget/', '<aside$1class="column-1_' . esc_attr( $pantry_columns ) . ' widget', $pantry_widgets_output );
			} else {
				$pantry_need_columns = false;
			}
		}
		?>
		<div class="header_widgets_wrap widget_area<?php echo ! empty( $pantry_header_wide ) ? ' header_fullwidth' : ' header_boxed'; ?>">
			<?php do_action( 'pantry_action_before_sidebar_wrap', 'header' ); ?>
			<div class="header_widgets_inner widget_area_inner">
				<?php
				if ( ! $pantry_header_wide ) {
					?>
					<div class="content_wrap">
					<?php
				}
				if ( $pantry_need_columns ) {
					?>
					<div class="columns_wrap">
					<?php
				}
				do_action( 'pantry_action_before_sidebar', 'header' );
				pantry_show_layout( $pantry_widgets_output );
				do_action( 'pantry_action_after_sidebar', 'header' );
				if ( $pantry_need_columns ) {
					?>
					</div>	<!-- /.columns_wrap -->
					<?php
				}
				if ( ! $pantry_header_wide ) {
					?>
					</div>	<!-- /.content_wrap -->
					<?php
				}
				?>
			</div>	<!-- /.header_widgets_inner -->
			<?php do_action( 'pantry_action_after_sidebar_wrap', 'header' ); ?>
		</div>	<!-- /.header_widgets_wrap -->
		<?php
	}
}
