<?php
namespace Sifency\Traits;

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

use Elementor\Controls_Manager;

trait Sifency_Products_Controls {

	protected function add_sifency_products_controls( $args = array() ) {
		$this->start_controls_section( 'section_query', array( 'label' => __( 'Query', 'sifency-addons' ) ) );

		$this->add_control(
			'source',
			array(
				'label'   => __( 'Source', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'latest',
				'options' => array(
					'latest'           => __( 'Latest Products', 'sifency-addons' ),
					'sale'             => __( 'On Sale', 'sifency-addons' ),
					'featured'         => __( 'Featured', 'sifency-addons' ),
					'related_products' => __( 'Related', 'sifency-addons' ),
					'manual_selection' => __( 'Manual Selection', 'sifency-addons' ),
				),
			)
		);

		$this->add_control(
			'manual_products',
			array(
				'label'       => __( 'Select Products', 'sifency-addons' ),
				'type'        => Controls_Manager::SELECT2,
				'multiple'    => true,
				'label_block' => true,
				'options'     => $this->get_all_products_list(),
				'condition'   => array( 'source' => 'manual_selection' ),
			)
		);

		$this->add_control(
			'include_categories',
			array(
				'label'       => __( 'Include Categories', 'sifency-addons' ),
				'type'        => Controls_Manager::SELECT2,
				'multiple'    => true,
				'label_block' => true,
				'options'     => $this->_get_tax_terms( 'product_cat' ),
				'condition'   => array( 'source!' => 'manual_selection' ),
			)
		);

		$this->add_control(
			'exclude_categories',
			array(
				'label'       => __( 'Exclude Categories', 'sifency-addons' ),
				'type'        => Controls_Manager::SELECT2,
				'multiple'    => true,
				'label_block' => true,
				'options'     => $this->_get_tax_terms( 'product_cat' ),
				'condition'   => array( 'source!' => 'manual_selection' ),
			)
		);

		$this->add_control(
			'posts_per_page',
			array(
				'label'   => __( 'Products per Page', 'sifency-addons' ),
				'type'    => Controls_Manager::NUMBER,
				'default' => 8,
			)
		);

		$this->add_control(
			'orderby',
			array(
				'label'   => __( 'Order By', 'sifency-addons' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'date',
				'options' => array(
					'date'       => __( 'Date', 'sifency-addons' ),
					'title'      => __( 'Title', 'sifency-addons' ),
					'price'      => __( 'Price', 'sifency-addons' ),
					'rand'       => __( 'Random', 'sifency-addons' ),
					'menu_order' => __( 'Menu Order', 'sifency-addons' ),
				),
			)
		);

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

		$this->end_controls_section();

		// --- Layout Section ---
		$this->start_controls_section( 'section_layout', array( 'label' => __( 'Layout', 'sifency-addons' ) ) );

		$this->add_responsive_control(
			'columns',
			array(
				'label'           => __( 'Columns', 'sifency-addons' ),
				'type'            => Controls_Manager::SELECT,
				'options'         => array(
					'1' => '1',
					'2' => '2',
					'3' => '3',
					'4' => '4',
					'5' => '5',
					'6' => '6',
				),
				'desktop_default' => '4',
				'tablet_default'  => '2',
				'mobile_default'  => '1',
				'selectors'       => array(
					'{{WRAPPER}} .sifency-products-grid ul.products' => 'grid-template-columns: repeat({{VALUE}}, 1fr); display: grid;',
				),
			)
		);

		$this->add_responsive_control(
			'column_gap',
			array(
				'label'      => __( 'Gap', 'sifency-addons' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'em', '%' ),
				'range'      => array(
					'px' => array(
						'min' => 0,
						'max' => 100,
					),
				),
				'default'    => array(
					'unit' => 'px',
					'size' => 20,
				),
				'selectors'  => array(
					'{{WRAPPER}} .sifency-products-grid ul.products' => 'gap: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'content_align',
			array(
				'label'     => __( 'Content Align', 'sifency-addons' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'left'   => array(
						'title' => __( 'Left', 'sifency-addons' ),
						'icon'  => 'eicon-text-align-left',
					),
					'center' => array(
						'title' => __( 'Center', 'sifency-addons' ),
						'icon'  => 'eicon-text-align-center',
					),
					'right'  => array(
						'title' => __( 'Right', 'sifency-addons' ),
						'icon'  => 'eicon-text-align-right',
					),
				),
				'selectors' => array( '{{WRAPPER}} ul.products li.product' => 'text-align: {{VALUE}};' ),
			)
		);
		$this->end_controls_section();

		// --- Rating Style Section ---
		$this->start_controls_section(
			'section_rating_style',
			array(
				'label' => __( 'Rating', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'show_rating',
			array(
				'label'   => __( 'Show Rating', 'sifency-addons' ),
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);

		$this->add_control(
			'star_color',
			array(
				'label'     => __( 'Star Color', 'sifency-addons' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array( '{{WRAPPER}} .star-rating span::before' => 'color: {{VALUE}} !important;' ),
				'condition' => array( 'show_rating' => 'yes' ),
			)
		);

		$this->add_responsive_control(
			'star_size',
			array(
				'label'     => __( 'Star Size', 'sifency-addons' ),
				'type'      => Controls_Manager::SLIDER,
				'selectors' => array( '{{WRAPPER}} .star-rating' => 'font-size: {{SIZE}}{{UNIT}};' ),
				'condition' => array( 'show_rating' => 'yes' ),
			)
		);

		$this->end_controls_section();

		$this->start_controls_section(
			'section_badge_settings',
			array(
				'label' => __( 'Sale Badge', 'sifency-addons' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);
		$this->add_control(
			'show_badge',
			array(
				'label'   => __( 'Show Sale Badge', 'sifency-addons' ),
				'type'    => Controls_Manager::SWITCHER,
				'default' => 'yes',
			)
		);
		$this->end_controls_section();
	}

	/**
	 * Helper: Get Taxonomy Terms
	 */
	protected function _get_tax_terms( $taxonomy ) {
		if ( ! taxonomy_exists( $taxonomy ) ) {
			return array();
		}
		$terms   = get_terms(
			array(
				'taxonomy'   => $taxonomy,
				'hide_empty' => false,
			)
		);
		$options = array();
		if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
			foreach ( $terms as $term ) {
				$options[ $term->slug ] = $term->name;
			}
		}
		return $options;
	}

	/**
	 * Helper: Get All Products for Manual Selection
	 */
	protected function get_all_products_list() {
		$args    = array(
			'post_type'      => 'product',
			'posts_per_page' => -1,
		);
		$posts   = get_posts( $args );
		$options = array();
		foreach ( $posts as $post ) {
			$options[ $post->ID ] = $post->post_title;
		}
		return $options;
	}

	/**
	 * Helper: Generate WP_Query Arguments based on settings
	 */
	protected function get_sifency_product_query_args( $settings ) {
		$args = array(
			'post_type'      => 'product',
			'post_status'    => 'publish',
			'posts_per_page' => $settings['posts_per_page'] ?? 6,
			'orderby'        => $settings['orderby'] ?? 'date',
			'order'          => $settings['order'] ?? 'DESC',
			'paged'          => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
		);

		if ( 'manual_selection' === $settings['source'] ) {
			if ( ! empty( $settings['manual_products'] ) ) {
				$args['post__in'] = $settings['manual_products'];
				$args['orderby']  = 'post__in';
			}
		} elseif ( 'sale' === $settings['source'] ) {
			$args['post__in'] = array_merge( array( 0 ), wc_get_product_ids_on_sale() );
		} elseif ( 'featured' === $settings['source'] ) {
			$args['tax_query'] = array(
				array(
					'taxonomy' => 'product_visibility',
					'field'    => 'name',
					'terms'    => 'featured',
					'operator' => 'IN',
				),
			);
		} elseif ( 'related_products' === $settings['source'] ) {
			global $product;
			if ( $product && is_a( $product, 'WC_Product' ) ) {
				$related_ids = wc_get_related_products( $product->get_id(), $settings['posts_per_page'] ?? 6 );
				if ( ! empty( $related_ids ) ) {
					$args['post__in'] = $related_ids;
					$args['orderby']  = 'post__in';
				} else {
					$args['post__in'] = array( 0 );
				}
			} else {
				$args['post__in'] = array( 0 );
			}
		}

		if ( 'manual_selection' !== $settings['source'] && 'related_products' !== $settings['source'] ) {
			$tax_query = array();

			if ( ! empty( $settings['include_categories'] ) ) {
				$tax_query[] = array(
					'taxonomy' => 'product_cat',
					'field'    => 'slug',
					'terms'    => $settings['include_categories'],
					'operator' => 'IN',
				);
			}

			if ( ! empty( $settings['exclude_categories'] ) ) {
				$tax_query[] = array(
					'taxonomy' => 'product_cat',
					'field'    => 'slug',
					'terms'    => $settings['exclude_categories'],
					'operator' => 'NOT IN',
				);
			}

			if ( ! empty( $tax_query ) ) {
				$tax_query['relation'] = 'AND';
				$args['tax_query']     = isset( $args['tax_query'] ) ? array_merge( $args['tax_query'], $tax_query ) : $tax_query;
			}
		}

		return $args;
	}
}
