<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Template/class file; variables are widget-scoped, not true globals.

/**
 * Main column: toolbar + product grid + pagination (used in full template and AJAX).
 *
 * @package storzen
 *
 * @var array                         $settings
 * @var \WP_Query                     $storzen_posts_query
 * @var string                        $szp_shop_sidebar_base_url
 * @var string                        $szp_element_id
 * @var array<string,mixed>           $szp_filters Active filters (for UI state).
 */

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

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

if (! isset($settings) || ! is_array($settings)) {
	$settings = array();
}
// Defaults match Archive Products Grid / Shop Sidebar widgets (AJAX may pass a partial $settings array).
$settings = array_merge(
	array(
		'titltag'                    => 'h6',
		'open-url'                   => 'same-window',
		'dtitle'                     => 'full',
		'title_excerpt_length'       => 8,
		'column'                     => '4',
		'show_toolbar'               => 'yes',
		'show_grid_list_icons'       => '',
		'enable_pagination'          => 'yes',
		'wc_orderby'                 => 'menu_order',
		'module_variation_swatches'  => '',
		'module_sale_notification'   => '',
		'module_quick_view'          => '',
		'module_sale_badge'          => '',
		'module_wishlist'            => '',
		'module_compare'             => '',
		'module_sticky_atc'          => '',
		'module_flash_countdown'     => '',
		'module_shipping_bar'        => '',
		'module_stock_scarcity'      => '',
	),
	$settings
);

/**
 * Resolve whether a module is active in this template render.
 *
 * Widget context takes priority when present (set by Archive Products Grid).
 * Falls back to the global Storzen module toggle when no widget context exists
 * (e.g. Shop Sidebar widget or direct template include without a widget).
 *
 * @param string $module_key  Storzen module key, e.g. 'sale_badge'.
 * @param string $setting_key Matching widget setting key, e.g. 'module_sale_badge'.
 * @return bool
 */
$szp_module_active = static function ( $module_key ) {
	// Archive Products Grid widget sets a per-render context.
	if ( class_exists( 'Elementor\Storzen_Archive_Grid' ) ) {
		$ctx = \Elementor\Storzen_Archive_Grid::is_module_active( $module_key );
		if ( null !== $ctx ) {
			return $ctx;
		}
	}
	// No widget context: honour the global module toggle.
	if ( function_exists( 'storzen_module_enabled' ) ) {
		return storzen_module_enabled( $module_key );
	}
	return false;
};

$szp_found   = (int) $storzen_posts_query->found_posts;
$szp_showing = (int) $storzen_posts_query->post_count;
$szp_sort_key = isset($szp_filters['orderby']) && (string) $szp_filters['orderby'] !== ''
	? sanitize_key((string) $szp_filters['orderby'])
	: (isset($settings['wc_orderby']) ? (string) $settings['wc_orderby'] : 'menu_order');

$szp_sort_options = array(
	'menu_order' => __('Default', 'storzen'),
	'popularity' => __('Sort by popularity', 'storzen'),
	'rating'     => __('Sort by rating', 'storzen'),
	'date'       => __('Sort by latest', 'storzen'),
	'price'      => __('Price: low to high', 'storzen'),
	'price-desc' => __('Price: high to low', 'storzen'),
);

$szp_show_view_toggle = 'yes' === ($settings['show_grid_list_icons'] ?? '');
$szp_main_classes     = 'szp-shop-sidebar__main szp-layout-grid';
if ($szp_show_view_toggle) {
	$szp_main_classes .= ' szp-has-view-toggle';
}

