<?php

namespace Elementor;

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

/**
 * Grid style widget.
 *
 * @package storzen
 */
class Storzen_Grid extends Widget_Base
{
	public function get_name()
	{
		return 'storzen-grid';
	}

	public function get_title()
	{
		return esc_html__('Grid Style', 'storzen');
	}

	public function get_icon()
	{
		return 'eicon-products';
	}

	public function get_categories()
	{
		return array('storzen');
	}

	protected function register_controls()
	{
		$this->start_controls_section(
			'grid_general_settings',
			array(
				'label' => esc_html__('General Settings', '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(
			'column',
			array(
				'label'   => esc_html__('Column', '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__('Amount of products to display', 'storzen'),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 1,
				'max'     => 48,
				'default' => 12,
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'grid_query_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(
			'orderby',
			array(
				'label'   => esc_html__('Order by', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'date'       => esc_html__('Date', 'storzen'),
					'title'      => esc_html__('Title', 'storzen'),
					'menu_order' => esc_html__('Menu order', 'storzen'),
					'rand'       => esc_html__('Random', 'storzen'),
				),
				'default' => 'date',
			)
		);

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

		$this->end_controls_section();

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

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

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

		$this->add_control(
			'titltag',
			array(
				'label'   => esc_html__('Title 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',
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'other_settings',
			array(
				'label' => esc_html__('Other Settings', '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(
			'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, 'Action Icons', '{{WRAPPER}} .social-style-two i', 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, 'Pagination Link', '{{WRAPPER}} .pagination.style-two a', 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(
			'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();
	}

	protected function render()
	{
		if (! function_exists('WC')) {
			echo '<p>' . esc_html__('WooCommerce is required for this widget.', '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;
		}

		$orderby = isset($settings['orderby']) ? sanitize_key((string) $settings['orderby']) : 'date';
		if (! in_array($orderby, array('date', 'title', 'menu_order', 'rand'), true)) {
			$orderby = 'date';
		}

		$order = isset($settings['order']) ? strtoupper((string) $settings['order']) : 'DESC';
		if (! in_array($order, array('ASC', 'DESC'), true)) {
			$order = 'DESC';
		}

		$args = array(
			'post_type'           => 'product',
			'post_status'         => 'publish',
			'ignore_sticky_posts' => 1,
			'posts_per_page'      => isset($settings['ppr']) ? max(1, (int) $settings['ppr']) : 12,
			'paged'               => $paged,
			'orderby'             => $orderby,
			'order'               => $order,
		);

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- public query input for filtering.
		$args['s'] = isset($_GET['keyword']) ? sanitize_text_field(wp_unslash($_GET['keyword'])) : '';

		$tax_query = array();
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- public query input for filtering.
		if ( ! empty( $_GET['product_cat'] ) && '-1' !== (string) $_GET['product_cat'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended,WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Public filter, sanitized below via sanitize_text_field(wp_unslash()).
			$tax_query[] = array(
				'taxonomy' => 'product_cat',
				'field'    => 'slug',
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- public query input for filtering.
				'terms'    => sanitize_text_field(wp_unslash($_GET['product_cat'])),
			);
		} elseif (! empty($settings['select_cat']) && is_array($settings['select_cat'])) {
			$tax_query[] = array(
				'taxonomy' => 'product_cat',
				'field'    => 'term_id',
				'terms'    => array_values(array_map('absint', $settings['select_cat'])),
			);
		}

		if (! empty($settings['exclude_cat']) && is_array($settings['exclude_cat'])) {
			$tax_query[] = array(
				'taxonomy' => 'product_cat',
				'field'    => 'term_id',
				'terms'    => array_values(array_map('absint', $settings['exclude_cat'])),
				'operator' => 'NOT IN',
			);
		}

		if (! empty($tax_query)) {
			// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_tax_query
			// Intentional: tax_query is required for category filtering in the
			// Elementor product grid widget. No WP_Query alternative exists.
			$args['tax_query'] = $tax_query;
			// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_tax_query
		}

		$storzen_posts_query = new \WP_Query($args);
		\Elementor\Storzen_Archive_Grid::set_active_module_settings( $settings );
		include storzen_get_template('grid.php');
		\Elementor\Storzen_Archive_Grid::clear_active_module_settings();
	}
}

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