<?php
if ( ! defined('ABSPATH') ) {
    exit; // Exit if accessed directly.
}
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Utils;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Background;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use \Sifency\Traits\Sifency_Arg_Controls;
use \Sifency\Traits\Sifency_Animation_Controls;
use \Sifency\Traits\Sifency_Elementor_Parity_Controls;
use Sifency\Traits\Sifency_Core_Text_Style;

use Sifency\Traits\Sifency_Item_Style_Controls;
use Sifency\Traits\Sifency_Addons_Slider_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Testimonial_Controls;

class Sifency_Addons_Widget_Testimonials extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Arg_Controls;
    use Sifency_Core_Text_Style;

    use Sifency_Item_Style_Controls;
	use Sifency_Addons_Slider_Controls;
	use Sifency_Testimonial_Controls;

	public function get_name() {
		return 'sifency-addons-testimonials';
	}
	public function get_title() {
		return esc_html__('Sifency Testimonials', 'sifency-addons');
	}
	public function get_icon() {
		return 'eicon-testimonial-carousel';
	}
	public function get_categories() {
		return [ 'sifency-advance-widgets' ];
	}
	public function get_keywords() {
		return [ 'testimonial', 'review', 'feedback', 'client', 'sifency' ];
	}
    public function get_script_depends() {
        return $this->get_carousel_script_depends();
    }
    public function get_style_depends() {
        return [ 'sifency-typo-style' , 'swiper', 'sifency-swiper-style', 'sifency-frontend-style', 'sifency-testimonials-style', 'sifency-icon' ];
    }
	
	protected function register_controls() {
		$carousel_condition = [
            'condition' => [
                'display_type' => 'carousel'
            ]
        ];
        $this->add_sifency_testimonial_controls();
		$this->add_sifency_carousel_controls($carousel_condition);
        $this->add_sifency_item_style_controls();
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'heading_style',
            'label'    => 'Name',
            'selector' => '.sifency-heading-style',
            'target_children' => false,
        ]);
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'content_style',
            'label'    => 'Review Content',
            'selector' => '.sifency-content-style',
            'target_children' => true,
        ]);
        $this->add_sifency_advanced_text_style([
            'prefix'   => 'meta_style',
            'label'    => 'Designation/Location',
            'selector' => '.sifency-meta-style',
            'target_children' => false,
        ]);
		Sifency_Elementor_Parity_Controls::register( $this );
		$this->add_sifency_animation_controls();
	}


	protected function render() {
		$settings = $this->get_settings_for_display();
		$is_carousel = ('carousel' === $settings['display_type']);
		$animation_manager = new Sifency_Animation_Manager($settings);
		$items = $this->_get_testimonial_items();

		if (empty($items)) {
			echo esc_html__('No testimonials found.', 'sifency-addons');
			return;
		}

		$this->add_render_attribute( 'wrapper', 'class', 'sifency-addons-testimonials-wrapper' );
		$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));
		}
		?>
		<div <?php echo wp_kses_post ( $this->get_render_attribute_string('wrapper') ); ?>>
			<div <?php  ?> <?php echo wp_kses_post ( $this->get_render_attribute_string($container_key) ); ?>>
				<div class="<?php echo esc_attr($items_wrapper_class); ?><?php  ?>">
					<?php
					foreach ($items as $index => $item) {
						$this->render_single_testimonial_item( $item, $index, $settings, $animation_manager );
					}
					?>
				</div>
				<?php if ($is_carousel) : ?>
					<?php if ('yes' === ($settings['show_arrows'] ?? 'yes')) : ?>
						<div class="sifency-slider-nav-container">
						<div class="swiper-button-prev sifency-slider-nav-arrow sifency-slider-nav-prev"><i class="icon-left"></i></div>
						<div class="swiper-button-next sifency-slider-nav-arrow sifency-slider-nav-next"><i class="icon-right"></i></div>
						</div>
					<?php endif; ?>
					<?php if (!empty($settings['show_pagination'])) : ?>
						<div class="swiper-pagination"></div>
					<?php endif; ?>
				<?php endif; ?>
			</div>
		</div>
		<?php
	}

	protected function render_single_testimonial_item( $item, $index, $settings, Sifency_Animation_Manager $animation_manager ) {
		$is_carousel = ( 'carousel' === $settings['display_type'] );
		$current_position = $index + 1;
		$parity_class = 'odd-item';
		$parity_pattern = $settings['parity_pattern'] ?? 'standard';

		switch ($parity_pattern) {
			case 'every_third':
				if ($current_position % 3 === 0) {
					$parity_class = 'even-item';
				}
				break;
			case 'custom':
				$custom_positions = [];
				if (!empty($settings['custom_even_positions'])) {
					$custom_positions = array_map('intval', explode(',', $settings['custom_even_positions']));
				}
				if (in_array($current_position, $custom_positions, true)) {
					$parity_class = 'even-item';
				}
				break;
			case 'standard':
			default:
				if ($current_position % 2 === 0) {
					$parity_class = 'even-item';
				}
				break;
		}

		$item_classes = $is_carousel ? ['swiper-slide sifency-testimonial-item'] : ['sifency-testimonial-item sifency-item-style'];
		$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 ( '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'], '');
						// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo wpautop( wp_kses_post( $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 {
						// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo wpautop( wp_kses_post( $item['content'] ) );
					}
					?>
				</div>
				<div class="sifency-addons-testimonial-author">
					<?php 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'] ); ?>" />
						</div>
					<?php endif; ?>
					<div class="sifency-addons-testimonial-author-details">
						<h4 class="sifency-addons-testimonial-name sifency-heading-style"><?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 sifency-meta-style">
								<?php if ($show_pos) : ?><span class="sifency-addons-testimonial-position"><?php echo esc_html( $item['position'] ); ?></span><?php endif; ?>
								<?php if ($show_pos && $show_com) : ?><span class="sifency-meta-separator">, </span><?php endif; ?>
								<?php if ($show_com) : ?><span class="sifency-addons-testimonial-company"><?php echo esc_html( $item['company'] ); ?></span><?php endif; ?>
							</div>
						<?php endif; ?>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

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

		if ( 'post_type' === $settings['source'] ) {
		$query_args = method_exists($this, 'get_sifency_query_args') ? $this->get_sifency_query_args() : [];
		$query_args['post_type'] = $settings['query_post_type'] ?? 'team';
		$query = new \WP_Query( $query_args );

    if ( ! $query->have_posts() ) { return; }
			if ( $query->have_posts() ) {
				while ( $query->have_posts() ) {
					$query->the_post();
					$items[] = [ 'name' => get_the_title(), 'content' => get_the_content(), 'image' => [ 'url' => get_the_post_thumbnail_url( get_the_ID(), 'large' ) ], 'position' => has_excerpt() ? get_the_excerpt() : '', 'company' => '', 'rating' => '', 'permalink' => get_permalink() ];
				}
			}
			wp_reset_postdata();
		} else {
			if ( ! empty( $settings['testimonials'] ) ) {
				foreach ( $settings['testimonials'] as $testimonial ) {
					$items[] = [ '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
	}
}