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

/**
 * Single product Elementor widgets (Shop Details tab toggles).
 *
 * @package storzen
 */

namespace Elementor;

use Elementor\Repeater;

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

/**
 * Shared helpers for single-product widgets.
 */
trait Storzen_Product_Part_Helpers
{

	/**
	 * @return \WC_Product|null
	 */
	protected function szp_get_loop_product()
	{
		if (! function_exists('wc_get_product')) {
			return null;
		}
		$id = get_the_ID();
		if (! $id) {
			return null;
		}
		$p = wc_get_product($id);
		return ($p instanceof \WC_Product) ? $p : null;
	}

	/**
	 * @param string $label Placeholder label in the editor.
	 * @return bool True if placeholder was rendered (stop render).
	 */
	protected function szp_maybe_placeholder($label)
	{
		if ($this->szp_get_loop_product()) {
			return false;
		}
		$ed = \Elementor\Plugin::$instance->editor;
		if ($ed && method_exists($ed, 'is_edit_mode') && $ed->is_edit_mode()) {
			printf(
				'<div class="szp-product-part-placeholder" style="padding:16px;border:1px dashed #ccc;border-radius:6px;background:#f9f9f9;font-size:13px;color:#555;">%s</div>',
				esc_html($label)
			);
			return true;
		}
		return false;
	}

	/**
	 * Set global $product for WooCommerce templates.
	 *
	 * @return \WC_Product|null
	 */
	protected function szp_setup_global_product()
	{
		$p = $this->szp_get_loop_product();
		global $product;
		$product = $p;
		return $p;
	}

	/**
	 * Wrapper for styles scoped under .product-details-content in main.css (shop-details.html).
	 */
	protected function szp_pd_fragment_open()
	{
		echo '<div class="product-details-content szp-pd-fragment">';
	}

	protected function szp_pd_fragment_close()
	{
		echo '</div>';
	}

	/**
	 * Term links as in shop-details.html (space-separated &lt;a&gt; tags).
	 *
	 * @param int    $product_id Post ID.
	 * @param string $taxonomy   Taxonomy slug.
	 * @return string HTML or empty string.
	 */
	protected function szp_get_term_links_html($product_id, $taxonomy)
	{
		$terms = get_the_terms($product_id, $taxonomy);
		if (empty($terms) || is_wp_error($terms)) {
			return '';
		}
		$out = array();
		foreach ($terms as $term) {
			$link = get_term_link($term);
			if (is_wp_error($link)) {
				continue;
			}
			$out[] = '<a href="' . esc_url($link) . '">' . esc_html($term->name) . '</a>';
		}
		return implode(' ', $out);
	}
}

/**
 * Product title.
 */
class Storzen_Product_Title_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-title';
	}

	public function get_title()
	{
		return esc_html__('Product Title', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_title',
			array(
				'label' => esc_html__('Title', 'storzen'),
			)
		);
		$this->add_control(
			'html_tag',
			array(
				'label'   => esc_html__('HTML Tag', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'h1' => 'H1',
					'h2' => 'H2',
					'h3' => 'H3',
					'h4' => 'H4',
					'h5' => 'H5',
					'h6' => 'H6',
				),
				'default' => 'h4',
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Product Title — assign this template to a single product or preview on a product page.', 'storzen'))) {
			return;
		}
		$settings = $this->get_settings_for_display();
		$tag      = isset($settings['html_tag']) ? sanitize_key($settings['html_tag']) : 'h4';
		if (! in_array($tag, array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'), true)) {
			$tag = 'h4';
		}
		$this->szp_pd_fragment_open();
		printf(
			'<%1$s class="title mb-20 szp-product-title product_title entry-title">%2$s</%1$s>',
			esc_attr($tag),
			esc_html(get_the_title())
		);
		$this->szp_pd_fragment_close();
	}
}

/**
 * Product price.
 */
class Storzen_Product_Price_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-price';
	}

	public function get_title()
	{
		return esc_html__('Product Price', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_price',
			array(
				'label' => esc_html__('Price', 'storzen'),
			)
		);
		$this->add_control(
			'vat_note',
			array(
				'label'       => esc_html__('Price note / VAT text', 'storzen'),
				'type'        => Controls_Manager::TEXT,
				'default'     => '',
				'placeholder' => '(15% Vat Included)',
				'description' => esc_html__('Shown after the price, matching shop-details.html (optional).', 'storzen'),
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Product Price', 'storzen'))) {
			return;
		}
		$product = $this->szp_get_loop_product();
		if (! $product) {
			return;
		}
		$settings = $this->get_settings_for_display();
		$vat      = isset($settings['vat_note']) ? trim((string) $settings['vat_note']) : '';
		$this->szp_pd_fragment_open();
		echo '<div class="price-vat mb-25 szp-price-vat">';
		echo '<span class="price">' . wp_kses_post($product->get_price_html()) . '</span>';
		if ($vat !== '') {
			echo '<span class="vat-text bat-text">' . esc_html($vat) . '</span>';
		}
		echo '</div>';

		/**
		 * Fires inside the Storzen single-product Price widget, after the
		 * price block — natural insertion point for Sale Badge "Save $X"
		 * chip, Flash Countdown timer, Stock Scarcity messages.
		 *
		 * @param WC_Product $product Current product.
		 */
		do_action( 'storzen_product_single_after_price', $product );

		$this->szp_pd_fragment_close();
	}
}

