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

class Vista_Blog_Carousel_Widget extends \Elementor\Widget_Base {

	public function get_name()       { return 'vista-blog-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 [ 'blog', 'carousel', 'slider', 'swiper', 'post', 'وبلاگ', 'مقاله', 'کاروسل', 'اسلایدر' ]; }
	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'     => 6,
			'min'         => 0,
			'max'         => 999,
			'description' => esc_html__( 'عدد ۰ = نمایش همه موارد', 'vista' ),
		] );

		$blog_cats = [];
		$cats = get_categories( [ 'hide_empty' => false ] );
		if ( $cats ) {
			foreach ( $cats as $cat ) {
				$blog_cats[ $cat->term_id ] = $cat->name;
			}
		}

		$this->add_control( 'category', [
			'label'    => esc_html__( 'دسته‌بندی', 'vista' ),
			'type'     => \Elementor\Controls_Manager::SELECT2,
			'options'  => $blog_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' ),
				'comment_count' => 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->add_control( 'read_more_text', [
			'label'       => esc_html__( 'متن دکمه ادامه', 'vista' ),
			'type'        => \Elementor\Controls_Manager::TEXT,
			'default'     => esc_html__( 'ادامه', 'vista' ),
			'label_block' => false,
		] );

		$this->add_control( 'show_read_time', [
			'label'        => esc_html__( 'نمایش زمان مطالعه', 'vista' ),
			'type'         => \Elementor\Controls_Manager::SWITCHER,
			'return_value' => 'yes',
			'default'      => 'yes',
		] );

		$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' ),
			],
		] );

		$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'      => 'post',
			'posts_per_page' => $ppp === 0 ? -1 : $ppp,
			'orderby'        => $settings['orderby'],
			'order'          => $settings['order'],
			'post_status'    => 'publish',
		];

		if ( ! empty( $settings['category'] ) ) {
			$args['cat'] = implode( ',', array_map( 'intval', (array) $settings['category'] ) );
		}

		$query     = new WP_Query( $args );
		$read_more = ! empty( $settings['read_more_text'] ) ? $settings['read_more_text'] : __( 'ادامه', 'vista' );
		$show_time = 'yes' === $settings['show_read_time'];
		$arrow_dir = is_rtl() ? 'left' : 'right';
		$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'];

		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;
		}
		?>
		<div class="vista-blog-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="blc-stage">
				<div class="swiper blc-swiper">
					<div class="swiper-wrapper">
						<?php while ( $query->have_posts() ) : $query->the_post();
							$categories = get_the_category();
						?>
						<div class="swiper-slide">
							<article id="post-<?php the_ID(); ?>" <?php post_class( 'blog-card' ); ?> aria-label="<?php the_title_attribute(); ?>">

								<div class="blog-card-thumb">
									<?php if ( has_post_thumbnail() ) : ?>
										<a href="<?php the_permalink(); ?>" tabindex="-1" aria-hidden="true">
											<?php the_post_thumbnail( 'vista-blog-card', [
												'loading' => 'lazy',
												'alt'     => the_title_attribute( [ 'echo' => false ] ),
											] ); ?>
										</a>
									<?php else : ?>
										<a href="<?php the_permalink(); ?>" tabindex="-1" aria-hidden="true">
											<i class="fa-solid fa-newspaper" style="font-size:36px;color:var(--t3);" aria-hidden="true"></i>
										</a>
									<?php endif; ?>

									<?php if ( $categories ) : ?>
										<a href="<?php echo esc_url( get_category_link( $categories[0]->term_id ) ); ?>" class="blog-card-cat">
											<?php echo esc_html( $categories[0]->name ); ?>
										</a>
									<?php endif; ?>
								</div>

								<div class="blog-card-body">
									<div class="blog-card-meta">
										<time datetime="<?php echo esc_attr( get_the_date( 'c' ) ); ?>">
											<?php echo esc_html( get_the_date() ); ?>
										</time>
										<span class="blog-card-meta-sep" aria-hidden="true"></span>
										<a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>">
											<?php the_author(); ?>
										</a>
									</div>

									<h2 class="blog-card-title">
										<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
									</h2>

									<div class="blog-card-excerpt">
										<?php echo esc_html( get_the_excerpt() ); ?>
									</div>

									<div class="blog-card-footer">
										<a href="<?php the_permalink(); ?>" class="blog-card-more">
											<?php echo esc_html( $read_more ); ?>
											<i class="fa-solid fa-arrow-<?php echo esc_attr( $arrow_dir ); ?>" aria-hidden="true"></i>
										</a>

										<?php if ( $show_time && function_exists( 'vista_reading_time' ) ) : ?>
											<div class="blog-card-read-time">
												<?php vista_reading_time( get_the_ID(), true ); ?>
											</div>
										<?php elseif ( $show_time ) : ?>
											<div class="blog-card-read-time">
												<?php
												$words   = str_word_count( strip_tags( get_the_content() ) );
												$minutes = max( 1, ceil( $words / 200 ) );
												printf( esc_html__( '%d دقیقه مطالعه', 'vista' ), $minutes );
												?>
											</div>
										<?php endif; ?>
									</div>
								</div>

							</article>
						</div>
						<?php endwhile; wp_reset_postdata(); ?>
					</div>
				</div>
				<?php if ( $show_arr || $show_dots ) : ?>
				<div class="test-controls blc-controls">
					<?php if ( $show_arr ) : ?>
						<div class="tctl-btn swiper-button-prev blc-prev"></div>
					<?php endif; ?>
					<?php if ( $show_dots ) : ?>
						<div class="tctl-dots blc-dots"></div>
					<?php endif; ?>
					<?php if ( $show_arr ) : ?>
						<div class="tctl-btn swiper-button-next blc-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 ) || 6;
		if ( cnt === 0 ) cnt = 6;
		#>
		<div class="vista-blog-carousel-wrap" data-spv="{{ spv }}" data-autoplay="false">
			<div class="blc-stage">
				<div class="swiper blc-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">
							<article class="blog-card on">
								<div class="blog-card-thumb" style="display:flex;align-items:center;justify-content:center;min-height:180px;background:var(--card2,#f4f7fb)">
									<i class="fa-solid fa-newspaper" style="font-size:36px;color:var(--t3,#7d95b0)"></i>
								</div>
								<div class="blog-card-body">
									<div class="blog-card-meta" style="font-size:11px;color:var(--t3)">
										<span>۱ فروردین ۱۴۰۴</span>
									</div>
									<h2 class="blog-card-title"><a href="#">عنوان مطلب {{ i+1 }}</a></h2>
									<div class="blog-card-excerpt" style="font-size:13px;color:var(--t2)">خلاصه مطلب اینجا نمایش داده می‌شود...</div>
									<div class="blog-card-footer">
										<a href="#" class="blog-card-more">{{ settings.read_more_text || 'ادامه' }} <i class="fa-solid fa-arrow-left"></i></a>
									</div>
								</div>
							</article>
						</div>
						<# } #>
					</div>
				</div>
				<div class="test-controls blc-controls">
					<div class="tctl-btn swiper-button-prev blc-prev"></div>
					<div class="tctl-dots blc-dots"></div>
					<div class="tctl-btn swiper-button-next blc-next"></div>
				</div>
			</div>
		</div>
		<?php
	}
}