<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Utils;
use Elementor\Icons_Manager;
use Sifency\Traits\Sifency_Addons_Query_Arg_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Parity_Style_Controls;
use Sifency\Traits\Sifency_Addons_Master_Typography;
use Sifency\Traits\Sifency_Addons_Item_Style_Controls;
use Sifency\Traits\Sifency_Addons_Slider_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Testimonial_Controls;
use Sifency\Traits\Sifency_Addons_Icon_Style_Controls;
use Sifency\Traits\Sifency_Addons_Image_Style_Controls;
use Sifency\Traits\Sifency_Addons_Section_Header;
use Sifency\Traits\Sifency_Addons_Custom_CSS_Controls;
use Sifency\Traits\Sifency_Addons_Help_Controls;

class Sifency_Addons_Widget_Testimonials extends Widget_Base {
	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Query_Arg_Controls;
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Item_Style_Controls;
	use Sifency_Addons_Slider_Controls;
	use Sifency_Testimonial_Controls;
	use Sifency_Addons_Icon_Style_Controls;
	use Sifency_Addons_Image_Style_Controls;
	use Sifency_Addons_Section_Header;
	use Sifency_Addons_Custom_CSS_Controls;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-addons-testimonials',
			'title'          => 'Sifency Testimonials',
			'icon'           => 'eicon-testimonial-carousel',
			'category'       => 'sifency-advance-widgets',
			'keywords'       => array( 'testimonial', 'review', 'feedback', 'client', 'sifency' ),
			'script_depends' => array( 'swiper', 'sifency-frontend-script', 'sifency-carousel-handler' ),
			'style_depends'  => array( 'sifency-typo-style', 'swiper', 'sifency-frontend-style', 'sifency-testimonials-style', 'sifency-icon', 'elementor-icons-fa-solid', 'elementor-icons-fa-regular' ),
		);}
	protected function register_controls() {
		$carousel_condition = array(
			'condition' => array(
				'display_type' => 'carousel',
			),
		);
		$this->add_sifency_testimonial_controls();
		$this->add_sifency_addons_slider_controls( $carousel_condition );
		$this->add_sifency_addons_help_controls();
		$this->add_sifency_addons_item_style_controls(
			array(
				'selector'     => '.sifency-addons-testimonial-item-inner',
				'label'        => esc_html__( 'Testimonial Item Wrapper', 'sifency-addons' ),
				'selector'     => '.sifency-testimonial-item',
				'show_opacity' => true,
			)
		);
		$this->add_sifency_addons_item_style_controls(
			array(
				'prefix'       => 'active_',
				'label'        => esc_html__( 'Active Slider', 'sifency-addons' ),
				'selector'     => '.swiper-slide.sifency-testimonial-item.swiper-slide-visible.swiper-slide-active',
				'show_opacity' => true,
				'condition'    => array( 'design_layout!' => 'overlap' ),
			)
		);
		$this->add_sifency_addons_item_style_controls(
			array(
				'prefix'    => 'overlap_active_',
				'label'     => esc_html__( 'Active Slider', 'sifency-addons' ),
				'selector'  => '.swiper-slide.sifency-testimonial-item.swiper-slide-visible.swiper-slide-active .sifency-addons-testimonial-item-inner',
				'condition' => array( 'design_layout' => 'overlap' ),
			)
		);
		$this->add_sifency_addons_item_style_controls(
			array(
				'prefix'          => 'main_body_wrapper_',
				'label'           => esc_html__( 'Content Wrapper', 'sifency-addons' ),
				'selector'        => '.sifency-testimonial-main-body',
				'hover_selector'  => '.sifency-bubble-arrow',
				'hover_tab_label' => esc_html__( 'Bubble Arrow', 'sifency-addons' ),
			)
		);
		$this->add_sifency_addons_item_style_controls(
			array(
				'prefix'    => 'author_wrapper_',
				'label'     => esc_html__( 'Author Wrapper', 'sifency-addons' ),
				'selector'  => '.sifency-addons-testimonial-author',
				'exclude'   => array( 'bg', 'radius', 'box_shadow', 'transition', 'tabs', 'padding', 'margin', 'dimensions' ),
				'condition' => array( 'design_layout' => 'overlap' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'          => 'sec_title_style_',
				'label'           => 'Title',
				'selector'        => '.sifency-heading-style',
				'target_children' => true,
				'show_max_width'  => true,
				'exclude'         => array( 'alignment', 'transition', 'tabs', 'bg', 'radius', 'border' ),
				'condition'       => array(
					'show_title' => 'yes',
					'title!'     => '',
				),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'          => 'content_style',
				'label'           => 'Review Content',
				'selector'        => '.sifency-content-style',
				'target_children' => array( 'p' ),
				'show_max_width'  => true,
				'exclude'         => array( 'alignment', 'transition', 'tabs' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'heading_style_',
				'label'      => 'Name',
				'selector'   => '.sifency-addons-testimonial-name',
				'color_only' => true,
				'exclude'    => array( 'transition', 'box_model', 'shadow', 'tabs', 'stroke' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'meta_style_',
				'label'      => 'Designation/Location',
				'selector'   => '.sifency-meta-style',
				'color_only' => true,
				'exclude'    => array( 'transition', 'box_model', 'shadow', 'tabs', 'stroke' ),
			)
		);
		$this->add_sifency_addons_icon_style_controls(
			array(
				'label'          => esc_html__( 'Quote Icon', 'sifency-addons' ),
				'hover_selector' => '.sifency-testimonial-item:hover .sifency-testimonial-quote-icon i, .sifency-testimonial-item:hover .sifency-testimonial-quote-icon svg',
				'selector'       => '.sifency-testimonial-quote-icon i, .sifency-testimonial-quote-icon svg',
				'condition'      => array( 'show_quote' => 'yes' ),
			)
		);
		$this->add_sifency_addons_image_style_controls(
			array(
				'prefix'    => 'author_image_style_',
				'label'     => 'Author Image',
				'selector'  => '.sifency-addons-testimonial-image img',
				'selectors' => array(
					'image'     => '.sifency-addons-testimonial-image img',
					'container' => '.sifency-addons-testimonial-image img',
				),
				'exclude'   => array( 'tabs', 'transition' ),
				'condition' => array( 'show_image' => 'yes' ),
			)
		);
		Sifency_Addons_Parity_Style_Controls::register( $this );
		$this->add_Sifency_Addons_Animation_Controls();
		$this->add_Sifency_Addons_Custom_CSS_Controls();
	}


	protected function render() {
		$settings = $this->get_settings_for_display();
		$this->sifency_addons_render_custom_css();
		$is_carousel       = ( 'carousel' === $settings['display_type'] );
		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );
		$items             = $this->_get_testimonial_items();
		if ( empty( $items ) ) {
			return;
		}

		$this->add_render_attribute( 'wrapper', 'class', 'sifency-addons-testimonials-wrapper' );
		$this->add_render_attribute( 'wrapper', 'class', 'layout-' . $settings['design_layout'] );

		$animation_attrs = $animation_manager->get_wrapper_attributes();
		if ( ! empty( $animation_attrs ) ) {
			preg_match( '/class="([^"]+)"/', $animation_attrs, $class_matches );
			if ( isset( $class_matches[1] ) ) {
				$this->add_render_attribute( 'wrapper', 'class', $class_matches[1] );
			}
		}

		$container_key       = 'layout_container';
		$items_wrapper_class = 'sifency-addons-testimonials-grid';

		if ( $is_carousel ) {
			$items_wrapper_class = 'swiper-wrapper';
			$this->add_render_attribute( $container_key, 'class', 'swiper-container sifency-carousel-wrapper' );
			$slider_options = $this->get_sifency_swiper_options( $settings, count( $items ) );
			$this->add_render_attribute( $container_key, 'data-swiper-options', wp_json_encode( $slider_options ) );
		}
		?>
		<?php $this->render_sifency_section_header_elements( $settings ); ?>
		<div <?php echo wp_kses_post( $this->get_render_attribute_string( 'wrapper' ) ); ?>>
			<?php $this->render_sifency_floating_count( $settings ); ?>
			<div <?php echo wp_kses_post( $this->get_render_attribute_string( $container_key ) ); ?>>
				<div class="<?php echo esc_attr( $items_wrapper_class ); ?>">
					<?php
					foreach ( $items as $index => $item ) {
						$this->render_single_testimonial_item( $item, $index, $settings, $animation_manager );
					}
					?>
				</div>
				<?php if ( $is_carousel ) : ?>
					<?php $this->render_sifency_addons_slider_nav( $settings ); ?>
				<?php endif; ?>
				<?php
				if ( 'posts' === $settings['source'] && ! $is_carousel ) {
					$query_args              = $this->get_sifency_addons_query_args();
					$query_args['post_type'] = $settings['query_post_type'] ?? 'testimonial';
					$query                   = new \WP_Query( $query_args );

					$this->render_sifency_addons_numeric_pagination( $query, $settings, 'query_pagination_' );
					wp_reset_postdata();
				}
				?>
			</div>
		</div>
		<?php
	}

	protected function render_single_testimonial_item( $item, $index, $settings, Sifency_Addons_Animation_Manager $animation_manager ) {
		$is_carousel      = ( 'carousel' === $settings['display_type'] );
		$current_position = $index + 1;

		$parity_class   = 'odd-item';
		$parity_pattern = $settings['parity_pattern'] ?? 'standard';
		if ( $parity_pattern === 'every_third' && $current_position % 3 === 0 ) {
			$parity_class = 'even-item';
		} elseif ( $parity_pattern === 'custom' && in_array( $current_position, array_map( 'intval', explode( ',', $settings['custom_even_positions'] ?? '' ) ) ) ) {
			$parity_class = 'even-item';
		} elseif ( $parity_pattern === 'standard' && $current_position % 2 === 0 ) {
			$parity_class = 'even-item';
		}

		$item_classes   = $is_carousel ? array( 'swiper-slide' ) : array();
		$item_classes[] = 'sifency-testimonial-item';
		$item_classes[] = 'sifency-layout-' . $settings['design_layout'];
		$item_classes[] = $parity_class;

		$item_attrs = $animation_manager->get_item_attributes( $item_classes );
		?>
		<div <?php echo wp_kses_post( $item_attrs ); ?>>
			<div class="sifency-addons-testimonial-item-inner">
				
				<?php if ( $settings['design_layout'] === 'overlap' ) : ?>
					<?php $this->render_author_image( $item, $settings ); ?>
				<?php endif; ?>

				<div class="sifency-testimonial-main-body">
					<?php
					if ( 'yes' === ( $settings['show_quote'] ?? 'no' ) ) {
						echo '<div class="sifency-testimonial-quote-icon">';
						Icons_Manager::render_icon( $settings['quote_icon'], array( 'aria-hidden' => 'true' ) );
						echo '</div>';
					}
					if ( ( 'yes' === ( $settings['show_title'] ?? 'yes' ) ) && ! empty( $settings['title'] ) ) {
						echo '<h3 class="testimonial-title sifency-heading-style">' . esc_html( $settings['title'] ) . '</h3>';
					}
					if ( 'yes' === ( $settings['show_rating'] ?? 'yes' ) && ! empty( $item['rating'] ) ) {
						$this->render_rating( $item['rating'] );
					}
					?>
					
					<div class="sifency-addons-testimonial-content sifency-content-style">
						<?php
						if ( 'excerpt' === $settings['content_length'] && ! empty( $settings['excerpt_length'] ) ) {
							$content = wp_trim_words( $item['content'], $settings['excerpt_length'], '' );
							echo wp_kses_post( wpautop( $content ) );
							if ( ! empty( $settings['read_more_text'] ) ) {
								printf( ' <a href="%s" class="sifency-read-more">%s</a>', esc_url( $item['permalink'] ), esc_html( $settings['read_more_text'] ) );
							}
						} else {
							echo wp_kses_post( wpautop( $item['content'] ) );
						}
						?>
					</div>

					<?php if ( $settings['design_layout'] === 'bubble' ) : ?>
						<div class="sifency-bubble-arrow"></div>
					<?php endif; ?>
				</div>

				<div class="sifency-addons-testimonial-author">
					<?php if ( $settings['design_layout'] !== 'overlap' ) : ?>
						<?php $this->render_author_image( $item, $settings ); ?>
					<?php endif; ?>
					
					<div class="sifency-addons-testimonial-author-details">
						<h4 class="sifency-addons-testimonial-name"><?php echo esc_html( $item['name'] ); ?></h4>
						<?php
						$show_pos = ( 'yes' === ( $settings['show_position'] ?? 'yes' ) && ! empty( $item['position'] ) );
						$show_com = ( 'yes' === ( $settings['show_company'] ?? 'yes' ) && ! empty( $item['company'] ) );
						if ( $show_pos || $show_com ) :
							?>
							<div class="sifency-addons-testimonial-meta">
								<?php
								if ( $show_pos ) :
									?>
									<span class="sifency-addons-testimonial-position sifency-meta-style"><?php echo esc_html( $item['position'] ); ?></span><?php endif; ?>
								<?php
								if ( $show_pos && $show_com ) :
									?>
									<span class="sifency-meta-separator sifency-meta-style">, </span><?php endif; ?>
								<?php
								if ( $show_com ) :
									?>
									<span class="sifency-addons-testimonial-company sifency-meta-style"><?php echo esc_html( $item['company'] ); ?></span><?php endif; ?>
							</div>
						<?php endif; ?>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	protected function render_author_image( $item, $settings ) {
		if ( 'yes' === ( $settings['show_image'] ?? 'yes' ) && ! empty( $item['image']['url'] ) ) :
			?>
			<div class="sifency-addons-testimonial-image">
				<img src="<?php echo esc_url( $item['image']['url'] ); ?>" alt="<?php echo esc_attr( $item['name'] ); ?>" loading="lazy" />
			</div>
			<?php
		endif;
	}

	private function _get_testimonial_items() {
		$settings = $this->get_settings_for_display();
		$items    = array();

		if ( 'posts' === $settings['source'] ) {

			$query_args              = $this->get_sifency_addons_query_args();
			$query_args['post_type'] = $settings['query_post_type'] ?? 'testimonial';
			$query                   = new \WP_Query( $query_args );
			if ( ! $query->have_posts() ) {
				return array();
			}

			while ( $query->have_posts() ) :
				$query->the_post();

				$content = sifency_has_field( 'testimonial_review_content' ) ? sifency_get_field( 'testimonial_review_content' ) : get_the_content();

				$image_id = sifency_get_field( 'testimonial_user_img' );
				if ( ! $image_id && has_post_thumbnail() ) {
					$image_id = get_post_thumbnail_id();
				}

				$items[] = array(
					'name'      => get_the_title(),
					'content'   => $content,
					'image'     => array(
						'id'  => $image_id,
						'url' => wp_get_attachment_image_url( $image_id, 'full' ),
					),
					'position'  => sifency_get_field( 'testimonial_position' ),
					'company'   => sifency_get_field( 'testimonial_company' ),
					'rating'    => '5',
					'permalink' => sifency_get_field( 'testimonial_link' ) ?: get_permalink(),
				);
			endwhile;

			wp_reset_postdata();

		} elseif ( ! empty( $settings['testimonials'] ) ) {
			foreach ( $settings['testimonials'] as $testimonial ) {
				$items[] = array(
					'name'      => $testimonial['name'],
					'content'   => $testimonial['content'],
					'image'     => $testimonial['image'],
					'position'  => $testimonial['position'],
					'company'   => $testimonial['company'],
					'rating'    => $testimonial['rating'],
					'permalink' => ! empty( $testimonial['link']['url'] ) ? esc_url( $testimonial['link']['url'] ) : '#',
				);
			}
		}
		return $items;
	}

	protected function render_rating( $rating ) {
		$rating = (int) $rating;
		if ( $rating < 1 || $rating > 5 ) {
			return; }
		?>
		<div class="sifency-addons-testimonial-rating">
			<?php
			for ( $i = 1; $i <= 5; $i++ ) {
				echo '<i class="' . ( $i <= $rating ? 'icon-star' : 'icon-star-empty' ) . '"></i>'; }
			?>
		</div>
		<?php
	}
}
