<?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_Button_Style_Controls;
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_Projects_Controls;
use Sifency\Traits\Sifency_Addons_Image_Style_Controls;
use Sifency\Traits\Sifency_Addons_Flex_Controls;
use Sifency\Traits\Sifency_Addons_Section_Header;
use Sifency\Traits\Sifency_Addons_Help_Controls;
use Sifency\Traits\Sifency_Addons_Custom_CSS_Controls;
use Sifency\Traits\Sifency_Addons_Filter_Controls;

class Sifency_Addons_Widget_Projects extends Widget_Base {
	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Query_Arg_Controls;
	use Sifency_Addons_Custom_CSS_Controls;
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Button_Style_Controls;
	use Sifency_Addons_Item_Style_Controls;
	use Sifency_Addons_Slider_Controls;
	use Sifency_Projects_Controls;
	use Sifency_Addons_Image_Style_Controls;
	use Sifency_Addons_Flex_Controls;
	use Sifency_Addons_Section_Header;
	use Sifency_Addons_Help_Controls;
	use Sifency_Addons_Filter_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'           => 'sifency-addons-projects',
			'title'          => 'Sifency Portfolio',
			'icon'           => 'eicon-gallery-grid',
			'category'       => 'sifency-advance-widgets',
			'keywords'       => array( 'portfolio', 'projects', 'gallery', 'grid', 'split', 'sifency' ),
			'style_depends'  => array( 'sifency-typo-style', 'sifency-frontend-style', 'sifency-portfolio-style', 'sifency-icon' ),
			'script_depends' => array( 'swiper', 'sifency-frontend-script', 'sifency-carousel-handler', 'sifency-projects-script' ),
		);}
	protected function register_controls() {
		$carousel_condition = array(
			'condition' => array(
				'display_type'  => 'carousel',
				'layout_style!' => 'style-3',
			),
		);
		$this->add_sifency_addons_section_header_controls();
		$this->add_sifency_projects_controls();
		$this->add_sifency_addons_slider_controls( $carousel_condition );
		$this->add_sifency_addons_filter_controls(
			array(
				'condition' => array(
					'source'       => 'posts',
					'display_type' => 'grid',
				),
			)
		);
		$this->add_sifency_addons_help_controls();
		$this->add_sifency_addons_item_style_controls(
			array(
				'label'    => esc_html__( 'Item Wrapper', 'sifency-addons' ),
				'selector' => '.sifency-portfolio-item',
			)
		);
		$this->add_sifency_addons_item_style_controls(
			array(
				'prefix'   => 'content_wrapper_',
				'label'    => esc_html__( 'Content Wrapper', 'sifency-addons' ),
				'selector' => '.sifency-portfolio-content',
				'exclude'  => array( 'tabs', 'transition' ),
			)
		);
		$this->add_sifency_addons_image_style_controls(
			array(
				'selector'  => '.sifency-portfolio-image img',
				'selectors' => array(
					'container'  => '.sifency-portfolio-image img,',
					'image'      => '.sifency-portfolio-image img',
					'dimensions' => '.sifency-portfolio-image img',
				),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'         => 'heading_style',
				'label'          => 'Project Heading',
				'selector'       => '.sifency-heading-style',
				'hover_selector' => '.sifency-portfolio-item:hover .sifency-heading-style',
				'show_max_width' => true,
				'exclude'        => array( 'bg' ),
			)
		);

		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'         => 'excerpt_style',
				'label'          => 'Project Excerpt',
				'selector'       => '.sifency-caption-style',
				'hover_selector' => '.sifency-portfolio-item:hover .sifency-caption-style',
				'condition'      => array( 'show_excerpt' => 'yes' ),
				'show_max_width' => true,
				'exclude'        => array( 'bg', 'radius', 'transition', 'border' ),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'         => 'content_style',
				'label'          => 'Project Category',
				'selector'       => '.sifency-content-style',
				'hover_selector' => '.sifency-portfolio-item:hover .sifency-content-style',
				'exclude'        => array( 'tabs', 'transition', 'shadow', 'stroke', 'bg', 'radius' ),
				'color_only'     => true,
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'         => 'count_style_',
				'label'          => 'Project Count',
				'selector'       => '.sifency-item-count',
				'condition'      => array( 'show_count' => 'yes' ),
				'hover_selector' => '.sifency-portfolio-item:hover .sifency-item-count',
				'exclude'        => array( 'transition' ),
			)
		);
		$this->add_Sifency_Addons_Button_Style_Controls(
			array(
				'selector'       => '.sifency-button-style',
				'section_label'  => 'Button Style',
				'condition'      => array( 'show_read_more' => 'yes' ),
				'hover_selector' => '.sifency-portfolio-item:hover .sifency-button-style',
			)
		);
		Sifency_Addons_Parity_Style_Controls::register( $this );
		$this->add_Sifency_Addons_Animation_Controls();
		$this->add_sifency_addons_custom_css_controls();
	}

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

		$wrapper_classes = array(
			'sifency-portfolio-wrapper',
			'sifency-portfolio-' . $settings['layout_style'],
		);
		$this->add_render_attribute( 'wrapper', 'data-sticky-enabled', $settings['enable_sticky_stack'] ?? 'no' );
		$this->add_render_attribute( 'wrapper', 'data-scale-density', $settings['sticky_scale_density']['size'] ?? 0.2 );
		$this->add_render_attribute( 'wrapper', 'data-opacity-density', $settings['sticky_opacity_density']['size'] ?? 0.3 );
		$wrapper_attrs = $animation_manager->get_wrapper_attributes( $wrapper_classes );

		$is_style_3  = ( $settings['layout_style'] === 'style-3' );
		$is_carousel = ( 'carousel' === $settings['display_type'] ) && ! $is_style_3;

		$query = null;
		if ( 'posts' === $settings['source'] ) {
			$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'] ?? 'portfolio';

			$paged               = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : ( ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1 );
			$query_args['paged'] = $paged;

			$query = new \WP_Query( $query_args );
		}

		if ( $is_carousel ) {
			$this->add_render_attribute( 'layout_container', 'class', array( 'swiper-container', 'sifency-carousel-wrapper' ) );

			$slide_count = ( $query ) ? $query->post_count : count( $settings['project_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', array( 'sifency-portfolio--grid', 'sifency-filter-container' ) );
		}

		?>
		<?php $this->render_sifency_section_header_elements( $settings ); ?>
		<div <?php echo wp_kses_post( $this->get_render_attribute_string( 'wrapper' ) ); ?> <?php echo wp_kses_post( $wrapper_attrs ); ?>>
			<?php $this->render_sifency_floating_count( $settings ); ?>
			<?php $this->render_sifency_addons_filter(); ?>
			<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'] ) {
					// Pass the already created $query to the content function
					$this->render_posts_content( $settings, $animation_manager, $query );
				} 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 );
				}
				?>
			</div>

			<?php
			// Show pagination only for posts source and grid layout
			if ( 'posts' === $settings['source'] && ! $is_carousel && $query ) {
				$this->render_sifency_addons_numeric_pagination( $query, $settings, 'query_pagination_' );
				wp_reset_postdata();
			}
			?>
		</div>
		<?php
	}

	private function render_item_inner( $settings, $data, $index ) {
		$layout_style = $settings['layout_style'];
		$link_url     = $data['link']['url'] ?? '';
		$has_image    = ! empty( $data['image_html'] );

		$count_html = '';
		if ( 'yes' === $settings['show_count'] ) {
			$count_html = '<span class="sifency-item-count">' . sprintf( '%02d', $index + 1 ) . '</span>';
		}

		$btn_icon_html = '';
		if ( ! empty( $settings['button_next_icon']['value'] ) ) {
			ob_start();
			Icons_Manager::render_icon( $settings['button_next_icon'], array( 'aria-hidden' => 'true' ) );
			$btn_icon_html = ob_get_clean();
		}

		if ( $layout_style === 'style-3' ) :
			?>
			
			<a href="<?php echo esc_url( $link_url ); ?>" class="sifency-list-link">
				<div class="sifency-list-left">
					<?php echo wp_kses_post( $count_html ); ?>
					<div class="title-excerpt">
					<h3 class="sifency-portfolio-title sifency-heading-style"><?php echo esc_html( $data['title'] ); ?></h3>
					<?php if ( ! empty( $data['excerpt'] ) && 'yes' === ( $settings['show_excerpt'] ?? 'yes' ) ) : ?>
						<div class="sifency-portfolio-excerpt sifency-caption-style">
							<?php echo esc_html( $data['excerpt'] ); ?>
						</div>
					<?php endif; ?>
					</div>

				</div>
				<div class="sifency-list-right">
					<?php if ( ( $settings['show_category'] ?? 'yes' ) === 'yes' ) : ?>
						<span class="sifency-portfolio-categories sifency-content-style">
							<?php echo esc_html( $data['category'] ); ?>
						</span>
					<?php endif; ?>
					<div class="sifency-button-style">
					<?php
					if ( ! empty( $settings['read_more_text'] ) ) {
						echo '<span>' . esc_html( $settings['read_more_text'] ) . '</span>';}
					?>
					<span><?php echo wp_kses_post( $btn_icon_html ); ?></span></div>
				</div>
			</a>
			
			<?php if ( $has_image ) : ?>
				<div class="sifency-hover-reveal-img">
					<?php echo wp_kses_post( $data['image_html'] ); ?>
				</div>
			<?php endif; ?>

		<?php else : ?>
			
			<?php if ( $has_image ) : ?>
				<div class="sifency-portfolio-image">
					<a href="<?php echo esc_url( $link_url ); ?>">
						<?php echo wp_kses_post( $data['image_html'] ); ?>
						<div class="sifency-image-overlay"></div>
					</a>
					<?php
					if ( in_array( $layout_style, array( 'style-2', 'style-5' ) ) ) {
						echo wp_kses_post( $count_html ); }
					?>
				</div>
			<?php endif; ?>

			<div class="sifency-portfolio-content">
				<?php
				if ( $layout_style === 'style-1' ) {
					echo wp_kses_post( $count_html ); }
				?>
				
				<div class="sifency-content-wrap">
					<?php if ( ! empty( $data['category'] ) && 'yes' === ( $settings['show_category'] ?? 'yes' ) ) : ?>
						<div class="sifency-portfolio-categories sifency-content-style"><?php echo esc_html( $data['category'] ); ?></div>
					<?php endif; ?>
					
					<?php if ( ! empty( $data['excerpt'] ) && 'yes' === ( $settings['show_excerpt'] ?? 'yes' ) ) : ?>
						<div class="sifency-portfolio-excerpt sifency-caption-style">
							<?php echo esc_html( $data['excerpt'] ); ?>
						</div>
					<?php endif; ?>

					<a href="<?php echo esc_url( $link_url ); ?>" class="sifency-heading-style"><?php echo esc_html( $data['title'] ); ?></a>
				</div>
				
				<?php if ( 'yes' === $settings['show_read_more'] ) : ?>
					<a href="<?php echo esc_url( $link_url ); ?>" class="sifency-pf-btn sifency-button-style">
						<?php
						if ( ! empty( $settings['read_more_text'] ) ) {
							echo '<span>' . esc_html( $settings['read_more_text'] ) . '</span>';}
						?>
						<?php echo wp_kses_post( $btn_icon_html ); ?>
					</a>
				<?php endif; ?>
			</div>

		<?php endif; ?>
		<?php
	}

	private function render_custom_content( $settings, Sifency_Addons_Animation_Manager $animation_manager ) {
		if ( empty( $settings['project_list'] ) ) {
			return; }

		$is_carousel  = ( 'carousel' === $settings['display_type'] && $settings['layout_style'] !== 'style-3' );
		$item_classes = $is_carousel ? array( 'swiper-slide' ) : array( 'sifency-portfolio-item' );

		foreach ( $settings['project_list'] as $index => $item ) {
			$oi           = $index + 1;
			$parity_class = ( $oi % 2 !== 0 ) ? 'odd-item' : 'even-item';

			$current_classes = $item_classes;
			if ( ! $is_carousel ) {
				$current_classes[] = $parity_class; }

			$attrs = $animation_manager->get_item_attributes( $current_classes );

			$img_html = ! empty( $item['image']['id'] ) ? Group_Control_Image_Size::get_attachment_image_html( $item, 'thumbnail', 'image' ) : '';

			$data = array(
				'title'      => $item['title'],
				'category'   => $item['category'],
				'link'       => $item['link'],
				'image_html' => $img_html,
			);
			?>
			<div <?php echo wp_kses_post( $attrs ); ?>>
				<?php if ( $is_carousel ) : ?>
					<div class="sifency-portfolio-item <?php echo esc_attr( $parity_class ); ?>">
				<?php endif; ?>
				
				<?php $this->render_item_inner( $settings, $data, $index ); ?>
				
				<?php if ( $is_carousel ) : ?>
					</div>
				<?php endif; ?>
			</div>
			<?php
		}
	}

	private function render_posts_content( $settings, $animation_manager, $query = null ) {
		if ( is_null( $query ) ) {
			$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'] ?? 'portfolio';
			$paged                   = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : ( ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1 );
			$query_args['paged']     = $paged;
			$query                   = new \WP_Query( $query_args );
		}

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

		$is_carousel = ( 'carousel' === $settings['display_type'] && $settings['layout_style'] !== 'style-3' );

		$item_classes = $is_carousel ? array( 'swiper-slide' ) : array( 'sifency-portfolio-item' );

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

			$current_classes = $item_classes;
			if ( ! $is_carousel ) {
				$current_classes[] = $parity_class; }

			$img_html  = get_the_post_thumbnail( get_the_ID(), $settings['thumbnail_size'] ?? 'large' );
			$cats      = get_the_terms( get_the_ID(), 'portfolio_category' );
			$cat_names = $cats && ! is_wp_error( $cats ) ? implode( ', ', wp_list_pluck( $cats, 'name' ) ) : '';

			$cat_classes     = $cats && ! is_wp_error( $cats ) ? array_map(
				function ( $term ) {
					return 'term-' . $term->term_id;
				},
				$cats
			) : array();
			$current_classes = array_merge( $current_classes, $cat_classes );

			$attrs = $animation_manager->get_item_attributes( $current_classes );

			$data = array(
				'title'      => get_the_title(),
				'category'   => $cat_names,
				'excerpt'    => get_the_excerpt(),
				'link'       => array( 'url' => get_permalink() ),
				'image_html' => $img_html,
			);
			?>
			<div <?php echo wp_kses_post( $attrs ); ?>>
				<?php if ( $is_carousel ) : ?>
					<div class="sifency-portfolio-item <?php echo esc_attr( $parity_class ); ?>">
				<?php endif; ?>
					
					<?php $this->render_item_inner( $settings, $data, $index ); ?>
				
				<?php if ( $is_carousel ) : ?>
					</div>
				<?php endif; ?>
			</div>
			<?php
		endwhile;
	}
}
