<?php
/**
 * Widget Name: Product Categories
 * Description: Displays WooCommerce product categories as a customizable grid of
 *              cards (image, name, product count) linking to each category
 *              archive. Source all categories, the children of a parent or a hand
 *              picked set, with multiple attractive styles.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.3.0
 */

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

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Border;

/**
 * Class Captwiki_Woo_Product_Categories
 *
 * @since 1.3.0
 */
class Captwiki_Woo_Product_Categories extends Widget_Base {

	/**
	 * Get widget name.
	 *
	 * @since 1.3.0
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-woo-product-categories';
	}

	/**
	 * Get widget title.
	 *
	 * @since 1.3.0
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Product Categories', 'captain-widgets-kit' );
	}

	/**
	 * Get widget icon.
	 *
	 * @since 1.3.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-product-categories captwiki-el-logo';
	}

	/**
	 * Get widget categories.
	 *
	 * @since 1.3.0
	 * @return array
	 */
	public function get_categories(): array {
		return array( 'captwiki-woo-commerce' );
	}

	/**
	 * Get widget keywords.
	 *
	 * @since 1.3.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'woocommerce', 'woo', 'product', 'categories', 'taxonomy', 'terms', 'shop', 'captain-widgets-kit' );
	}

	/**
	 * Disable Elementor's default inner wrapper.
	 *
	 * @since 1.3.0
	 * @return bool
	 */
	public function has_widget_inner_wrapper(): bool {
		return ! \Elementor\Plugin::$instance->experiments->is_feature_active( 'e_optimized_markup' );
	}

	/**
	 * Available visual styles.
	 *
	 * @since 1.3.0
	 * @return array
	 */
	private function captwiki_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Card', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Overlay', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – List', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Build a list of product categories for the selectors.
	 *
	 * @since 1.3.0
	 * @return array
	 */
	private function captwiki_get_category_options(): array {

		$options = array();

		if ( ! taxonomy_exists( 'product_cat' ) ) {
			return $options;
		}

		$terms = get_terms(
			array(
				'taxonomy'   => 'product_cat',
				'hide_empty' => false,
				'number'     => 100,
			)
		);

		if ( is_wp_error( $terms ) ) {
			return $options;
		}

		foreach ( $terms as $term ) {
			$options[ $term->term_id ] = $term->name;
		}

		return $options;
	}

	/**
	 * Register controls.
	 *
	 * @since 1.3.0
	 */
	protected function register_controls(): void {
		$this->register_content_controls();
		$this->register_card_style_controls();
		$this->register_text_style_controls();
	}

