<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Image_Size;
use Elementor\Repeater;
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_Icon_Style_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Team_Controls;
use Sifency\Traits\Sifency_Addons_Image_Style_Controls;
use Sifency\Traits\Sifency_Addons_Section_Header;
use Sifency\Traits\Sifency_Addons_Help_Controls;
class Sifency_Addons_Widget_Team 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_Addons_Icon_Style_Controls;
	use Sifency_Team_Controls;
	use Sifency_Addons_Image_Style_Controls;
	use Sifency_Addons_Section_Header;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-addons-team',
			'title'          => 'Sifency Team',
			'icon'           => 'eicon-person',
			'category'       => 'sifency-advance-widgets',
			'keywords'       => array( 'team', 'members', 'staff', 'carousel' ),
			'style_depends'  => array( 'sifency-typo-style', 'swiper', 'sifency-frontend-style', 'sifency-team-style', 'sifency-icon' ),
			'script_depends' => array( 'swiper', 'sifency-frontend-script', 'sifency-carousel-handler' ),
		);}
	protected function register_controls() {
		$this->add_sifency_addons_section_header_controls();
		$carousel_condition = array(
			'condition' => array( 'display_type' => 'carousel' ),
		);
		$this->add_sifency_team_controls();
		$this->add_sifency_addons_slider_controls( $carousel_condition );
		$this->add_sifency_addons_help_controls();
		$this->add_sifency_addons_item_style_controls(
			array(
				'label'    => esc_html__( 'Item Wrapper', 'sifency-addons' ),
				'selector' => '.sifency-team-item',
			)
		);
		$this->add_sifency_addons_item_style_controls(
			array(
				'prefix'   => 'content_wrapper_style_',
				'label'    => esc_html__( 'Item Content Wrapper', 'sifency-addons' ),
				'selector' => '.sifency-team-item__content',
			)
		);
		$this->add_sifency_addons_item_style_controls(
			array(
				'prefix'   => 'icon_wrapper_style_',
				'label'    => esc_html__( 'Icon Box Wrapper', 'sifency-addons' ),
				'selector' => '.sifency-team-item__social-overlay',
				'exclude'  => array( 'tabs', 'transition' ),
			)
		);
		$this->add_sifency_addons_image_style_controls(
			array(
				'selector'  => '.sifency-team-item__image img',
				'selectors' => array(
					'image'     => '.sifency-team-item__image img',
					'container' => '.sifency-team-item__image img',
					'dimension' => '.sifency-team-item__image img',
				),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'   => 'heading_style',
				'label'    => 'Member Name',
				'selector' => '.sifency-heading-style',
				'exclude'  => array( 'bg', 'radius' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'     => 'content_style',
				'label'      => 'Member Designation',
				'selector'   => '.sifency-content-style',
				'exclude'    => array( 'tabs', 'transition', 'bg', 'radius', 'border', 'stroke', 'shadow' ),
				'color_only' => true,
			)
		);
		$this->add_sifency_addons_icon_style_controls(
			array(
				'selector' => '.sifency-icon-style',
			)
		);
		Sifency_Addons_Parity_Style_Controls::register( $this );
		$this->add_Sifency_Addons_Animation_Controls();
	}

	protected function render() {
		$settings          = $this->get_settings_for_display();
		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );

		$wrapper_classes = array(
			'sifency-team-wrapper',
			'sifency-team-layout-' . $settings['layout_style'],
		);

		$this->add_render_attribute( 'wrapper', 'class', $wrapper_classes );

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

		$is_carousel = ( 'carousel' === $settings['display_type'] );

		if ( $is_carousel ) {
			$this->add_render_attribute( 'layout_container', 'class', array( 'sifency-carousel-wrapper', 'swiper-container' ) );
			$slide_count = ( 'posts' === $settings['source'] )
				? ( new \WP_Query( array_merge( $this->get_sifency_addons_query_args() ?? array(), array( 'post_type' => $settings['query_post_type'] ?? 'team' ) ) ) )->post_count
				: count( $settings['team_list'] ?? array() );

			$slider_options = $this->get_sifency_swiper_options( $settings, $slide_count );
			$this->add_render_attribute( 'layout_container', 'data-swiper-options', wp_json_encode( $slider_options ) );
		} else {
			$this->add_render_attribute( 'layout_container', 'class', 'sifency-team-grid' );
		}

		?>
		<?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( 'layout_container' ) ); ?>>
				<?php
				if ( $is_carousel ) {
					echo '<div class="swiper-wrapper">'; }
				?>

				<?php
				if ( 'posts' === $settings['source'] ) {
					$this->render_posts_content( $settings, $animation_manager );
				} else {
					$this->render_custom_content( $settings, $animation_manager );
				}
				?>
				<?php
				if ( $is_carousel ) {
					echo '</div>'; }
				?>
				
				<?php
				if ( $is_carousel ) {
					$this->render_sifency_addons_slider_nav( $settings );
					$this->render_sifency_addons_slider_pagination( $settings );
				}
				?>
			</div>
		</div>
		<?php
	}

	private function render_custom_content( $settings, Sifency_Addons_Animation_Manager $animation_manager ) {
		if ( empty( $settings['team_list'] ) ) {
			return; }
		foreach ( $settings['team_list'] as $index => $item ) {
			$oi           = $index + 1;
			$parity_class = ( $oi % 2 !== 0 ) ? 'odd-item' : 'even-item';
			$this->render_team_member( $item, $parity_class, $settings, $animation_manager );
		}
	}

	private function render_posts_content( $settings, Sifency_Addons_Animation_Manager $animation_manager ) {
		$query_args              = method_exists( $this, 'get_sifency_addons_query_args' ) ? $this->get_sifency_addons_query_args() : array();
		$query_args['post_type'] = $settings['query_post_type'] ?? 'team';
		$query                   = new \WP_Query( $query_args );

		if ( ! $query->have_posts() ) {
			return; }

		while ( $query->have_posts() ) :
			$query->the_post();
			$oi           = $query->current_post + 1;
			$parity_class = ( $oi % 2 !== 0 ) ? 'odd-item' : 'even-item';

			$position = function_exists( 'sifency_get_field' ) ? sifency_get_field( 'member_position' ) : '';

			$social_profiles = function_exists( 'sifency_get_field' ) ? sifency_get_field( 'member_social_icons' ) : array();

			if ( empty( $social_profiles ) ) {
				if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
					$social_profiles = array(
						array(
							'member_icon'        => 'fab fa-facebook-f',
							'member_social_link' => '#',
						),
						array(
							'member_icon'        => 'fab fa-twitter',
							'member_social_link' => '#',
						),
						array(
							'member_icon'        => 'fab fa-instagram',
							'member_social_link' => '#',
						),
						array(
							'member_icon'        => 'fab fa-linkedin-in',
							'member_social_link' => '#',
						),
					);
				} else {
					$social_profiles = array();
				}
			}

			$formatted_socials = array();
			if ( is_array( $social_profiles ) ) {
				foreach ( $social_profiles as $profile ) {
					$icon_class = $profile['member_icon'] ?? '';
					$social_url = $profile['member_social_link'] ?? '';

					$formatted_socials[] = array(
						'_id'         => wp_rand( 1000, 9999 ),
						'social_icon' => $icon_class,
						'link'        => array(
							'url'         => $social_url,
							'is_external' => 'on',
							'nofollow'    => 'on',
						),
					);
				}
			}

			$member_data = array(
				'name'         => get_the_title(),
				'image'        => array( 'id' => get_post_thumbnail_id() ),
				'position'     => $position,
				'link'         => array( 'url' => get_permalink() ),
				'social_icons' => $formatted_socials,
			);

			$this->render_team_member( $member_data, $parity_class, $settings, $animation_manager );
		endwhile;
		$this->render_sifency_addons_numeric_pagination( $query, $settings, 'query_pagination_' );
		wp_reset_postdata();
	}

	private function render_team_member( $member, $parity_class, $settings, Sifency_Addons_Animation_Manager $animation_manager ) {
		$is_carousel = ( 'carousel' === $settings['display_type'] );
		$tag         = $is_carousel ? 'div' : 'div';
		$classes     = $is_carousel ? array( 'swiper-slide' ) : array( 'sifency-team-item', $parity_class );
		$attrs       = $animation_manager->get_item_attributes( $classes );

		$link_key = 'member_link_' . ( $member['image']['id'] ?? wp_rand( 1000, 9999 ) );
		$this->remove_render_attribute( $link_key );

		$has_socials = ! empty( $member['social_icons'] );
		?>
		<<?php echo esc_html( $tag ); ?> <?php echo wp_kses_post( $attrs ); ?>>
			<?php if ( $is_carousel ) : ?>
				<div class="sifency-team-item <?php echo esc_attr( $parity_class ); ?>">
			<?php endif; ?>

				<!-- Image Wrapper -->
				<div class="sifency-team-item__image">
					<?php
					if ( ! empty( $member['link']['url'] ) ) {
						$this->add_link_attributes( $link_key, $member['link'] );
						echo '<a ' . wp_kses_post( $this->get_render_attribute_string( $link_key ) ) . '>';
					}
					echo \Elementor\Group_Control_Image_Size::get_attachment_image_html( $member, 'thumbnail', 'image' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor already escapes content internally.
					if ( ! empty( $member['link']['url'] ) ) {
						echo '</a>'; }
					?>
					
					<!-- For Styles that overlay social icons on image -->
					<?php if ( $has_socials && in_array( $settings['layout_style'], array( 'style-1', 'style-4', 'style-5', 'style-8', 'style-9', 'style-10', 'style-15', 'style-18', 'style-19', 'style-20' ) ) ) : ?>
						<div class="sifency-team-item__social-overlay">
							<?php $this->render_social_icons( $member['social_icons'] ); ?>
						</div>
					<?php endif; ?>
				</div>

				<div class="sifency-team-item__content">
					<h3 class="sifency-team-item__name">
						<?php if ( ! empty( $member['link']['url'] ) ) : ?>
							<a <?php echo wp_kses_post( $this->get_render_attribute_string( $link_key ) ); ?> class="sifency-heading-style">
								<?php echo esc_html( $member['name'] ); ?>
							</a>
						<?php else : ?>
							<span class="sifency-heading-style"><?php echo esc_html( $member['name'] ); ?></span>
						<?php endif; ?>
					</h3>
					
					<?php if ( ! empty( $member['position'] ) ) : ?>
						<div class="sifency-team-item__position sifency-content-style"><?php echo esc_html( $member['position'] ); ?></div>
					<?php endif; ?>
					
					<?php if ( $has_socials && in_array( $settings['layout_style'], array( 'style-2', 'style-3', 'style-6', 'style-7', 'style-11', 'style-12', 'style-13', 'style-14', 'style-16', 'style-17' ) ) ) : ?>
						<div class="sifency-team-item__social-content">
							<?php $this->render_social_icons( $member['social_icons'] ); ?>
						</div>
					<?php endif; ?>

				</div>

			<?php if ( $is_carousel ) : ?>
				</div>
			<?php endif; ?>
		</<?php echo esc_html( $tag ); ?>>
		<?php
	}

	private function render_social_icons( $icons ) {
		foreach ( $icons as $icon_item ) :
			$icon_data       = $icon_item['social_icon'] ?? null;
			$social_link_key = 'social_link_' . ( $icon_item['_id'] ?? wp_rand() );
			$this->remove_render_attribute( $social_link_key );

			if ( ! empty( $icon_item['link']['url'] ) ) {
				$this->add_link_attributes( $social_link_key, $icon_item['link'] );
			} else {
				$this->add_render_attribute( $social_link_key, 'href', '#' );
			}

			echo '<a ' . wp_kses_post( $this->get_render_attribute_string( $social_link_key ) ) . ' class="sifency-icon-style">';
			if ( is_array( $icon_data ) && ! empty( $icon_data['value'] ) ) {
				\Elementor\Icons_Manager::render_icon( $icon_data, array( 'aria-hidden' => 'true' ) );
			} elseif ( ! empty( $icon_data ) && is_string( $icon_data ) ) {
				echo '<i class="' . esc_attr( $icon_data ) . '" aria-hidden="true"></i>';
			}
			echo '</a>';
		endforeach;

		$social_profiles = sifency_get_field( 'member_social_icons' );
		if ( empty( $social_profiles ) ) {
			if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				$social_profiles = array(
					array(
						'member_icon'        => 'fab fa-facebook-f',
						'member_social_link' => '#',
					),
					array(
						'member_icon'        => 'fab fa-twitter',
						'member_social_link' => '#',
					),
					array(
						'member_icon'        => 'fab fa-instagram',
						'member_social_link' => '#',
					),
					array(
						'member_icon'        => 'fab fa-linkedin-in',
						'member_social_link' => '#',
					),
				);
			} else {
				return;
			}
		}
		$job_title = sifency_get_field( 'member_position' );
	}
}