/**
 * Product rating (stars).
 */
class Storzen_Product_Rating_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-rating';
	}

	public function get_title()
	{
		return esc_html__('Product Rating', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_tabs_description',
			array(
				'label' => esc_html__('Description Tab', 'storzen'),
			)
		);
		$this->add_control(
			'description_source',
			array(
				'label'   => esc_html__('Description source', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'product_long'  => esc_html__('Product full description', 'storzen'),
					'product_short' => esc_html__('Product short description', 'storzen'),
					'product_tab_box' => esc_html__('Product tab description box', 'storzen'),
					'custom'        => esc_html__('Custom description box', 'storzen'),
				),
				'default' => 'product_tab_box',
			)
		);
		$this->add_control(
			'custom_description_box',
			array(
				'label'       => esc_html__('Custom description box', 'storzen'),
				'type'        => Controls_Manager::WYSIWYG,
				'default'     => '',
				'description' => esc_html__('Used only when "Custom description box" source is selected.', 'storzen'),
				'condition'   => array(
					'description_source' => 'custom',
				),
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Product Rating', 'storzen'))) {
			return;
		}
		if (! $this->szp_setup_global_product()) {
			return;
		}
		$this->szp_pd_fragment_open();
		echo '<div class="ratting mb-10 szp-ratting">';
		woocommerce_template_single_rating();
		echo '</div>';
		$this->szp_pd_fragment_close();
	}
}

/**
 * Add to cart form.
 */
class Storzen_Product_Add_To_Cart_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-add-to-cart';
	}

	public function get_title()
	{
		return esc_html__('Add to Cart', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_tabs_description',
			array(
				'label' => esc_html__('Description Tab', 'storzen'),
			)
		);
		$this->add_control(
			'description_source',
			array(
				'label'   => esc_html__('Description source', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'product_tab_box' => esc_html__('Product tab description box', 'storzen'),
					'product_short'   => esc_html__('Product short description', 'storzen'),
					'product_long'    => esc_html__('Product full description', 'storzen'),
					'custom'          => esc_html__('Custom description box', 'storzen'),
				),
				'default' => 'product_tab_box',
			)
		);
		$this->add_control(
			'custom_description_box',
			array(
				'label'       => esc_html__('Custom description box', 'storzen'),
				'type'        => Controls_Manager::WYSIWYG,
				'default'     => '',
				'description' => esc_html__('Used only when "Custom description box" source is selected.', 'storzen'),
				'condition'   => array(
					'description_source' => 'custom',
				),
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Add to Cart', 'storzen'))) {
			return;
		}
		if (! $this->szp_setup_global_product()) {
			return;
		}
		$this->szp_pd_fragment_open();
		echo '<div class="szp-product-add-to-cart szp-wc-add-to-cart">';
		// Elementor single-product templates often omit woocommerce_before_single_product(), so cart success/error notices never print.
		if ( function_exists( 'woocommerce_output_all_notices' ) ) {
			woocommerce_output_all_notices();
		}
		echo '<b class="szp-atc-qty-label">' . esc_html__('Quantity:', 'storzen') . '</b>';
		echo '<div class="quantity-btn szp-wc-atc-row">';
		$GLOBALS['storzen_single_atc'] = true;
		try {
			woocommerce_template_single_add_to_cart();
		} finally {
			unset($GLOBALS['storzen_single_atc']);
		}
		echo '</div></div>';
		$this->szp_pd_fragment_close();
	}
}

