<?php
/**
 * The Sidebar containing the main widget areas.
 *
 * @package PANTRY
 * @since PANTRY 1.0
 */

if ( pantry_sidebar_present() ) {
	
	$pantry_sidebar_type = pantry_get_theme_option( 'sidebar_type' );
	if ( 'custom' == $pantry_sidebar_type && ! pantry_is_layouts_available() ) {
		$pantry_sidebar_type = 'default';
	}
	
	// Catch output to the buffer
	ob_start();
	if ( 'default' == $pantry_sidebar_type ) {
		// Default sidebar with widgets
		$pantry_sidebar_name = pantry_get_theme_option( 'sidebar_widgets' );
		pantry_storage_set( 'current_sidebar', 'sidebar' );
		if ( is_active_sidebar( $pantry_sidebar_name ) ) {
			dynamic_sidebar( $pantry_sidebar_name );
		}
	} else {
		// Custom sidebar from Layouts Builder
		$pantry_sidebar_id = pantry_get_custom_sidebar_id();
		do_action( 'pantry_action_show_layout', $pantry_sidebar_id );
	}
	$pantry_out = trim( ob_get_contents() );
	ob_end_clean();
	
	// If any html is present - display it
	if ( ! empty( $pantry_out ) ) {
		$pantry_sidebar_position    = pantry_get_theme_option( 'sidebar_position' );
		$pantry_sidebar_position_ss = pantry_get_theme_option( 'sidebar_position_ss' );
		?>
		<div class="sidebar widget_area
			<?php
			echo ' ' . esc_attr( $pantry_sidebar_position );
			echo ' sidebar_' . esc_attr( $pantry_sidebar_position_ss );
			echo ' sidebar_' . esc_attr( $pantry_sidebar_type );

			$pantry_sidebar_scheme = apply_filters( 'pantry_filter_sidebar_scheme', pantry_get_theme_option( 'sidebar_scheme' ) );
			if ( ! empty( $pantry_sidebar_scheme ) && ! pantry_is_inherit( $pantry_sidebar_scheme ) && 'custom' != $pantry_sidebar_type ) {
				echo ' scheme_' . esc_attr( $pantry_sidebar_scheme );
			}
			?>
		" role="complementary">
			<?php

			// Skip link anchor to fast access to the sidebar from keyboard
			?>
			<a id="sidebar_skip_link_anchor" class="pantry_skip_link_anchor" href="#"></a>
			<?php

			do_action( 'pantry_action_before_sidebar_wrap', 'sidebar' );

			// Button to show/hide sidebar on mobile
			if ( in_array( $pantry_sidebar_position_ss, array( 'above', 'float' ) ) ) {
				$pantry_title = apply_filters( 'pantry_filter_sidebar_control_title', 'float' == $pantry_sidebar_position_ss ? esc_html__( 'Show Sidebar', 'pantry' ) : '' );
				$pantry_text  = apply_filters( 'pantry_filter_sidebar_control_text', 'above' == $pantry_sidebar_position_ss ? esc_html__( 'Show Sidebar', 'pantry' ) : '' );
				?>
				<a href="#" class="sidebar_control" title="<?php echo esc_attr( $pantry_title ); ?>"><?php echo esc_html( $pantry_text ); ?></a>
				<?php
			}
			?>
			<div class="sidebar_inner">
				<?php
				do_action( 'pantry_action_before_sidebar', 'sidebar' );
				pantry_show_layout( preg_replace( "/<\/aside>[\r\n\s]*<aside/", '</aside><aside', $pantry_out ) );
				do_action( 'pantry_action_after_sidebar', 'sidebar' );
				?>
			</div>
			<?php

			do_action( 'pantry_action_after_sidebar_wrap', 'sidebar' );

			?>
		</div>
		<div class="clearfix"></div>
		<?php
	}
}
