<?php

/**
 * Shop page with sidebar (filters + product grid) — matches theme shop-with-sidebar layout.
 *
 * @package storzen
 */

namespace Elementor;

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

/**
 * Class Storzen_Shop_Sidebar
 */
class Storzen_Shop_Sidebar extends Widget_Base
{

	/**
	 * @return string
	 */
	public function get_name()
	{
		return 'storzen-shop-sidebar';
	}

	/**
	 * @return string
	 */
	public function get_title()
	{
		return esc_html__('Shop With Sidebar', 'storzen');
	}

	/**
	 * @return string
	 */
	public function get_icon()
	{
		return 'eicon-products';
	}

	/**
	 * @return array<int,string>
	 */
	public function get_categories()
	{
		return array('storzen');
	}

	/**
	 * @return array<int,string>
	 */
	public function get_script_depends()
	{
		return array('jquery-ui-slider', 'storzen-shop-sidebar');
	}

	/**
	 * Register controls.
	 */
	protected function register_controls()
	{

		$this->start_controls_section(
			'sidebar_section',
			array(
				'label' => esc_html__('Sidebar', 'storzen'),
			)
		);

		$this->add_control(
			'style',
			array(
				'label'   => esc_html__('Select Style', 'storzen'),
				'type'    => Controls_Manager::SELECT2,
				'options' => array(
					'style-1' => esc_html__('Style 1', 'storzen'),
				),
				'default' => 'style-1',
			)
		);

		$this->add_control(
			'show_sidebar',
			array(
				'label'        => esc_html__('Show sidebar', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__('Yes', 'storzen'),
				'label_off'    => esc_html__('No', 'storzen'),
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'sidebar_cat_title',
			array(
				'label'   => esc_html__('Categories widget title', 'storzen'),
				'type'    => Controls_Manager::TEXT,
				'default' => esc_html__('Category', 'storzen'),
			)
		);

		$this->add_control(
			'show_sidebar_categories',
			array(
				'label'        => esc_html__('Categories list', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'sidebar_price_title',
			array(
				'label'   => esc_html__('Price filter title', 'storzen'),
				'type'    => Controls_Manager::TEXT,
				'default' => esc_html__('Filter by price', 'storzen'),
				'condition' => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'show_sidebar_price',
			array(
				'label'        => esc_html__('Price filter', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'sidebar_color_title',
			array(
				'label'   => esc_html__('Color widget title', 'storzen'),
				'type'    => Controls_Manager::TEXT,
				'default' => esc_html__('Color', 'storzen'),
				'condition' => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'show_sidebar_color',
			array(
				'label'        => esc_html__('Color attribute list', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'color_attr_taxonomy',
			array(
				'label'       => esc_html__('Color attribute slug', 'storzen'),
				'type'        => Controls_Manager::TEXT,
				'default'     => 'pa_color',
				'description' => esc_html__('WooCommerce attribute taxonomy, e.g. pa_color', 'storzen'),
				'condition'   => array(
					'show_sidebar'        => 'yes',
					'show_sidebar_color' => 'yes',
				),
			)
		);

		$this->add_control(
			'sidebar_brands_title',
			array(
				'label'   => esc_html__('Brands widget title', 'storzen'),
				'type'    => Controls_Manager::TEXT,
				'default' => esc_html__('Brands', 'storzen'),
				'condition' => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'show_sidebar_brands',
			array(
				'label'        => esc_html__('Brands list', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'sidebar_multi_filter',
			array(
				'label'        => esc_html__('Multi-select filters', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__('Yes', 'storzen'),
				'label_off'    => esc_html__('No', 'storzen'),
				'return_value' => 'yes',
				'default'      => 'yes',
				'description'  => esc_html__('Allow multiple categories, colors, and brands at once.', 'storzen'),
				'condition'    => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'brand_attr_taxonomy',
			array(
				'label'       => esc_html__('Brand taxonomy slug', 'storzen'),
				'type'        => Controls_Manager::TEXT,
				'default'     => 'pa_brand',
				'description' => esc_html__('WooCommerce attribute (e.g. pa_brand) or brands plugin taxonomy. Leave empty to auto-detect (pa_brand, product_brand, pwb-brand, etc.). Never uses product categories.', 'storzen'),
				'condition'   => array(
					'show_sidebar'         => 'yes',
					'show_sidebar_brands' => 'yes',
				),
			)
		);

		$this->add_control(
			'sidebar_recent_title',
			array(
				'label'   => esc_html__('Recent products title', 'storzen'),
				'type'    => Controls_Manager::TEXT,
				'default' => esc_html__('Recent product', 'storzen'),
				'condition' => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'show_sidebar_recent',
			array(
				'label'        => esc_html__('Recent products', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => array('show_sidebar' => 'yes'),
			)
		);

		$this->add_control(
			'sidebar_recent_count',
			array(
				'label'   => esc_html__('Recent products count', 'storzen'),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 1,
				'max'     => 10,
				'default' => 3,
				'condition' => array(
					'show_sidebar'          => 'yes',
					'show_sidebar_recent' => 'yes',
				),
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'grid_section',
			array(
				'label' => esc_html__('Product grid', 'storzen'),
			)
		);

		$this->add_control(
			'column',
			array(
				'label'   => esc_html__('Columns (main area)', 'storzen'),
				'type'    => Controls_Manager::SELECT2,
				'options' => array(
					'2' => esc_html__('6', 'storzen'),
					'3' => esc_html__('4', 'storzen'),
					'4' => esc_html__('3', 'storzen'),
					'6' => esc_html__('2', 'storzen'),
				),
				'default' => '4',
			)
		);

		$this->add_control(
			'ppr',
			array(
				'label'   => esc_html__('Products per page', 'storzen'),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 1,
				'max'     => 48,
				'default' => 12,
			)
		);

		$this->add_control(
			'show_toolbar',
			array(
				'label'        => esc_html__('Show toolbar (count + sort)', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'show_grid_list_icons',
			array(
				'label'        => esc_html__('Grid / list icons (visual)', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => array('show_toolbar' => 'yes'),
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'Post_filter_settings',
			array(
				'label' => esc_html__('Query', 'storzen'),
			)
		);

		$this->add_control(
			'select_cat',
			array(
				'label'    => esc_html__('Product categories', 'storzen'),
				'type'     => Controls_Manager::SELECT2,
				'multiple' => true,
				'options'  => storzen_post_category(),
			)
		);

		$this->add_control(
			'exclude_cat',
			array(
				'label'    => esc_html__('Exclude categories', 'storzen'),
				'type'     => Controls_Manager::SELECT2,
				'multiple' => true,
				'options'  => storzen_post_category(),
			)
		);

		$this->add_control(
			'wc_orderby',
			array(
				'label'   => esc_html__('Sort products by', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'menu_order' => esc_html__('Default sorting', 'storzen'),
					'popularity' => esc_html__('Popularity', 'storzen'),
					'rating'     => esc_html__('Average rating', 'storzen'),
					'date'       => esc_html__('Latest', 'storzen'),
					'price'      => esc_html__('Price: low to high', 'storzen'),
					'price-desc' => esc_html__('Price: high to low', 'storzen'),
				),
				'default' => 'menu_order',
			)
		);

		$this->add_control(
			'order',
			array(
				'label'   => esc_html__('Order', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'ASC'  => esc_html__('ASC', 'storzen'),
					'DESC' => esc_html__('DESC', 'storzen'),
				),
				'default' => 'DESC',
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'title_settings',
			array(
				'label' => esc_html__('Title', 'storzen'),
			)
		);

		$this->add_control(
			'dtitle',
			array(
				'label'   => esc_html__('Product title', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'full'    => esc_html__('Full', 'storzen'),
					'excerpt' => esc_html__('Excerpt', 'storzen'),
				),
				'default' => 'full',
			)
		);

		$this->add_control(
			'title_excerpt_length',
			array(
				'label'     => esc_html__('Title excerpt words', 'storzen'),
				'type'      => Controls_Manager::NUMBER,
				'default'   => 8,
				'condition' => array('dtitle' => 'excerpt'),
			)
		);

		$this->add_control(
			'titltag',
			array(
				'label'   => esc_html__('Title HTML tag', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'h1' => 'H1',
					'h2' => 'H2',
					'h3' => 'H3',
					'h4' => 'H4',
					'h5' => 'H5',
					'h6' => 'H6',
				),
				'default' => 'h6',
			)
		);

		$this->add_control(
			'open-url',
			array(
				'label'       => esc_html__('Open product in', 'storzen'),
				'type'        => Controls_Manager::SELECT,
				'options'     => array(
					'same-window' => esc_html__('Same window', 'storzen'),
					'new-window'  => esc_html__('New window', 'storzen'),
				),
				'default'     => 'same-window',
				'label_block'   => true,
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'pagination_section',
			array(
				'label' => esc_html__('Pagination', 'storzen'),
			)
		);

		$this->add_control(
			'enable_pagination',
			array(
				'label'        => esc_html__('Enable pagination', 'storzen'),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'sidebar_style',
			array(
				'label' => esc_html__('Sidebar Style', 'storzen'),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		storzen_elementor_style_options($this, 'Sidebar Widget Title', '{{WRAPPER}} .shop-sidebar .widget-title', array('style-1'));
		storzen_elementor_style_options($this, 'Sidebar Filter Link', '{{WRAPPER}} .shop-sidebar .szp-filter-link', array('style-1'));
		storzen_elementor_style_options($this, 'Sidebar Active Filter', '{{WRAPPER}} .shop-sidebar .szp-filter-link.is-active', array('style-1'));
		storzen_elementor_style_options($this, 'Sidebar Active Filter Background', '{{WRAPPER}} .shop-sidebar .szp-filter-link.is-active', array('style-1'), 'background-color', false, true);

		storzen_elementor_style_options($this, 'Price Filter Button', '{{WRAPPER}} .shop-sidebar .btn-price button', array('style-1'));
		storzen_elementor_style_options($this, 'Price Readout', '{{WRAPPER}} .shop-sidebar .szp-price-readout', array('style-1'));
		storzen_elementor_style_options($this, 'Price Slider', '{{WRAPPER}} .shop-sidebar .price-slider-range', array('style-1'));

		storzen_elementor_style_options($this, 'Brands Empty Text', '{{WRAPPER}} .shop-sidebar .szp-brands-empty', array('style-1'));
		storzen_elementor_style_options($this, 'Recent Product Title', '{{WRAPPER}} .shop-sidebar .widget-products .content h6 a', array('style-1'));
		storzen_elementor_style_options($this, 'Recent Product Price', '{{WRAPPER}} .shop-sidebar .widget-products .content b', array('style-1'));

		$this->end_controls_section();

		$this->start_controls_section(
			'content_style',
			array(
				'label' => esc_html__('Content Style', 'storzen'),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		storzen_elementor_style_options($this, 'Title', '{{WRAPPER}} .content .woo-title', array('style-1'));
		storzen_elementor_style_options($this, 'Category', '{{WRAPPER}} .content .category', array('style-1'));
		storzen_elementor_style_options($this, 'Pricing', '{{WRAPPER}} .prices span', array('style-1'));

		storzen_elementor_style_options($this, 'New Badge', '{{WRAPPER}} .bgc-black', array('style-1'));
		storzen_elementor_style_options($this, 'New Badge Background', '{{WRAPPER}} .bgc-black', array('style-1'), 'background-color', false, true);

		storzen_elementor_style_options($this, 'Sale Badge', '{{WRAPPER}} .bgc-primary', array('style-1'));
		storzen_elementor_style_options($this, 'Sale Badge Background', '{{WRAPPER}} .bgc-primary', array('style-1'), 'background-color', false, true);

		storzen_elementor_style_options($this, 'List Description', '{{WRAPPER}} .shop-list-sidebar .content p', array('style-1'));
		storzen_elementor_style_options($this, 'List Rating Stars', '{{WRAPPER}} .shop-list-sidebar .ratting i', array('style-1'));
		storzen_elementor_style_options($this, 'Action Icons', '{{WRAPPER}} .shop-card-items .social-style-two i, {{WRAPPER}} .shop-list-sidebar .cart-btns i, {{WRAPPER}} .shop-list-sidebar .shop-icon i', array('style-1'));

		storzen_elementor_style_options($this, 'No Products Message', '{{WRAPPER}} .no-post-found', array('style-1'));

		$this->end_controls_section();

		$this->start_controls_section(
			'toolbar_style',
			array(
				'label' => esc_html__('Toolbar Style', 'storzen'),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		storzen_elementor_style_options($this, 'Result Text', '{{WRAPPER}} .szp-result-text', array('style-1'));
		storzen_elementor_style_options($this, 'Sort Label', '{{WRAPPER}} .sort-label', array('style-1'));
		storzen_elementor_style_options($this, 'Sort Dropdown', '{{WRAPPER}} .szp-sort-select', array('style-1'));
		storzen_elementor_style_options($this, 'View Toggle Icons', '{{WRAPPER}} .szp-view-btn', array('style-1'));

		$this->end_controls_section();

		$this->start_controls_section(
			'pagination_style',
			array(
				'label' => esc_html__('Pagination Style', 'storzen'),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		storzen_elementor_style_options($this, 'Pagination Controls', '{{WRAPPER}} .szp-pagination button.szp-page-btn', array('style-1'));
		storzen_elementor_style_options($this, 'Pagination Disabled', '{{WRAPPER}} .szp-pagination span.previous', array('style-1'));

		$this->end_controls_section();

		$this->start_controls_section(
			'modules_section',
			array( 'label' => esc_html__( 'Modules', 'storzen' ) )
		);
		$this->add_control( 'modules_info', array(
			'type'            => \Elementor\Controls_Manager::RAW_HTML,
			'raw'             => sprintf(
				wp_kses(
					/* translators: %s: URL to module settings page */
					__( 'Each toggle below overrides the global module setting <strong>for this widget only</strong>. A module must be enabled on the <a href="%s" target="_blank">Storzen Modules page</a> before it can be activated here.', 'storzen' ),
					array( 'strong' => array(), 'a' => array( 'href' => array(), 'target' => array() ) ) ),
				esc_url( admin_url( 'admin.php?page=storzen-modules' ) )
			),
			'content_classes' => 'elementor-panel-alert elementor-panel-alert-info',
		) );
		foreach ( array(
			'module_sale_badge'         => array( 'Sale Badge',             'Show Hot, New, and Sale % badges on each product card.' ),
			'module_quick_view'         => array( 'Quick View',             'Show a Quick View eye icon on each product card.' ),
			'module_wishlist'           => array( 'Wishlist',               'Show a Wishlist heart icon on each product card.' ),
			'module_compare'            => array( 'Compare Products',       'Show a Compare icon on each product card.' ),
			'module_flash_countdown'    => array( 'Flash Sale Countdown',   'Show a sale countdown timer below the price on each product card.' ),
			'module_stock_scarcity'     => array( 'Stock Scarcity',         'Show "Only X left!" urgency messages below the price on each product card.' ),
			'module_variation_swatches' => array( 'Variation Swatches',    'Show color / image / button swatches on variable product cards.' ),
			'module_preorder'           => array( 'Pre-Order',              'Show the Pre-Order badge on each product card. (Pro)' ),
			'module_quick_checkout'     => array( 'Quick Checkout',         'Show the Quick Checkout button on each product card. (Pro)' ),
		) as $key => $info ) {
			$this->add_control( $key, array(
				'label'        => esc_html__( $info[0], 'storzen' ), // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
				'description'  => esc_html__( $info[1], 'storzen' ), // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			) );
		}
		$this->end_controls_section();
	}

	/**
	 * Current page URL for filters / forms.
	 *
	 * @return string
	 */
	protected function get_current_page_url()
	{
		if (is_singular() && get_queried_object_id()) {
			return get_permalink(get_queried_object_id());
		}
		global $post;
		if ($post && is_a($post, 'WP_Post')) {
			return get_permalink($post);
		}
		return home_url('/');
	}

	/**
	 * Render widget output.
	 */
	protected function render()
	{
		if (! function_exists('WC')) {
			echo '<p>' . esc_html__('WooCommerce is required for this widget.', 'storzen') . '</p>';
			return;
		}

		if (! function_exists('storzen_shop_sidebar_build_query_args')) {
			echo '<p>' . esc_html__('Shop sidebar helpers are missing.', 'storzen') . '</p>';
			return;
		}

		$settings = $this->get_settings_for_display();

		if (is_front_page()) {
			$paged = (int) get_query_var('page');
		} else {
			$paged = (int) get_query_var('paged');
		}
		if ($paged < 1) {
			$paged = 1;
		}

		$query_settings = storzen_shop_sidebar_sanitize_settings($settings);

		$filters = array(
			'paged'             => $paged,
			'orderby'           => $query_settings['wc_orderby'],
			'order'             => $query_settings['order'],
			'product_cat_slugs' => array(),
			'color_slugs'       => array(),
			'brand_slugs'       => array(),
		);
		$filters = storzen_shop_sidebar_filters_from_request($filters, $query_settings);

		if (! empty($filters['orderby'])) {
			$query_settings['wc_orderby'] = $filters['orderby'];
			$settings['wc_orderby']       = $filters['orderby'];
		}

		$args                     = storzen_shop_sidebar_build_query_args($query_settings, $filters);
		$storzen_posts_query = new \WP_Query($args);

		$szp_shop_sidebar_base_url = $this->get_current_page_url();
		$szp_element_id            = $this->get_id();
		$szp_filters               = $filters;

		$szp_inline = array(
			'elementId'        => $szp_element_id,
			'settings'       => $query_settings,
			'initialFilters' => $szp_filters,
			'pageUrl'        => $szp_shop_sidebar_base_url,
		);
		wp_add_inline_script(
			'storzen-shop-sidebar',
			'window.WcommeroProShopSidebarCfg=window.WcommeroProShopSidebarCfg||{};window.WcommeroProShopSidebarCfg[' . wp_json_encode($szp_element_id) . ']=' . wp_json_encode($szp_inline) . ';',
			'after'
		);

		\Elementor\Storzen_Archive_Grid::set_active_module_settings( $settings );
		include storzen_get_template('shop-sidebar.php');
		\Elementor\Storzen_Archive_Grid::clear_active_module_settings();
	}
}

plugin::instance()->widgets_manager->register(new Storzen_Shop_Sidebar());