/**
 * Product images / gallery.
 */
class Storzen_Product_Gallery_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-gallery';
	}

	public function get_title()
	{
		return esc_html__('Product Gallery', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_gallery',
			array(
				'label' => esc_html__('Gallery', 'storzen'),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);
		$this->add_control(
			'gallery_layout',
			array(
				'label'   => esc_html__('Layout', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'layout_1' => esc_html__('Layout One', 'storzen'),
					'layout_2' => esc_html__('Layout Two', 'storzen'),
					'layout_3' => esc_html__('Layout Three', 'storzen'),
				),
				'default' => 'layout_1',
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Product Gallery', 'storzen'))) {
			return;
		}
		$product = $this->szp_setup_global_product();
		if (! $product) {
			return;
		}
		$settings = $this->get_settings_for_display();
		$layout   = isset($settings['gallery_layout']) ? $settings['gallery_layout'] : 'layout_1';
		if ('layout_2' === $layout && function_exists('storzen_print_single_product_gallery_layout_two')) {
			storzen_print_single_product_gallery_layout_two($product);
			return;
		}
		if ('layout_3' === $layout && function_exists('storzen_print_single_product_gallery_layout_three')) {
			storzen_print_single_product_gallery_layout_three($product);
			return;
		}
		if (function_exists('storzen_print_single_product_gallery')) {
			storzen_print_single_product_gallery($product);
		}
	}
}

/**
 * Short or long description.
 */
class Storzen_Product_Description_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-description';
	}

	public function get_title()
	{
		return esc_html__('Product Description', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_desc',
			array(
				'label' => esc_html__('Description', 'storzen'),
			)
		);
		$this->add_control(
			'description_type',
			array(
				'label'   => esc_html__('Source', 'storzen'),
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'short'  => esc_html__('Short description', 'storzen'),
					'long'   => esc_html__('Full content', 'storzen'),
					'custom' => esc_html__('Custom Content', 'storzen'),
				),
				'default' => 'short',
			)
		);

		$this->add_control(
			'custom_description',
			array(
				'label'       => esc_html__('Custom Description Content', 'storzen'),
				'type'        => Controls_Manager::WYSIWYG,
				'default'     => '',
				'description' => esc_html__('Add your custom description content here. This will be displayed in the description tab.', 'storzen'),
				'condition'   => array(
					'description_type' => 'custom',
				),
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Product Description', 'storzen'))) {
			return;
		}
		if (! $this->szp_setup_global_product()) {
			return;
		}
		$settings = $this->get_settings_for_display();
		$type     = isset($settings['description_type']) ? $settings['description_type'] : 'short';
		echo '<div class="szp-product-description woocommerce-product-details__short-description">';
		$this->szp_pd_fragment_open();
		if ('custom' === $type) {
			$custom_content = isset($settings['custom_description']) ? $settings['custom_description'] : '';
			echo wp_kses_post($custom_content);
		} elseif ('long' === $type) {
			// Get only the product description, not Elementor content
			$product_id = get_the_ID();
			$product_post = get_post($product_id);
			if ($product_post) {
				// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Intentionally reusing WP core filter
				echo wp_kses_post(apply_filters('the_content', $product_post->post_content));
			}
		} else {
			woocommerce_template_single_excerpt();
		}
		$this->szp_pd_fragment_close();
		echo '</div>';
	}
}

/**
 * Related products grid.
 */
