<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Template/class file; variables are widget-scoped, not true globals.
/**
 * Shop with sidebar — layout aligned with theme shop-with-sidebar.html
 *
 * @package storzen
 *
 * @var array                         $settings                 Widget settings.
 * @var \WP_Query                     $storzen_posts_query Main product query.
 * @var string                        $szp_shop_sidebar_base_url Current page URL for filters/forms.
 * @var string                        $szp_element_id              Elementor widget id.
 * @var array<string,mixed>           $szp_filters                 Active query filters.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

global $product;

if ( ! isset( $szp_filters ) || ! is_array( $szp_filters ) ) {
	$szp_filters = array();
}
if ( ! isset( $szp_element_id ) ) {
	$szp_element_id = 'wcp';
}

$szp_price_min = 0;
$szp_price_max = 1000;
global $wpdb;
$lookup = $wpdb->prefix . 'wc_product_meta_lookup';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$table_ok = ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $lookup ) ) === $lookup );
if ( $table_ok ) {
	$cache_key = 'storzen_price_range_' . md5( $lookup );
	$row       = wp_cache_get( $cache_key, 'storzen' );
	if ( false === $row ) {
		$row = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- No WP API for this aggregation; result is cached via wp_cache_get/set.
			"SELECT MIN(min_price) AS min_p, MAX(max_price) AS max_p FROM " . esc_sql( $lookup ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
			ARRAY_A
		);
		wp_cache_set( $cache_key, $row, 'storzen', HOUR_IN_SECONDS );
	}
	if ( $row && null !== $row['min_p'] && null !== $row['max_p'] ) {
		$szp_price_min = (float) $row['min_p'];
		$szp_price_max = (float) $row['max_p'];
		if ( $szp_price_max <= $szp_price_min ) {
			$szp_price_max = $szp_price_min + 1;
		}
	}
}

if ( isset( $szp_filters['min_price'], $szp_filters['max_price'] ) ) {
	$cur_min = (float) $szp_filters['min_price'];
	$cur_max = (float) $szp_filters['max_price'];
} else {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Public price filter; sanitized via wc_clean().
	$cur_min = isset( $_GET['min_price'] ) ? (float) wc_clean( wp_unslash( $_GET['min_price'] ) ) : $szp_price_min;
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Public price filter; sanitized via wc_clean().
	$cur_max = isset( $_GET['max_price'] ) ? (float) wc_clean( wp_unslash( $_GET['max_price'] ) ) : $szp_price_max;
}
$cur_min = max( $szp_price_min, min( $cur_min, $szp_price_max ) );
$cur_max = min( $szp_price_max, max( $cur_max, $szp_price_min ) );

$szp_color_tax = isset( $settings['color_attr_taxonomy'] ) ? sanitize_key( $settings['color_attr_taxonomy'] ) : 'pa_color';
if ( ! taxonomy_exists( $szp_color_tax ) ) {
	$szp_color_tax = '';
}

$szp_brand_pref = isset( $settings['brand_attr_taxonomy'] ) ? (string) $settings['brand_attr_taxonomy'] : '';
$szp_brand_tax  = function_exists( 'storzen_resolve_brand_taxonomy' ) ? storzen_resolve_brand_taxonomy( $szp_brand_pref ) : '';

$szp_cat_terms = array();
if ( 'yes' === ( $settings['show_sidebar_categories'] ?? '' ) ) {
	$szp_cat_terms = get_terms(
		array(
			'taxonomy'   => 'product_cat',
			'hide_empty' => true,
		)
	);
	if ( is_wp_error( $szp_cat_terms ) ) {
		$szp_cat_terms = array();
	}
}

$szp_color_terms = array();
if ( 'yes' === ( $settings['show_sidebar_color'] ?? '' ) && $szp_color_tax ) {
	$szp_color_terms = get_terms(
		array(
			'taxonomy'   => $szp_color_tax,
			'hide_empty' => true,
		)
	);
	if ( is_wp_error( $szp_color_terms ) ) {
		$szp_color_terms = array();
	}
}

$szp_brand_terms = array();
if ( 'yes' === ( $settings['show_sidebar_brands'] ?? '' ) && $szp_brand_tax ) {
	$szp_brand_terms = get_terms(
		array(
			'taxonomy'   => $szp_brand_tax,
			'hide_empty' => true,
		)
	);
	if ( is_wp_error( $szp_brand_terms ) ) {
		$szp_brand_terms = array();
	}
}

$szp_recent_q = null;
if ( 'yes' === ( $settings['show_sidebar_recent'] ?? '' ) ) {
	$szp_recent_q = new \WP_Query(
		array(
			'post_type'      => 'product',
			'posts_per_page' => (int) ( $settings['sidebar_recent_count'] ?? 3 ),
			'post_status'    => 'publish',
		)
	);
}

$szp_col_main = 'yes' === ( $settings['show_sidebar'] ?? 'yes' ) ? 'wco-col-xl-9 wco-col-lg-8' : 'wco-col-12';

$szp_active_cats = isset( $szp_filters['product_cat_slugs'] ) && is_array( $szp_filters['product_cat_slugs'] ) ? $szp_filters['product_cat_slugs'] : array();
$szp_active_brands = isset( $szp_filters['brand_slugs'] ) && is_array( $szp_filters['brand_slugs'] ) ? $szp_filters['brand_slugs'] : array();
$szp_active_colors = isset( $szp_filters['color_slugs'] ) && is_array( $szp_filters['color_slugs'] ) ? $szp_filters['color_slugs'] : array();

?>
<section class="shop-section fix section-padding szp-shop-sidebar" data-szp-element="<?php echo esc_attr( $szp_element_id ); ?>" data-szp-multi="<?php echo 'yes' === ( $settings['sidebar_multi_filter'] ?? 'yes' ) ? '1' : '0'; ?>">
	<div class="wco-container">
		<div class="wco-row wco-g-4">
			<?php if ( 'yes' === ( $settings['show_sidebar'] ?? 'yes' ) ) : ?>
			<div class="wco-col-xl-3 wco-col-lg-4">
				<div class="main-sidebar shop-sidebar rmb-75">
					<?php if ( 'yes' === ( $settings['show_sidebar_categories'] ?? '' ) && ! empty( $szp_cat_terms ) ) : ?>
					<div class="widget widget-menu wow fadeInUp delay-0-2s">
						<h6 class="widget-title"><?php echo esc_html( $settings['sidebar_cat_title'] ?? __( 'Category', 'storzen' ) ); ?></h6>
						<ul class="szp-filter-list szp-filter-list--category">
							<?php foreach ( $szp_cat_terms as $szp_term ) : ?>
								<?php
								$szp_cat_active = in_array( $szp_term->slug, $szp_active_cats, true );
								?>
								<li>
									<button
										type="button"
										class="szp-filter-link<?php echo $szp_cat_active ? ' is-active' : ''; ?>"
										data-szp-element="<?php echo esc_attr( $szp_element_id ); ?>"
										data-szp-filter="product_cat_slugs"
										data-szp-slug="<?php echo esc_attr( $szp_term->slug ); ?>"
										aria-pressed="<?php echo $szp_cat_active ? 'true' : 'false'; ?>"
									>
										<?php echo esc_html( $szp_term->name ); ?>
										<span>(<?php echo esc_html( (string) $szp_term->count ); ?>)</span>
									</button>
								</li>
							<?php endforeach; ?>
						</ul>
					</div>
					<?php endif; ?>

					<?php if ( 'yes' === ( $settings['show_sidebar_price'] ?? '' ) ) : ?>
					<div class="widget widget-filter wow fadeInUp delay-0-2s">
						<h6 class="widget-title"><?php echo esc_html( $settings['sidebar_price_title'] ?? __( 'Filter by price', 'storzen' ) ); ?></h6>
						<form method="get" action="<?php echo esc_url( $szp_shop_sidebar_base_url ); ?>" class="szp-price-filter-form" data-szp-element="<?php echo esc_attr( $szp_element_id ); ?>">
							<?php
							// Preserve other public query args (exclude min/max/orderby).
							// phpcs:ignore WordPress.Security.NonceVerification.Recommended
							foreach ( $_GET as $szp_key => $szp_val ) {
								if ( in_array( $szp_key, array( 'min_price', 'max_price', 'orderby' ), true ) ) {
									continue;
								}
								if ( is_array( $szp_val ) ) {
									continue;
								}
								echo '<input type="hidden" name="' . esc_attr( $szp_key ) . '" value="' . esc_attr( wp_unslash( (string) $szp_val ) ) . '" />';
							}
							?>
							<div class="price-filter-wrap" data-min="<?php echo esc_attr( (string) $szp_price_min ); ?>" data-max="<?php echo esc_attr( (string) $szp_price_max ); ?>">
								<div class="price-slider-range"></div>
								<div class="btn-price">
									<button type="submit"><?php esc_html_e( 'Filter', 'storzen' ); ?></button>
									<input type="text" class="szp-price-readout" readonly="readonly" value="" />
									<input type="hidden" name="min_price" value="<?php echo esc_attr( (string) $cur_min ); ?>" />
									<input type="hidden" name="max_price" value="<?php echo esc_attr( (string) $cur_max ); ?>" />
								</div>
							</div>
						</form>
					</div>
					<?php endif; ?>

					<?php if ( 'yes' === ( $settings['show_sidebar_color'] ?? '' ) && $szp_color_tax && ! empty( $szp_color_terms ) ) : ?>
					<div class="widget widget-color wow fadeInUp delay-0-2s">
						<h6 class="widget-title"><?php echo esc_html( $settings['sidebar_color_title'] ?? __( 'Color', 'storzen' ) ); ?></h6>
						<ul class="szp-filter-list szp-filter-list--color">
							<?php
							foreach ( $szp_color_terms as $szp_term ) {
								$szp_col_active = in_array( $szp_term->slug, $szp_active_colors, true );
								?>
								<li>
									<button
										type="button"
										class="szp-filter-link<?php echo $szp_col_active ? ' is-active' : ''; ?>"
										data-szp-element="<?php echo esc_attr( $szp_element_id ); ?>"
										data-szp-filter="color_slugs"
										data-szp-slug="<?php echo esc_attr( $szp_term->slug ); ?>"
										aria-pressed="<?php echo $szp_col_active ? 'true' : 'false'; ?>"
									>
										<span class="<?php echo esc_attr( sanitize_html_class( $szp_term->slug ) ); ?>"></span>
										<?php echo esc_html( $szp_term->name ); ?>
									</button>
								</li>
								<?php
							}
							?>
						</ul>
					</div>
					<?php endif; ?>

					<?php if ( 'yes' === ( $settings['show_sidebar_brands'] ?? '' ) ) : ?>
					<div class="widget widget-menu wow fadeInUp delay-0-2s szp-brands-widget">
						<h6 class="widget-title"><?php echo esc_html( $settings['sidebar_brands_title'] ?? __( 'Brands', 'storzen' ) ); ?></h6>
						<?php if ( ! $szp_brand_tax ) : ?>
							<p class="szp-brands-empty"><?php esc_html_e( 'No brand taxonomy is registered. Add a product attribute (e.g. Brand) or a brands plugin, then set the Brand taxonomy in the widget.', 'storzen' ); ?></p>
						<?php elseif ( ! empty( $szp_brand_terms ) ) : ?>
						<ul class="szp-filter-list szp-filter-list--brand">
							<?php foreach ( $szp_brand_terms as $szp_term ) : ?>
								<?php
								$szp_brand_active = in_array( $szp_term->slug, $szp_active_brands, true );
								?>
								<li>
									<button
										type="button"
										class="szp-filter-link<?php echo $szp_brand_active ? ' is-active' : ''; ?>"
										data-szp-element="<?php echo esc_attr( $szp_element_id ); ?>"
										data-szp-filter="brand_slugs"
										data-szp-slug="<?php echo esc_attr( $szp_term->slug ); ?>"
										aria-pressed="<?php echo $szp_brand_active ? 'true' : 'false'; ?>"
									>
										<?php echo esc_html( $szp_term->name ); ?>
										<span>(<?php echo esc_html( (string) $szp_term->count ); ?>)</span>
									</button>
								</li>
							<?php endforeach; ?>
						</ul>
						<?php else : ?>
							<p class="szp-brands-empty"><?php esc_html_e( 'No brands found.', 'storzen' ); ?></p>
						<?php endif; ?>
					</div>
					<?php endif; ?>

					<?php if ( 'yes' === ( $settings['show_sidebar_recent'] ?? '' ) && $szp_recent_q && $szp_recent_q->have_posts() ) : ?>
					<div class="widget widget-products wow fadeInUp delay-0-2s">
						<h6 class="widget-title"><?php echo esc_html( $settings['sidebar_recent_title'] ?? __( 'Recent product', 'storzen' ) ); ?></h6>
						<ul>
							<?php
							while ( $szp_recent_q->have_posts() ) :
								$szp_recent_q->the_post();
								$szp_rimg = get_the_post_thumbnail_url( get_the_ID(), 'thumbnail' );
								$szp_rproduct = wc_get_product( get_the_ID() );
								?>
								<li>
									<div class="image">
										<?php if ( $szp_rimg ) : ?>
											<img src="<?php echo esc_url( $szp_rimg ); ?>" alt="<?php echo esc_attr( get_the_title() ); ?>" />
										<?php endif; ?>
									</div>
									<div class="content">
										<h6><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h6>
										<?php if ( $szp_rproduct ) : ?>
											<b><?php echo wp_kses_post( $szp_rproduct->get_price_html() ); ?></b>
										<?php endif; ?>
									</div>
								</li>
								<?php
							endwhile;
							wp_reset_postdata();
							?>
						</ul>
					</div>
					<?php endif; ?>
				</div>
			</div>
			<?php endif; ?>

			<div class="<?php echo esc_attr( $szp_col_main ); ?>">
				<?php include storzen_get_template( 'shop-sidebar-main.php' ); ?>
			</div>
		</div>
	</div>
</section>
