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

if ( hygia_sidebar_present() ) {
	
	$hygia_sidebar_type = hygia_get_theme_option( 'sidebar_type' );
	if ( 'custom' == $hygia_sidebar_type && ! hygia_is_layouts_available() ) {
		$hygia_sidebar_type = 'default';
	}
	
	// Catch output to the buffer
	ob_start();
	if ( 'default' == $hygia_sidebar_type ) {
		// Default sidebar with widgets
		$hygia_sidebar_name = hygia_get_theme_option( 'sidebar_widgets' );
		hygia_storage_set( 'current_sidebar', 'sidebar' );
		if ( is_active_sidebar( $hygia_sidebar_name ) ) {
			dynamic_sidebar( $hygia_sidebar_name );
		}
	} else {
		// Custom sidebar from Layouts Builder
		$hygia_sidebar_id = hygia_get_custom_sidebar_id();
		do_action( 'hygia_action_show_layout', $hygia_sidebar_id );
	}
	$hygia_out = trim( ob_get_contents() );
	ob_end_clean();
	
	// If any html is present - display it
	if ( ! empty( $hygia_out ) ) {
		$hygia_sidebar_position    = hygia_get_theme_option( 'sidebar_position' );
		$hygia_sidebar_position_ss = hygia_get_theme_option( 'sidebar_position_ss', 'below' );
		?>
		<div class="sidebar widget_area
			<?php
			echo ' ' . esc_attr( $hygia_sidebar_position );
			echo ' sidebar_' . esc_attr( $hygia_sidebar_position_ss );
			echo ' sidebar_' . esc_attr( $hygia_sidebar_type );

			$hygia_sidebar_scheme = apply_filters( 'hygia_filter_sidebar_scheme', hygia_get_theme_option( 'sidebar_scheme', 'inherit' ) );
			if ( ! empty( $hygia_sidebar_scheme ) && ! hygia_is_inherit( $hygia_sidebar_scheme ) && 'custom' != $hygia_sidebar_type ) {
				echo ' scheme_' . esc_attr( $hygia_sidebar_scheme );
			}
			?>
		" role="complementary">
			<?php

			// Skip link anchor to fast access to the sidebar from keyboard
			?>
			<span id="sidebar_skip_link_anchor" class="hygia_skip_link_anchor"></span>
			<?php

			do_action( 'hygia_action_before_sidebar_wrap', 'sidebar' );

			// Button to show/hide sidebar on mobile
			if ( in_array( $hygia_sidebar_position_ss, array( 'above', 'float' ) ) ) {
				$hygia_title = apply_filters( 'hygia_filter_sidebar_control_title', 'float' == $hygia_sidebar_position_ss ? esc_html__( 'Show Sidebar', 'hygia' ) : '' );
				$hygia_text  = apply_filters( 'hygia_filter_sidebar_control_text', 'above' == $hygia_sidebar_position_ss ? esc_html__( 'Show Sidebar', 'hygia' ) : '' );
				?>
				<a href="#" role="button" class="sidebar_control" title="<?php echo esc_attr( $hygia_title ); ?>"><?php echo esc_html( $hygia_text ); ?></a>
				<?php
			}
			?>
			<div class="sidebar_inner">
				<?php
				do_action( 'hygia_action_before_sidebar', 'sidebar' );
				hygia_show_layout( preg_replace( "/<\/aside>[\r\n\s]*<aside/", '</aside><aside', $hygia_out ) );
				do_action( 'hygia_action_after_sidebar', 'sidebar' );
				?>
			</div>
			<?php

			do_action( 'hygia_action_after_sidebar_wrap', 'sidebar' );

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