class Storzen_Product_Related_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-related';
	}

	public function get_title()
	{
		return esc_html__('Related Products', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_related',
			array(
				'label' => esc_html__('Related Products', 'storzen'),
			)
		);
		$this->add_control(
			'related_count_override',
			array(
				'label'       => esc_html__('Number of products', 'storzen'),
				'type'        => Controls_Manager::NUMBER,
				'min'         => 1,
				'max'         => 24,
				'step'        => 1,
				'placeholder' => esc_html__('From Shop Details', 'storzen'),
				'description' => esc_html__('Total products (WooCommerce related first, then same category). Use 8+ for two pages at 4 columns. Leave empty to use Shop Details (saved value 4 is treated as 12).', 'storzen'),
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Related Products', 'storzen'))) {
			return;
		}
		$product = $this->szp_setup_global_product();
		if (! $product) {
			return;
		}
		$settings = $this->get_settings_for_display();
		$saved    = (int) storzen_get_shop_details_option('related_count', 12);
		$limit    = $saved;
		if (isset($settings['related_count_override']) && '' !== $settings['related_count_override'] && null !== $settings['related_count_override']) {
			$limit = (int) $settings['related_count_override'];
		} elseif (4 === $saved) {
			// Old default was 4 — not enough for a second slider page at 4 columns.
			$limit = 12;
		}
		$limit = max(1, min(24, $limit));
		if (function_exists('storzen_print_related_products_slider')) {
			storzen_print_related_products_slider($product, $limit);
		}
	}
}

/**
 * Product data tabs (description, additional info, reviews).
 */
class Storzen_Product_Tabs_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-tabs';
	}

	public function get_title()
	{
		return esc_html__('Product Tabs', 'storzen');
	}

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

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

	protected function register_controls() {}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Product Tabs', 'storzen'))) {
			return;
		}
		if (! $this->szp_setup_global_product()) {
			return;
		}

		$settings           = $this->get_settings_for_display();
		$description_source = isset($settings['description_source']) ? $settings['description_source'] : 'product_tab_box';
		$custom_desc_box    = isset($settings['custom_description_box']) ? $settings['custom_description_box'] : '';

		$tabs = apply_filters('woocommerce_product_tabs', array());
		if (empty($tabs) || ! is_array($tabs)) {
			echo '<p class="szp-product-tabs-empty">' . esc_html__('No product tabs.', 'storzen') . '</p>';
			return;
		}

		$uid = 'szp-pd-' . (int) get_the_ID();
?>
		<div class="product-description-area pb-80 szp-product-description-area">
			<div class="wco-container elementor-container szp-product-tabs-inner">
				<div class="product-description-tab szp-product-description-tab">
					<div class="nav custom-tabs" role="tablist">
						<?php
						$i = 0;
						foreach ($tabs as $key => $tab) {
							$panel_id = $uid . '-tab-' . $i;
							$title    = isset($tab['title']) ? $tab['title'] : '';
						?>
							<button type="button" class="nav-link<?php echo 0 === $i ? ' active' : ''; ?>" data-tab="<?php echo esc_attr($panel_id); ?>" role="tab" aria-selected="<?php echo 0 === $i ? 'true' : 'false'; ?>">
								<?php echo wp_kses_post($title); ?>
							</button>
						<?php
							++$i;
						}
						?>
					</div>
					<div class="tab-content">
						<?php
						$i = 0;
						foreach ($tabs as $key => $tab) {
							$panel_id = $uid . '-tab-' . $i;
							$classes  = 'tab-pane tab-pane-' . sanitize_html_class($key);
							$classes .= (0 === $i) ? ' fade show active' : ' fade';
						?>
							<div class="<?php echo esc_attr($classes); ?>" id="<?php echo esc_attr($panel_id); ?>" role="tabpanel">
								<?php
								// Description tab: choose source from widget settings.
								if (function_exists('storzen_product_tab_is_long_description') && function_exists('storzen_render_description_tab_without_related') && storzen_product_tab_is_long_description($key, $tab)) {
									if ('custom' === $description_source) {
										echo '<div class="woocommerce-Tabs-panel--description szp-product-tab-description-box">';
										echo wp_kses_post($custom_desc_box);
										echo '</div>';
									} elseif ('product_tab_box' === $description_source) {
										$tab_box_content = get_post_meta(get_the_ID(), '_storzen_tab_description', true);
										echo '<div class="woocommerce-Tabs-panel--description szp-product-tab-description-box">';
										if (! empty($tab_box_content)) {
											// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Intentionally reusing WP core filter for rich text output.
											echo wp_kses_post(apply_filters('the_content', $tab_box_content));
										}
										echo '</div>';
									} elseif ('product_short' === $description_source) {
										echo '<div class="woocommerce-Tabs-panel--description szp-product-tab-description-box woocommerce-product-details__short-description">';
										woocommerce_template_single_excerpt();
										echo '</div>';
									} elseif ('product_long' === $description_source) {
										storzen_render_description_tab_without_related($key, $tab);
									} else {
										// Safe fallback: if source is missing/old value, prefer dedicated tab box.
										$tab_box_content = get_post_meta(get_the_ID(), '_storzen_tab_description', true);
										echo '<div class="woocommerce-Tabs-panel--description szp-product-tab-description-box">';
										if (! empty($tab_box_content)) {
											// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Intentionally reusing WP core filter for rich text output.
											echo wp_kses_post(apply_filters('the_content', $tab_box_content));
										}
										echo '</div>';
									}
								} elseif (isset($tab['callback']) && is_callable($tab['callback'])) {
									call_user_func($tab['callback'], $key, $tab);
								}
								?>
							</div>
						<?php
							++$i;
						}
						?>
					</div>
				</div>
			</div>
		</div>
	<?php
	}
}

