<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class Vista_Portfolio_Carousel_Widget extends \Elementor\Widget_Base {

	public function get_name()       { return 'vista-portfolio-carousel'; }
	public function get_title()      { return esc_html__( 'کاروسل نمونه کارها', 'vista' ); }
	public function get_icon()       { return 'eicon-post-slider'; }
	public function get_categories() { return [ 'vista-widgets' ]; }
	public function get_keywords()   { return [ 'portfolio', 'carousel', 'slider', 'swiper', 'نمونه کار', 'کاروسل', 'اسلایدر' ]; }
	public function get_script_depends() { return [ 'swiper', 'vista-widgets' ]; }
	public function get_style_depends()  { return [ 'swiper' ]; }
	public function is_dynamic_content(): bool { return true; }

	protected function register_controls() {

		$this->start_controls_section( 'section_query', [
			'label' => esc_html__( 'کوئری', 'vista' ),
			'tab'   => \Elementor\Controls_Manager::TAB_CONTENT,
		] );

		$this->add_control( 'posts_per_page', [
			'label'       => esc_html__( 'تعداد نمایش', 'vista' ),
			'type'        => \Elementor\Controls_Manager::NUMBER,
			'default'     => 8,
			'min'         => 0,
			'max'         => 999,
			'description' => esc_html__( 'عدد ۰ = نمایش همه موارد', 'vista' ),
		] );

		$portfolio_cats = [];
		$terms = get_terms( [ 'taxonomy' => 'portfolio_category', 'hide_empty' => false ] );
		if ( ! is_wp_error( $terms ) && $terms ) {
			foreach ( $terms as $term ) {
				$portfolio_cats[ $term->term_id ] = $term->name;
			}
		}

		$this->add_control( 'category', [
			'label'    => esc_html__( 'دسته‌بندی', 'vista' ),
			'type'     => \Elementor\Controls_Manager::SELECT2,
			'options'  => $portfolio_cats,
			'multiple' => true,
			'default'  => [],
		] );

		$this->add_control( 'orderby', [
			'label'   => esc_html__( 'مرتب‌سازی بر اساس', 'vista' ),
			'type'    => \Elementor\Controls_Manager::SELECT,
			'default' => 'date',
			'options' => [
				'date'       => esc_html__( 'تاریخ', 'vista' ),
				'title'      => esc_html__( 'عنوان', 'vista' ),
				'menu_order' => esc_html__( 'ترتیب منو', 'vista' ),
				'rand'       => esc_html__( 'تصادفی', 'vista' ),
			],
		] );

		$this->add_control( 'order', [
			'label'   => esc_html__( 'ترتیب', 'vista' ),
			'type'    => \Elementor\Controls_Manager::SELECT,
			'default' => 'DESC',
			'options' => [
				'DESC' => esc_html__( 'نزولی', 'vista' ),
				'ASC'  => esc_html__( 'صعودی', 'vista' ),
			],
		] );

		$this->end_controls_section();
		$this->start_controls_section( 'section_slider', [
			'label' => esc_html__( 'تنظیمات اسلایدر', 'vista' ),
			'tab'   => \Elementor\Controls_Manager::TAB_CONTENT,
		] );

		$this->add_control( 'slides_per_view', [
			'label'   => esc_html__( 'تعداد اسلاید در هر نما', 'vista' ),
			'type'    => \Elementor\Controls_Manager::SELECT,
			'default' => '3',
			'options' => [
				'1' => esc_html__( '۱ کارت', 'vista' ),
				'2' => esc_html__( '۲ کارت', 'vista' ),
				'3' => esc_html__( '۳ کارت', 'vista' ),
				'4' => esc_html__( '۴ کارت', 'vista' ),
			],
		] );

		$this->add_control( 'autoplay', [
			'label'   => esc_html__( 'پخش خودکار', 'vista' ),
			'type'    => \Elementor\Controls_Manager::SWITCHER,
			'default' => 'yes',
		] );

		$this->add_control( 'autoplay_speed', [
			'label'     => esc_html__( 'تأخیر پخش خودکار (ms)', 'vista' ),
			'type'      => \Elementor\Controls_Manager::NUMBER,
			'default'   => 4000,
			'min'       => 1000,
			'max'       => 10000,
			'condition' => [ 'autoplay' => 'yes' ],
		] );

		$this->add_control( 'show_arrows', [
			'label'     => esc_html__( 'نمایش فلش‌ها', 'vista' ),
			'type'      => \Elementor\Controls_Manager::SWITCHER,
			'default'   => 'yes',
			'separator' => 'before',
		] );

		$this->add_control( 'show_dots', [
			'label'   => esc_html__( 'نمایش نقاط (Dots)', 'vista' ),
			'type'    => \Elementor\Controls_Manager::SWITCHER,
			'default' => 'yes',
		] );

		$this->end_controls_section();
	}

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

		$ppp = intval( $settings['posts_per_page'] );

		$args = [
			'post_type'      => 'portfolio',
			'posts_per_page' => $ppp === 0 ? -1 : $ppp,
			'orderby'        => $settings['orderby'],
			'order'          => $settings['order'],
			'post_status'    => 'publish',
		];

		if ( ! empty( $settings['category'] ) ) {
			$args['tax_query'] = [ [
				'taxonomy' => 'portfolio_category',
				'field'    => 'term_id',
				'terms'    => array_map( 'intval', (array) $settings['category'] ),
			] ];
		}

		$query = new WP_Query( $args );

		if ( ! $query->have_posts() ) {
			if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				echo '<p style="text-align:center;padding:40px;color:var(--t2,#666);">' . esc_html__( 'هیچ نمونه کاری یافت نشد. لطفاً چند پروژه اضافه کنید.', 'vista' ) . '</p>';
			}
			wp_reset_postdata();
			return;
		}

		$spv       = intval( $settings['slides_per_view'] );
		$do_auto   = 'yes' === $settings['autoplay'] ? 'true' : 'false';
		$auto_spd  = intval( $settings['autoplay_speed'] );
		$show_arr  = 'yes' === $settings['show_arrows'];
		$show_dots = 'yes' === $settings['show_dots'];
		?>
		<div class="vista-pf-carousel-wrap"
		     data-spv="<?php echo esc_attr( $spv ); ?>"
		     data-autoplay="<?php echo esc_attr( $do_auto ); ?>"
		     data-speed="<?php echo esc_attr( $auto_spd ); ?>">

			<div class="pfc-stage">
				<div class="swiper pfc-swiper">
					<div class="swiper-wrapper">
						<?php while ( $query->have_posts() ) : $query->the_post();
							$tax_terms = get_the_terms( get_the_ID(), 'portfolio_category' );
							$cat_name  = ( $tax_terms && ! is_wp_error( $tax_terms ) ) ? $tax_terms[0]->name : '';
						?>
						<div class="swiper-slide">
							<div class="pf-card">
								<div class="pf-card-image">
									<?php if ( has_post_thumbnail() ) : ?>
										<a href="<?php the_permalink(); ?>">
											<?php the_post_thumbnail( 'vista-portfolio-thumb', [
												'alt'     => the_title_attribute( [ 'echo' => false ] ),
												'loading' => 'lazy',
											] ); ?>
										</a>
									<?php else : ?>
										<a href="<?php the_permalink(); ?>" class="pf-no-thumb">
											<i class="fa-solid fa-folder-open" aria-hidden="true"></i>
										</a>
									<?php endif; ?>

									<?php if ( $cat_name ) : ?>
										<span class="pf-badge"><?php echo esc_html( $cat_name ); ?></span>
									<?php endif; ?>
								</div>

								<div class="pf-card-footer">
									<div class="pf-card-text">
										<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
										<?php if ( has_excerpt() ) : ?>
											<p><?php echo esc_html( wp_trim_words( get_the_excerpt(), 10 ) ); ?></p>
										<?php endif; ?>
									</div>
									<a href="<?php the_permalink(); ?>" class="pf-action-btn" aria-label="<?php the_title_attribute(); ?>">
										<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" aria-hidden="true">
											<path d="M7 17L17 7M17 7H7M17 7v10"/>
										</svg>
									</a>
								</div>
							</div>
						</div>
						<?php endwhile; wp_reset_postdata(); ?>
					</div>
				</div>

				<?php if ( $show_arr || $show_dots ) : ?>
				<div class="test-controls pfc-controls">
					<?php if ( $show_arr ) : ?>
						<div class="tctl-btn swiper-button-prev pfc-prev"></div>
					<?php endif; ?>
					<?php if ( $show_dots ) : ?>
						<div class="tctl-dots pfc-dots"></div>
					<?php endif; ?>
					<?php if ( $show_arr ) : ?>
						<div class="tctl-btn swiper-button-next pfc-next"></div>
					<?php endif; ?>
				</div>
				<?php endif; ?>

			</div>
		</div>
		<?php
	}

	protected function content_template() {
		?>
		<#
		var spv = settings.slides_per_view || '3';
		var cnt = parseInt( settings.posts_per_page ) || 8;
		if ( cnt === 0 ) cnt = 8;
		#>
		<div class="vista-pf-carousel-wrap" data-spv="{{ spv }}" data-autoplay="false">
			<div class="pfc-stage">
				<div class="swiper pfc-swiper" style="overflow:hidden">
					<div class="swiper-wrapper" style="display:flex;gap:24px">
						<# for(var i=0;i<cnt;i++){ #>
						<div class="swiper-slide" style="min-width:calc(100%/{{ spv }} - 20px);flex-shrink:0">
							<div class="pf-card">
								<div class="pf-card-image pf-no-thumb" style="aspect-ratio:1/1;min-height:180px;display:flex;align-items:center;justify-content:center;background:var(--card2,#f4f7fb);border-radius:var(--r)">
									<i class="fa-solid fa-folder-open" style="font-size:36px;color:var(--t3,#7d95b0)"></i>
								</div>
								<div class="pf-card-footer">
									<div class="pf-card-text">
										<h3 style="font-size:15px;color:var(--t1,#0b1829)">نمونه کار {{ i+1 }}</h3>
									</div>
									<a href="#" class="pf-action-btn">
										<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M7 17L17 7M17 7H7M17 7v10"/></svg>
									</a>
								</div>
							</div>
						</div>
						<# } #>
					</div>
				</div>
				<div class="test-controls pfc-controls">
					<div class="tctl-btn swiper-button-prev pfc-prev"></div>
					<div class="tctl-dots pfc-dots"></div>
					<div class="tctl-btn swiper-button-next pfc-next"></div>
				</div>
			</div>
		</div>
		<?php
	}
}