?>
<div class="<?php echo esc_attr($szp_main_classes); ?>" data-szp-main="<?php echo esc_attr($szp_element_id); ?>">
	<?php if ('yes' === ($settings['show_toolbar'] ?? 'yes')) : ?>
		<div class="shop-shorter szp-toolbar">
			<div class="sort-text szp-result-text">
				<?php
				printf(
				/* translators: 1: visible count, 2: total results */
				esc_html__('Showing %1$d of %2$d results', 'storzen'),
				absint( $szp_showing ),
				absint( $szp_found )
			);
				?>
			</div>
			<div class="shorter-right">
				<?php if ($szp_show_view_toggle) : ?>
					<ul class="grid-list szp-grid-list" data-szp-element="<?php echo esc_attr($szp_element_id); ?>">
						<li>
							<button type="button" class="szp-view-btn active" data-szp-view="grid" aria-pressed="true" title="<?php esc_attr_e('Grid view', 'storzen'); ?>">
								<i class="fas fa-border-all" aria-hidden="true"></i>
							</button>
						</li>
						<li>
							<button type="button" class="szp-view-btn" data-szp-view="list" aria-pressed="false" title="<?php esc_attr_e('List view', 'storzen'); ?>">
								<i class="fas fa-list-ul" aria-hidden="true"></i>
							</button>
						</li>
					</ul>
				<?php endif; ?>
				<div class="sort-area">
					<span class="sort-label"><?php esc_html_e('Sort by:', 'storzen'); ?></span>
					<div class="custom-select szp-sort-select-wrap">
						<select class="szp-sort-select" data-szp-element="<?php echo esc_attr($szp_element_id); ?>" aria-label="<?php esc_attr_e('Sort products', 'storzen'); ?>">
							<?php foreach ($szp_sort_options as $szp_key => $szp_label) : ?>
								<option value="<?php echo esc_attr($szp_key); ?>" <?php selected($szp_sort_key, $szp_key); ?>>
									<?php echo esc_html($szp_label); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</div>
				</div>
			</div>
		</div>
	<?php endif; ?>

	<?php if ($szp_show_view_toggle) : ?>
		<div class="szp-product-loop szp-product-loop--grid wco-row">
			<?php
			if ($storzen_posts_query->have_posts()) :
				while ($storzen_posts_query->have_posts()) :
					$storzen_posts_query->the_post();
					$storzen_img_src = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
					$product              = wc_get_product(get_the_ID());
					if (! $product) {
						continue;
					}
			?>
					<div class="wco-col-xl-<?php echo esc_attr($settings['column']); ?> wco-col-sm-6">
						<div class="shop-card-items">
							<div class="image">
								<div class="badges">
								<?php if ( $szp_module_active( 'sale_badge' ) ) : ?>
									<?php do_action( 'storzen_shop_card_badges', $product ); ?>
								<?php endif; ?>
								</div>
								<a href="<?php the_permalink(); ?>">
									<?php the_post_thumbnail(); ?>
								</a>
								<div class="social-style-two">
									<?php echo storzen_add_to_cart_button(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- storzen_add_to_cart_button() returns markup already escaped with esc_url/esc_attr/wc_implode_html_attributes. ?>
									<?php do_action( 'storzen_shop_card_overlay', $product ); ?>
								</div>
							</div>
							<div class="content">
								<?php
								$storzen_categories = get_the_terms(get_the_ID(), 'product_cat');
								if ($storzen_categories && ! is_wp_error($storzen_categories)) :
									$storzen_category = array_shift($storzen_categories);
								?>
									<a href="<?php echo esc_url(get_term_link($storzen_category)); ?>" class="category"><?php echo esc_html($storzen_category->name); ?></a>
								<?php endif; ?>
								<<?php echo esc_attr($settings['titltag']); ?>>
									<a <?php echo ('new-window' === $settings['open-url']) ? 'target="_blank" rel="noopener noreferrer"' : ''; ?> href="<?php the_permalink(); ?>" class="woo-title">
										<?php
										if ('full' === $settings['dtitle']) {
											the_title();
										} else {
											echo esc_html(wp_trim_words(get_the_title(), (int) ($settings['title_excerpt_length'] ?? 8), ''));
										}
										?>
									</a>
								</<?php echo esc_attr($settings['titltag']); ?>>
								<div class="prices"><?php echo wp_kses_post($product->get_price_html()); ?></div>
								<?php if ( $szp_module_active( 'flash_countdown' ) || $szp_module_active( 'stock_scarcity' ) ) : ?>
									<?php do_action( 'storzen_shop_card_after_title', $product ); ?>
								<?php endif; ?>
							</div>
						</div>
					</div>
				<?php
				endwhile;
				wp_reset_postdata();
			else :
				?>
				<article class="wco-col-12">
					<h3 class="no-post-found"><?php esc_html_e('Sorry, no products found', 'storzen'); ?></h3>
				</article>
			<?php
			endif;
			?>
		</div>

		<div class="szp-product-loop szp-product-loop--list wco-row">
			<?php
			$storzen_posts_query->rewind_posts();
			if ($storzen_posts_query->have_posts()) :
				while ($storzen_posts_query->have_posts()) :
					$storzen_posts_query->the_post();
					$storzen_img_src = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
					$product              = wc_get_product(get_the_ID());
					if (! $product) {
						continue;
					}
					$szp_short = $product->get_short_description();
					$szp_desc  = $szp_short ? wp_strip_all_tags($szp_short) : wp_strip_all_tags(get_the_excerpt());
			?>
					<div class="wco-col-12">
						<div class="shop-list-sidebar">
							<div class="thumb">
								<a href="<?php the_permalink(); ?>">
									<?php the_post_thumbnail('large'); ?>
								</a>
							</div>
							<div class="content">
								<div class="ratting">
									<?php echo wp_kses_post(storzen_shop_sidebar_star_rating_html($product)); ?>
								</div>
								<h6>
									<a <?php echo ('new-window' === $settings['open-url']) ? 'target="_blank" rel="noopener noreferrer"' : ''; ?> href="<?php the_permalink(); ?>" class="woo-title">
										<?php
										if ('full' === $settings['dtitle']) {
											the_title();
										} else {
											echo esc_html(wp_trim_words(get_the_title(), (int) ($settings['title_excerpt_length'] ?? 8), ''));
										}
										?>
									</a>
								</h6>
								<div class="prices"><?php echo wp_kses_post($product->get_price_html()); ?></div>
								<?php if ( $szp_module_active( 'flash_countdown' ) || $szp_module_active( 'stock_scarcity' ) ) : ?>
									<?php do_action( 'storzen_shop_card_after_title', $product ); ?>
								<?php endif; ?>
								<p><?php echo esc_html(wp_trim_words($szp_desc, 30, '...')); ?></p>
								<div class="cart-btns">
									<?php echo storzen_add_to_cart_button(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- storzen_add_to_cart_button() returns markup already escaped with esc_url/esc_attr/wc_implode_html_attributes. ?>
									<div class="shop-icon">
										<?php do_action( 'storzen_shop_card_overlay', $product ); ?>
									</div>
								</div>
							</div>
						</div>
					</div>
			<?php
				endwhile;
				wp_reset_postdata();
			endif;
			?>
		</div>

	<?php else : ?>
		<div class="szp-product-loop szp-product-loop--grid wco-row">
			<?php
			if ($storzen_posts_query->have_posts()) :
				while ($storzen_posts_query->have_posts()) :
					$storzen_posts_query->the_post();
					$storzen_img_src = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
					$product              = wc_get_product(get_the_ID());
					if (! $product) {
						continue;
					}
			?>
					<div class="wco-col-xl-<?php echo esc_attr($settings['column']); ?> wco-col-sm-6">
						<div class="shop-card-items">
							<div class="image">
								<div class="badges">
								<?php if ( $szp_module_active( 'sale_badge' ) ) : ?>
									<?php do_action( 'storzen_shop_card_badges', $product ); ?>
								<?php endif; ?>
								</div>
								<a href="<?php the_permalink(); ?>">
									<?php the_post_thumbnail(); ?>
								</a>
								<div class="social-style-two">
									<?php echo storzen_add_to_cart_button(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- storzen_add_to_cart_button() returns markup already escaped with esc_url/esc_attr/wc_implode_html_attributes. ?>
									<?php do_action( 'storzen_shop_card_overlay', $product ); ?>
								</div>
							</div>
							<div class="content">
								<?php
								$storzen_categories = get_the_terms(get_the_ID(), 'product_cat');
								if ($storzen_categories && ! is_wp_error($storzen_categories)) :
									$storzen_category = array_shift($storzen_categories);
								?>
									<a href="<?php echo esc_url(get_term_link($storzen_category)); ?>" class="category"><?php echo esc_html($storzen_category->name); ?></a>
								<?php endif; ?>
								<<?php echo esc_attr($settings['titltag']); ?>>
									<a <?php echo ('new-window' === $settings['open-url']) ? 'target="_blank" rel="noopener noreferrer"' : ''; ?> href="<?php the_permalink(); ?>" class="woo-title">
										<?php
										if ('full' === $settings['dtitle']) {
											the_title();
										} else {
											echo esc_html(wp_trim_words(get_the_title(), (int) ($settings['title_excerpt_length'] ?? 8), ''));
										}
										?>
									</a>
								</<?php echo esc_attr($settings['titltag']); ?>>
								<div class="prices"><?php echo wp_kses_post($product->get_price_html()); ?></div>
								<?php if ( $szp_module_active( 'flash_countdown' ) || $szp_module_active( 'stock_scarcity' ) ) : ?>
									<?php do_action( 'storzen_shop_card_after_title', $product ); ?>
								<?php endif; ?>
							</div>
						</div>
					</div>
				<?php
				endwhile;
				wp_reset_postdata();
			else :
				?>
				<article class="wco-col-12">
					<h3 class="no-post-found"><?php esc_html_e('Sorry, no products found', 'storzen'); ?></h3>
				</article>
			<?php
			endif;
			?>
		</div>
	<?php endif; ?>

	<?php
	if ('yes' === ($settings['enable_pagination'] ?? '') && isset($storzen_posts_query) && $storzen_posts_query->max_num_pages > 1) :
		$szp_total_pages  = (int) $storzen_posts_query->max_num_pages;
		$szp_current_page = isset($szp_filters['paged']) ? max(1, (int) $szp_filters['paged']) : 1;
	?>
		<ul class="pagination style-two szp-pagination" data-szp-element="<?php echo esc_attr($szp_element_id); ?>">
			<li class="page-item">
				<?php if ($szp_current_page > 1) : ?>
					<button type="button" class="button-link previous szp-page-btn" data-szp-page="<?php echo esc_attr((string) ($szp_current_page - 1)); ?>"><?php esc_html_e('Previous', 'storzen'); ?></button>
				<?php else : ?>
					<span class="previous disabled"><?php esc_html_e('Previous', 'storzen'); ?></span>
				<?php endif; ?>
			</li>
			<li>
				<div class="number-icon">
					<?php
					for ($szp_i = 1; $szp_i <= $szp_total_pages; $szp_i++) {
						$szp_class = ($szp_i === $szp_current_page) ? 'number current' : 'number';
					?>
						<button type="button" class="<?php echo esc_attr($szp_class); ?> szp-page-btn" data-szp-page="<?php echo esc_attr((string) $szp_i); ?>"><?php echo esc_html((string) $szp_i); ?></button>
					<?php
					}
					?>
				</div>
			</li>
			<li class="page-item">
				<?php if ($szp_current_page < $szp_total_pages) : ?>
					<button type="button" class="button-link previous szp-page-btn" data-szp-page="<?php echo esc_attr((string) ($szp_current_page + 1)); ?>"><?php esc_html_e('Next', 'storzen'); ?></button>
				<?php else : ?>
					<span class="previous disabled"><?php esc_html_e('Next', 'storzen'); ?></span>
				<?php endif; ?>
			</li>
		</ul>
	<?php
	endif;
	?>
</div>