/**
 * Sticky add-to-cart bar (simple / external products work best).
 */
class Storzen_Product_Sticky_Atc_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-sticky-atc';
	}

	public function get_title()
	{
		return esc_html__('Sticky Add to Cart', 'storzen');
	}

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

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

	protected function register_controls() {}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Sticky Add to Cart', 'storzen'))) {
			return;
		}
		$product = $this->szp_get_loop_product();
		if (! $product || ! $product->is_purchasable()) {
			return;
		}
		$offset = (int) storzen_get_shop_details_option('sticky_atc_offset', 12);
		$offset = max(0, min(200, $offset));
	?>
		<div class="szp-sticky-atc" style="position:fixed;left:0;right:0;bottom:<?php echo esc_attr((string) $offset); ?>px;z-index:9999;background:#fff;box-shadow:0 -4px 20px rgba(0,0,0,.08);padding:12px 16px;display:flex;align-items:center;justify-content:center;gap:16px;flex-wrap:wrap;">
			<span class="szp-sticky-atc__price" style="font-weight:600;"><?php echo wp_kses_post($product->get_price_html()); ?></span>
			<div class="szp-sticky-atc__btn">
				<?php
				$product = $this->szp_get_loop_product();
				if ($product->is_type('simple') && $product->is_in_stock()) {
					echo sprintf(
						'<a href="%s" class="button product_type_simple add_to_cart_button ajax_add_to_cart" data-product_id="%d" data-quantity="1" rel="nofollow">%s</a>',
						esc_url($product->add_to_cart_url()),
						(int) $product->get_id(),
						esc_html($product->add_to_cart_text())
					);
				} else {
					echo sprintf(
						'<a href="%s" class="button">%s</a>',
						esc_url($product->add_to_cart_url()),
						esc_html($product->add_to_cart_text())
					);
				}
				?>
			</div>
		</div>
	<?php
	}
}

/**
 * Social share links.
 */