	/**
	 * Content tab controls.
	 *
	 * @since 1.3.0
	 */
	private function register_content_controls(): void {

		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Categories', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'widget_style',
			array(
				'label'   => esc_html__( 'Style', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'style-1',
				'options' => $this->captwiki_style_options(),
			)
		);

		$this->add_control(
			'source',
			array(
				'label'   => esc_html__( 'Source', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'all',
				'options' => array(
					'all'      => esc_html__( 'All Categories', 'captain-widgets-kit' ),
					'parent'   => esc_html__( 'Children of…', 'captain-widgets-kit' ),
					'specific' => esc_html__( 'Specific Categories', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'parent_id',
			array(
				'label'     => esc_html__( 'Parent Category', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::SELECT2,
				'options'   => $this->captwiki_get_category_options(),
				'condition' => array( 'source' => 'parent' ),
			)
		);

		$this->add_control(
			'category_ids',
			array(
				'label'       => esc_html__( 'Categories', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::SELECT2,
				'label_block' => true,
				'multiple'    => true,
				'options'     => $this->captwiki_get_category_options(),
				'condition'   => array( 'source' => 'specific' ),
			)
		);

		$this->add_control(
			'limit',
			array(
				'label'       => esc_html__( 'Max Categories', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::NUMBER,
				'min'         => 0,
				'default'     => 8,
				'description' => esc_html__( '0 = no limit.', 'captain-widgets-kit' ),
			)
		);

		$this->add_control(
			'orderby',
			array(
				'label'   => esc_html__( 'Order By', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'name',
				'options' => array(
					'name'       => esc_html__( 'Name', 'captain-widgets-kit' ),
					'count'      => esc_html__( 'Product Count', 'captain-widgets-kit' ),
					'slug'       => esc_html__( 'Slug', 'captain-widgets-kit' ),
					'menu_order' => esc_html__( 'Custom Order', 'captain-widgets-kit' ),
				),
			)
		);

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

		$this->add_control(
			'hide_empty',
			array(
				'label'        => esc_html__( 'Hide Empty', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_responsive_control(
			'columns',
			array(
				'label'          => esc_html__( 'Columns', 'captain-widgets-kit' ),
				'type'           => Controls_Manager::SLIDER,
				'range'          => array( 'px' => array( 'min' => 1, 'max' => 6, 'step' => 1 ) ),
				'default'        => array( 'size' => 4 ),
				'tablet_default' => array( 'size' => 3 ),
				'mobile_default' => array( 'size' => 2 ),
				'selectors'      => array(
					'{{WRAPPER}} .captwiki-pcats__grid' => 'grid-template-columns: repeat({{SIZE}}, 1fr);',
				),
			)
		);

		$this->add_control(
			'elements_heading',
			array(
				'label'     => esc_html__( 'Elements', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::HEADING,
				'separator' => 'before',
			)
		);

		$this->add_control(
			'show_image',
			array(
				'label'        => esc_html__( 'Image', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'show_name',
			array(
				'label'        => esc_html__( 'Name', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'show_count',
			array(
				'label'        => esc_html__( 'Product Count', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'count_text',
			array(
				'label'       => esc_html__( 'Count Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( '{count} products', 'captain-widgets-kit' ),
				'label_block' => true,
				'description' => esc_html__( 'Use {count} for the number.', 'captain-widgets-kit' ),
				'condition'   => array( 'show_count' => 'yes' ),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Card style controls.
	 *
	 * @since 1.3.0
	 */
	private function register_card_style_controls(): void {

		$card_selector = '{{WRAPPER}} .captwiki-pcats__card';
		$img_selector  = '{{WRAPPER}} .captwiki-pcats__media img';

		$this->start_controls_section(
			'section_style_card',
			array(
				'label' => esc_html__( 'Card', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_responsive_control(
			'grid_gap',
			array(
				'label'      => esc_html__( 'Grid Gap', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array( 'px' => array( 'min' => 0, 'max' => 60, 'step' => 1 ) ),
				'default'    => array( 'size' => 20 ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-pcats__grid' => 'gap: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'card_bg',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					$card_selector => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'card_border',
				'selector' => $card_selector,
			)
		);

		$this->add_responsive_control(
			'card_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%' ),
				'selectors'  => array(
					$card_selector => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}}; overflow: hidden;',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'card_box_shadow',
				'selector' => $card_selector,
			)
		);

		$this->add_responsive_control(
			'image_height',
			array(
				'label'      => esc_html__( 'Image Height', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'vh' ),
				'range'      => array( 'px' => array( 'min' => 80, 'max' => 500, 'step' => 1 ) ),
				'selectors'  => array(
					$img_selector => 'height: {{SIZE}}{{UNIT}}; object-fit: cover;',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Name / count style controls.
	 *
	 * @since 1.3.0
	 */
	private function register_text_style_controls(): void {

		$name_selector  = '{{WRAPPER}} .captwiki-pcats__name';
		$count_selector = '{{WRAPPER}} .captwiki-pcats__count';

		$this->start_controls_section(
			'section_style_text',
			array(
				'label' => esc_html__( 'Name & Count', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'name_color',
			array(
				'label'     => esc_html__( 'Name Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					$name_selector . ', ' . $name_selector . ' a' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'name_typography',
				'selector' => $name_selector,
			)
		);

		$this->add_control(
			'count_color',
			array(
				'label'     => esc_html__( 'Count Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'separator' => 'before',
				'selectors' => array(
					$count_selector => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'count_typography',
				'selector' => $count_selector,
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Query the categories to display.
	 *
	 * @since 1.3.0
	 * @param array $settings Widget settings.
	 * @return array
	 */
	private function captwiki_query_terms( array $settings ): array {

		if ( ! taxonomy_exists( 'product_cat' ) ) {
			return array();
		}

		$args = array(
			'taxonomy'   => 'product_cat',
			'hide_empty' => ! empty( $settings['hide_empty'] ) && 'yes' === $settings['hide_empty'],
			'orderby'    => ! empty( $settings['orderby'] ) ? sanitize_key( $settings['orderby'] ) : 'name',
			'order'      => ! empty( $settings['order'] ) && 'DESC' === $settings['order'] ? 'DESC' : 'ASC',
		);

		$limit = isset( $settings['limit'] ) ? absint( $settings['limit'] ) : 0;
		if ( $limit > 0 ) {
			$args['number'] = $limit;
		}

		$source = ! empty( $settings['source'] ) ? $settings['source'] : 'all';

		if ( 'parent' === $source ) {
			$args['parent'] = ! empty( $settings['parent_id'] ) ? absint( $settings['parent_id'] ) : 0;
		} elseif ( 'specific' === $source && ! empty( $settings['category_ids'] ) ) {
			$args['include'] = array_map( 'absint', (array) $settings['category_ids'] );
			$args['orderby'] = 'include' === $args['orderby'] ? 'include' : $args['orderby'];
		}

		$terms = get_terms( $args );

		return is_wp_error( $terms ) ? array() : $terms;
	}

	/**
	 * Output an editor-only notice.
	 *
	 * @since 1.3.0
	 * @param string $message Notice text.
	 */
	private function captwiki_render_editor_notice( string $message ): void {

		if ( ! \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
			return;
		}

		echo '<div class="captwiki-pcats captwiki-pcats--notice"><p>' . esc_html( $message ) . '</p></div>';
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * @since 1.3.0
	 */
	protected function render(): void {

		if ( ! class_exists( 'WooCommerce' ) ) {
			$this->captwiki_render_editor_notice( esc_html__( 'WooCommerce is required for the Product Categories widget.', 'captain-widgets-kit' ) );
			return;
		}

		$settings = $this->get_settings_for_display();
		$terms    = $this->captwiki_query_terms( $settings );

		if ( empty( $terms ) ) {
			$this->captwiki_render_editor_notice( esc_html__( 'No product categories found for this selection.', 'captain-widgets-kit' ) );
			return;
		}

		$allowed_styles = array_keys( $this->captwiki_style_options() );
		$style          = ! empty( $settings['widget_style'] ) && in_array( $settings['widget_style'], $allowed_styles, true ) ? $settings['widget_style'] : 'style-1';

		wp_enqueue_style(
			'captwiki-woo-product-categories-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/woo-product-categories/captwiki-woo-product-categories-' . $style . '.css',
			array( 'captwiki-woo-product-categories' ),
			CAPTWIKI_VERSION
		);

		$show_image = ! empty( $settings['show_image'] ) && 'yes' === $settings['show_image'];
		$show_name  = ! empty( $settings['show_name'] ) && 'yes' === $settings['show_name'];
		$show_count = ! empty( $settings['show_count'] ) && 'yes' === $settings['show_count'];
		$count_tpl  = ! empty( $settings['count_text'] ) ? $settings['count_text'] : esc_html__( '{count} products', 'captain-widgets-kit' );

		$wrapper_classes = array(
			'captwiki-pcats',
			'captwiki-' . $style,
			'captwiki-widget-' . $this->get_id(),
		);

		echo '<div class="' . esc_attr( implode( ' ', $wrapper_classes ) ) . '">';
		echo '<div class="captwiki-pcats__grid">';

		foreach ( $terms as $term ) {

			$link = get_term_link( $term );
			if ( is_wp_error( $link ) ) {
				continue;
			}

			echo '<a class="captwiki-pcats__card" href="' . esc_url( $link ) . '">';

			if ( $show_image ) {
				$thumb_id  = get_term_meta( $term->term_id, 'thumbnail_id', true );
				$image_html = $thumb_id
					? wp_get_attachment_image( $thumb_id, 'woocommerce_thumbnail', false, array( 'alt' => $term->name ) )
					: '<img src="' . esc_url( wc_placeholder_img_src( 'woocommerce_thumbnail' ) ) . '" alt="' . esc_attr( $term->name ) . '" />';

				echo '<span class="captwiki-pcats__media">' . $image_html . '</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}

			if ( $show_name || $show_count ) {
				echo '<span class="captwiki-pcats__body">';

				if ( $show_name ) {
					echo '<span class="captwiki-pcats__name">' . esc_html( $term->name ) . '</span>';
				}

				if ( $show_count ) {
					echo '<span class="captwiki-pcats__count">' . esc_html( str_replace( '{count}', number_format_i18n( $term->count ), $count_tpl ) ) . '</span>';
				}

				echo '</span>';
			}

			echo '</a>';
		}

		echo '</div>'; // .captwiki-pcats__grid
		echo '</div>'; // .captwiki-pcats
	}
}