class Storzen_Product_Share_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-share';
	}

	public function get_title()
	{
		return esc_html__('Product Share', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_share',
			array(
				'label' => esc_html__('Share links', 'storzen'),
			)
		);
		$this->add_control(
			'youtube_url',
			array(
				'label'       => esc_html__('YouTube URL', 'storzen'),
				'type'        => Controls_Manager::URL,
				'placeholder' => 'https://',
				'default'     => array('url' => ''),
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Product Share', 'storzen'))) {
			return;
		}
		$product = $this->szp_get_loop_product();
		if (! $product) {
			return;
		}
		$settings = $this->get_settings_for_display();
		$url      = get_permalink($product->get_id());
		$title    = get_the_title($product->get_id());
		$enc_u    = rawurlencode($url);
		$enc_t    = rawurlencode($title);
		$yt       = isset($settings['youtube_url']['url']) ? trim((string) $settings['youtube_url']['url']) : '';
		if ($yt === '') {
			$yt = 'https://www.youtube.com/';
		}
		$this->szp_pd_fragment_open();
	?>
		<div class="social-share szp-social-share">
			<a class="facebook" href="<?php echo esc_url('https://www.facebook.com/sharer/sharer.php?u=' . $enc_u); ?>" target="_blank" rel="noopener noreferrer"><i class="fab fa-facebook-f" aria-hidden="true"></i> <?php esc_html_e('Facebook', 'storzen'); ?></a>
			<a class="twitter" href="<?php echo esc_url('https://twitter.com/intent/tweet?url=' . $enc_u . '&text=' . $enc_t); ?>" target="_blank" rel="noopener noreferrer"><i class="fab fa-twitter" aria-hidden="true"></i> <?php esc_html_e('Twitter', 'storzen'); ?></a>
			<a class="youtube" href="<?php echo esc_url($yt); ?>" target="_blank" rel="noopener noreferrer"><i class="fab fa-youtube" aria-hidden="true"></i> <?php esc_html_e('Youtube', 'storzen'); ?></a>
			<a class="instagram" href="<?php echo esc_url('https://www.instagram.com/'); ?>" target="_blank" rel="noopener noreferrer"><i class="fab fa-instagram" aria-hidden="true"></i> <?php esc_html_e('Instagram', 'storzen'); ?></a>
		</div>
	<?php
		$this->szp_pd_fragment_close();
	}
}

/**
 * SKU, product categories and tags (shop-details.html .sku-category-tags).
 */
class Storzen_Product_Meta_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-meta';
	}

	public function get_title()
	{
		return esc_html__('SKU, Category & Tags', 'storzen');
	}

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

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

	protected function register_controls() {}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('SKU, Category & Tags', 'storzen'))) {
			return;
		}
		$product = $this->szp_get_loop_product();
		if (! $product) {
			return;
		}
		$pid = (int) $product->get_id();
		$this->szp_pd_fragment_open();
		echo '<ul class="sku-category-tags mb-20 szp-sku-category-tags">';
		$sku = $product->get_sku();
		echo '<li><b>' . esc_html__('SKU:', 'storzen') . '</b> <span class="sku">' . ($sku ? esc_html($sku) : '&mdash;') . '</span></li>';
		$cats = $this->szp_get_term_links_html($pid, 'product_cat');
		echo '<li><b>' . esc_html__('Category:', 'storzen') . '</b> ';
		echo $cats ? wp_kses_post($cats) : '&mdash;';
		echo '</li>';
		$tags = $this->szp_get_term_links_html($pid, 'product_tag');
		echo '<li><b>' . esc_html__('Tags:', 'storzen') . '</b> ';
		echo $tags ? wp_kses_post($tags) : '&mdash;';
		echo '</li>';
		echo '</ul>';
		$this->szp_pd_fragment_close();
	}
}

/**
 * Service info blocks (shop-details.html .product-details-info .info-item.style-two).
 */
class Storzen_Product_Service_Info_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-service-info';
	}

	public function get_title()
	{
		return esc_html__('Product Service Info', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$repeater = new Repeater();
		$repeater->add_control(
			'item_title',
			array(
				'label'   => esc_html__('Title', 'storzen'),
				'type'    => Controls_Manager::TEXT,
				'default' => esc_html__('Free Shipping', 'storzen'),
			)
		);
		$repeater->add_control(
			'item_text',
			array(
				'label'   => esc_html__('Description', 'storzen'),
				'type'    => Controls_Manager::TEXTAREA,
				'default' => esc_html__("Brought good third life image you're brought days", 'storzen'),
				'rows'    => 3,
			)
		);
		$repeater->add_control(
			'item_svg',
			array(
				'label'       => esc_html__('Custom SVG icon', 'storzen'),
				'type'        => Controls_Manager::CODE,
				'language'    => 'html',
				'description' => esc_html__('Optional. Leave empty to use the default Storzen template inline SVG for this row (cycles 3 icons).', 'storzen'),
				'rows'        => 6,
			)
		);
		$this->start_controls_section(
			'section_items',
			array(
				'label' => esc_html__('Info items', 'storzen'),
			)
		);
		$this->add_control(
			'service_items',
			array(
				'label'       => esc_html__('Items', 'storzen'),
				'type'        => Controls_Manager::REPEATER,
				'fields'      => $repeater->get_controls(),
				'default'     => array(
					array(
						'item_title' => __('Free Shipping', 'storzen'),
						'item_text'  => __("Brought good third life image you're brought days", 'storzen'),
					),
					array(
						'item_title' => __('Support 24/7', 'storzen'),
						'item_text'  => __("Brought good third life image you're brought days", 'storzen'),
					),
					array(
						'item_title' => __('30 Days Return', 'storzen'),
						'item_text'  => __("Brought good third life image you're brought days", 'storzen'),
					),
				),
				'title_field' => '{{{ item_title }}}',
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Product Service Info', 'storzen'))) {
			return;
		}
		$settings = $this->get_settings_for_display();
		$items    = isset($settings['service_items']) ? $settings['service_items'] : array();
		if (empty($items)) {
			return;
		}
		echo '<div class="product-details-info pb-30 szp-product-details-info">';
		$defaults = function_exists('storzen_service_info_default_svgs') ? storzen_service_info_default_svgs() : array('', '', '');
		foreach ($items as $idx => $item) {
			$t = isset($item['item_title']) ? $item['item_title'] : '';
			$d = isset($item['item_text']) ? $item['item_text'] : '';
			$custom_svg = isset($item['item_svg']) ? trim((string) $item['item_svg']) : '';
			echo '<div class="info-item style-two wow fadeInUp delay-0-2s">';
			echo '<div class="icon">';
			if ($custom_svg !== '' && function_exists('storzen_kses_svg')) {
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- storzen_kses_svg() sanitizes SVG output
				echo storzen_kses_svg($custom_svg);
			} elseif (! empty($defaults[$idx % 3]) && function_exists('storzen_kses_svg')) {
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- storzen_kses_svg() sanitizes SVG output
				echo storzen_kses_svg($defaults[$idx % 3]);
			}
			echo '</div><div class="content">';
			echo '<h6>' . esc_html($t) . '</h6>';
			echo '<p>' . esc_html($d) . '</p>';
			echo '</div></div>';
		}
		echo '</div>';
	}
}

/**
 * Buy it now — checkout with product in cart (simple) or product link (variable).
 */
class Storzen_Product_Buy_Now_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-buy-now';
	}

	public function get_title()
	{
		return esc_html__('Buy It Now', 'storzen');
	}

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

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

	protected function register_controls() {}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Buy It Now', 'storzen'))) {
			return;
		}
		$product = $this->szp_get_loop_product();
		if (! $product || ! $product->is_purchasable()) {
			return;
		}
		$this->szp_pd_fragment_open();
		if ($product->is_type('simple') && $product->is_in_stock()) {
			$url = add_query_arg(array('add-to-cart' => $product->get_id()), wc_get_checkout_url());
		} else {
			$url = apply_filters('storzen_buy_now_url', $product->add_to_cart_url(), $product);
		}
		echo '<a href="' . esc_url($url) . '" class="theme-btn buy-now style-two w-100 szp-buy-now">' . esc_html__('Buy it now', 'storzen') . '</a>';
		$this->szp_pd_fragment_close();
	}
}

/**
 * Compare, shipping, ask question row (shop-details.html .compare-shipping-question).
 */
class Storzen_Product_Utility_Links_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-utility-links';
	}

	public function get_title()
	{
		return esc_html__('Compare / Shipping / Ask', 'storzen');
	}

	public function get_icon()
	{
		return 'eicon-editor-list-ul';
	}

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_links',
			array(
				'label' => esc_html__('Links', 'storzen'),
			)
		);
		$this->add_control(
			'compare_url',
			array(
				'label'       => esc_html__('Compare URL', 'storzen'),
				'type'        => Controls_Manager::URL,
				'placeholder' => '#',
				'default'     => array('url' => '#'),
			)
		);
		$this->add_control(
			'shipping_url',
			array(
				'label'       => esc_html__('Shipping URL', 'storzen'),
				'type'        => Controls_Manager::URL,
				'placeholder' => '#',
				'default'     => array('url' => '#'),
			)
		);
		$this->add_control(
			'ask_url',
			array(
				'label'       => esc_html__('Ask question URL', 'storzen'),
				'type'        => Controls_Manager::URL,
				'placeholder' => '/contact/',
				'default'     => array('url' => '#'),
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Compare / Shipping / Ask', 'storzen'))) {
			return;
		}
		$product = $this->szp_get_loop_product();
		if (! $product) {
			return;
		}
		$settings = $this->get_settings_for_display();
		$c        = isset($settings['compare_url']['url']) ? $settings['compare_url']['url'] : '';
		$s        = isset($settings['shipping_url']['url']) ? $settings['shipping_url']['url'] : '';
		$a        = isset($settings['ask_url']['url']) ? $settings['ask_url']['url'] : '';
		$compare  = apply_filters('storzen_product_compare_url', $c ? $c : '#', $product);
		$ship     = $s ? $s : '#';
		$ask      = $a ? $a : '#';
		$this->szp_pd_fragment_open();
	?>
		<ul class="compare-shipping-question my-20 szp-utility-links">
			<li><i class="fas fa-sync" aria-hidden="true"></i> <span><a href="<?php echo esc_url($compare); ?>"><?php esc_html_e('Compare', 'storzen'); ?></a></span></li>
			<li><i class="fas fa-truck" aria-hidden="true"></i> <span><a href="<?php echo esc_url($ship); ?>"><?php esc_html_e('Shipping', 'storzen'); ?></a></span></li>
			<li><i class="far fa-comment-dots" aria-hidden="true"></i> <a href="<?php echo esc_url($ask); ?>"><?php esc_html_e('Ask Question', 'storzen'); ?></a></li>
		</ul>
<?php
		$this->szp_pd_fragment_close();
	}
}

/**
 * Realtime visitor line (shop-details.html .realtime).
 */
class Storzen_Product_Realtime_Visitor_Widget extends Widget_Base
{
	use Storzen_Product_Part_Helpers;

	public function get_name()
	{
		return 'storzen-product-realtime-visitor';
	}

	public function get_title()
	{
		return esc_html__('Realtime Visitor', 'storzen');
	}

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

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

	protected function register_controls()
	{
		$this->start_controls_section(
			'section_text',
			array(
				'label' => esc_html__('Message', 'storzen'),
			)
		);
		$this->add_control(
			'message_tpl',
			array(
				'label'       => esc_html__('Text', 'storzen'),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__('Real time [count] person visit right now', 'storzen'),
				'description' => esc_html__('Use [count] for the visitor number.', 'storzen'),
			)
		);
		$this->add_control(
			'count_base',
			array(
				'label'   => esc_html__('Visitor number (0 = auto from product ID)', 'storzen'),
				'type'    => Controls_Manager::NUMBER,
				'min'     => 0,
				'max'     => 99999,
				'default' => 0,
			)
		);
		$this->end_controls_section();
	}

	protected function render()
	{
		if ($this->szp_maybe_placeholder(esc_html__('Realtime Visitor', 'storzen'))) {
			return;
		}
		if (! $this->szp_get_loop_product()) {
			return;
		}
		$settings = $this->get_settings_for_display();
		$tpl      = isset($settings['message_tpl']) ? (string) $settings['message_tpl'] : '';
		if ($tpl === '') {
			$tpl = esc_html__('Real time [count] person visit right now', 'storzen');
		}
		$base = isset($settings['count_base']) ? (int) $settings['count_base'] : 0;
		$pid  = (int) get_the_ID();
		$n    = $base > 0 ? $base : (180 + ($pid % 120));
		$parts = explode('[count]', $tpl, 2);
		$this->szp_pd_fragment_open();
		echo '<div class="realtime mb-20 szp-realtime">';
		echo esc_html($parts[0]);
		echo '<span>' . esc_html((string) $n) . '</span>';
		if (isset($parts[1])) {
			echo esc_html($parts[1]);
		}
		echo '</div>';
		$this->szp_pd_fragment_close();
	}
}
